Skip to content

A programming framework for agentic AI

Add isort (#2265)

Li Jiang42b27b9a9d24
diff --git a/autogen/__init__.py b/autogen/__init__.py
index ba920c92e..02f956c4b 100644
--- a/autogen/__init__.py
+++ b/autogen/__init__.py
@@ -1,10 +1,10 @@
import logging
-from .version import __version__
-from .oai import *
+
from .agentchat import *
-from .exception_utils import *
from .code_utils import DEFAULT_MODEL, FAST_MODEL
-
+from .exception_utils import *
+from .oai import *
+from .version import __version__
# Set the root logger.
logger = logging.getLogger(__name__)
diff --git a/autogen/agentchat/__init__.py b/autogen/agentchat/__init__.py
index 817fc8abd..d31a59d98 100644
--- a/autogen/agentchat/__init__.py
+++ b/autogen/agentchat/__init__.py
@@ -1,9 +1,9 @@
from .agent import Agent
from .assistant_agent import AssistantAgent
+from .chat import ChatResult, initiate_chats
from .conversable_agent import ConversableAgent, register_function
from .groupchat import GroupChat, GroupChatManager
from .user_proxy_agent import UserProxyAgent
-from .chat import initiate_chats, ChatResult
from .utils import gather_usage_summary
__all__ = (
diff --git a/autogen/agentchat/assistant_agent.py b/autogen/agentchat/assistant_agent.py
index 25f7edbf0..b5ec7de90 100644
--- a/autogen/agentchat/assistant_agent.py
+++ b/autogen/agentchat/assistant_agent.py
@@ -1,7 +1,8 @@
from typing import Callable, Dict, Literal, Optional, Union
+from autogen.runtime_logging import log_new_agent, logging_enabled
+
from .conversable_agent import ConversableAgent
-from autogen.runtime_logging import logging_enabled, log_new_agent
class AssistantAgent(ConversableAgent):
diff --git a/autogen/agentchat/chat.py b/autogen/agentchat/chat.py
index 347f58bfc..a07f3302a 100644
--- a/autogen/agentchat/chat.py
+++ b/autogen/agentchat/chat.py
@@ -1,15 +1,15 @@
import asyncio
-from functools import partial
-import logging
-from collections import defaultdict, abc
-from typing import Dict, List, Any, Set, Tuple
-from dataclasses import dataclass
-from .utils import consolidate_chat_info
import datetime
+import logging
import warnings
-from ..io.base import IOStream
-from ..formatting_utils import colored
+from collections import abc, defaultdict
+from dataclasses import dataclass
+from functools import partial
+from typing import Any, Dict, List, Set, Tuple
+from ..formatting_utils import colored
+from ..io.base import IOStream
+from .utils import consolidate_chat_info
logger = logging.getLogger(__name__)
Prerequisite = Tuple[int, int]
diff --git a/autogen/agentchat/contrib/agent_builder.py b/autogen/agentchat/contrib/agent_builder.py
index 7a3850d79..a257a6dcf 100644
--- a/autogen/agentchat/contrib/agent_builder.py
+++ b/autogen/agentchat/contrib/agent_builder.py
@@ -1,10 +1,11 @@
-import autogen
-import time
-import subprocess as sp
-import socket
-import json
import hashlib
-from typing import Optional, List, Dict, Tuple
+import json
+import socket
+import subprocess as sp
+import time
+from typing import Dict, List, Optional, Tuple
+
+import autogen
def _config_check(config: Dict):
diff --git a/autogen/agentchat/contrib/agent_optimizer.py b/autogen/agentchat/contrib/agent_optimizer.py
index 711874efc..68c341089 100644
--- a/autogen/agentchat/contrib/agent_optimizer.py
+++ b/autogen/agentchat/contrib/agent_optimizer.py
@@ -1,8 +1,9 @@
-from autogen.code_utils import execute_code
-from typing import List, Dict, Optional
-import json
import copy
+import json
+from typing import Dict, List, Optional
+
import autogen
+from autogen.code_utils import execute_code
ADD_FUNC = {
"type": "function",
diff --git a/autogen/agentchat/contrib/capabilities/generate_images.py b/autogen/agentchat/contrib/capabilities/generate_images.py
index d16121ddb..e4a8f1195 100644
--- a/autogen/agentchat/contrib/capabilities/generate_images.py
+++ b/autogen/agentchat/contrib/capabilities/generate_images.py
@@ -5,10 +5,10 @@ from openai import OpenAI
from PIL.Image import Image
from autogen import Agent, ConversableAgent, code_utils
-from autogen.cache import AbstractCache
from autogen.agentchat.contrib import img_utils
from autogen.agentchat.contrib.capabilities.agent_capability import AgentCapability
from autogen.agentchat.contrib.text_analyzer_agent import TextAnalyzerAgent
+from autogen.cache import AbstractCache
SYSTEM_MESSAGE = "You've been given the special ability to generate images."
DESCRIPTION_MESSAGE = "This agent has the ability to generate images."
diff --git a/autogen/agentchat/contrib/capabilities/teachability.py b/autogen/agentchat/contrib/capabilities/teachability.py
index 58ba35ed4..3a64f0619 100644
--- a/autogen/agentchat/contrib/capabilities/teachability.py
+++ b/autogen/agentchat/contrib/capabilities/teachability.py
@@ -1,11 +1,14 @@
import os
+import pickle
from typing import Dict, Optional, Union
+
import chromadb
from chromadb.config import Settings
-import pickle
+
from autogen.agentchat.assistant_agent import ConversableAgent
from autogen.agentchat.contrib.capabilities.agent_capability import AgentCapability
from autogen.agentchat.contrib.text_analyzer_agent import TextAnalyzerAgent
+
from ....formatting_utils import colored
diff --git a/autogen/agentchat/contrib/capabilities/transform_messages.py b/autogen/agentchat/contrib/capabilities/transform_messages.py
index db12fe688..46c8d4e0a 100644
--- a/autogen/agentchat/contrib/capabilities/transform_messages.py
+++ b/autogen/agentchat/contrib/capabilities/transform_messages.py
@@ -4,6 +4,7 @@ from typing import Dict, List
from termcolor import colored
from autogen import ConversableAgent
+
from .transforms import MessageTransform
diff --git a/autogen/agentchat/contrib/compressible_agent.py b/autogen/agentchat/contrib/compressible_agent.py
index 152cc871a..0b15d482d 100644
--- a/autogen/agentchat/contrib/compressible_agent.py
+++ b/autogen/agentchat/contrib/compressible_agent.py
@@ -1,10 +1,10 @@
-from typing import Callable, Dict, Optional, Union, Tuple, List, Any
-from autogen import OpenAIWrapper
-from autogen import Agent, ConversableAgent
-import copy
import asyncio
-import logging
+import copy
import inspect
+import logging
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+from autogen import Agent, ConversableAgent, OpenAIWrapper
from autogen.token_count_utils import count_token, get_max_token_limit, num_tokens_from_functions
from ...formatting_utils import colored
diff --git a/autogen/agentchat/contrib/gpt_assistant_agent.py b/autogen/agentchat/contrib/gpt_assistant_agent.py
index 20acd2b08..253d4d18e 100644
--- a/autogen/agentchat/contrib/gpt_assistant_agent.py
+++ b/autogen/agentchat/contrib/gpt_assistant_agent.py
@@ -1,16 +1,16 @@
-from collections import defaultdict
-import openai
+import copy
import json
-import time
import logging
-import copy
+import time
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import openai
from autogen import OpenAIWrapper
-from autogen.oai.openai_utils import retrieve_assistants_by_name
from autogen.agentchat.agent import Agent
-from autogen.agentchat.assistant_agent import ConversableAgent
-from autogen.agentchat.assistant_agent import AssistantAgent
-from typing import Dict, Optional, Union, List, Tuple, Any
+from autogen.agentchat.assistant_agent import AssistantAgent, ConversableAgent
+from autogen.oai.openai_utils import retrieve_assistants_by_name
logger = logging.getLogger(__name__)
diff --git a/autogen/agentchat/contrib/llava_agent.py b/autogen/agentchat/contrib/llava_agent.py
index 182f72837..063b256d3 100644
--- a/autogen/agentchat/contrib/llava_agent.py
+++ b/autogen/agentchat/contrib/llava_agent.py
@@ -1,6 +1,7 @@
import json
import logging
from typing import List, Optional, Tuple
+
import replicate
import requests
@@ -8,8 +9,8 @@ from autogen.agentchat.agent import Agent
from autogen.agentchat.contrib.img_utils import get_image_data, llava_formatter
from autogen.agentchat.contrib.multimodal_conversable_agent import MultimodalConversableAgent
from autogen.code_utils import content_str
-from ...formatting_utils import colored
+from ...formatting_utils import colored
logger = logging.getLogger(__name__)
diff --git a/autogen/agentchat/contrib/math_user_proxy_agent.py b/autogen/agentchat/contrib/math_user_proxy_agent.py
index 70f365ef9..d2b6b7cde 100644
--- a/autogen/agentchat/contrib/math_user_proxy_agent.py
+++ b/autogen/agentchat/contrib/math_user_proxy_agent.py
@@ -1,15 +1,15 @@
-import re
import os
-from pydantic import BaseModel, Extra, root_validator
-from typing import Any, Callable, Dict, List, Optional, Union, Tuple
+import re
from time import sleep
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+from pydantic import BaseModel, Extra, root_validator
from autogen._pydantic import PYDANTIC_V1
from autogen.agentchat import Agent, UserProxyAgent
-from autogen.code_utils import UNKNOWN, extract_code, execute_code, infer_lang
+from autogen.code_utils import UNKNOWN, execute_code, extract_code, infer_lang
from autogen.math_utils import get_answer
-
PROMPTS = {
# default
"default": """Let's use Python to solve a math problem.
diff --git a/autogen/agentchat/contrib/multimodal_conversable_agent.py b/autogen/agentchat/contrib/multimodal_conversable_agent.py
index 2a016bcff..edeb88cd5 100644
--- a/autogen/agentchat/contrib/multimodal_conversable_agent.py
+++ b/autogen/agentchat/contrib/multimodal_conversable_agent.py
@@ -11,7 +11,6 @@ from autogen.code_utils import content_str
from ..._pydantic import model_dump
-
DEFAULT_LMM_SYS_MSG = """You are a helpful AI assistant."""
DEFAULT_MODEL = "gpt-4-vision-preview"
diff --git a/autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py b/autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py
index c539c716a..3f5278c5f 100644
--- a/autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py
+++ b/autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py
@@ -1,15 +1,15 @@
+import logging
from typing import Callable, Dict, List, Optional
from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent
-from autogen.retrieve_utils import get_files_from_dir, split_files_to_chunks, TEXT_FORMATS
-import logging
+from autogen.retrieve_utils import TEXT_FORMATS, get_files_from_dir, split_files_to_chunks
logger = logging.getLogger(__name__)
try:
+ import fastembed
from qdrant_client import QdrantClient, models
from qdrant_client.fastembed_common import QueryResponse
- import fastembed
except ImportError as e:
logging.fatal("Failed to import qdrant_client with fastembed. Try running 'pip install qdrant_client[fastembed]'")
raise e
diff --git a/autogen/agentchat/contrib/retrieve_assistant_agent.py b/autogen/agentchat/contrib/retrieve_assistant_agent.py
index a09677710..9b5ace200 100644
--- a/autogen/agentchat/contrib/retrieve_assistant_agent.py
+++ b/autogen/agentchat/contrib/retrieve_assistant_agent.py
@@ -1,6 +1,7 @@
+from typing import Any, Dict, List, Optional, Tuple, Union
+
from autogen.agentchat.agent import Agent
from autogen.agentchat.assistant_agent import AssistantAgent
-from typing import Dict, Optional, Union, List, Tuple, Any
class RetrieveAssistantAgent(AssistantAgent):
diff --git a/autogen/agentchat/contrib/retrieve_user_proxy_agent.py b/autogen/agentchat/contrib/retrieve_user_proxy_agent.py
index 68bb73027..ddc70e063 100644
--- a/autogen/agentchat/contrib/retrieve_user_proxy_agent.py
+++ b/autogen/agentchat/contrib/retrieve_user_proxy_agent.py
@@ -1,19 +1,20 @@
import re
-from typing import Callable, Dict, Optional, Union, List, Tuple, Any
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
from IPython import get_ipython
try:
import chromadb
except ImportError:
raise ImportError("Please install dependencies first. `pip install pyautogen[retrievechat]`")
-from autogen.agentchat.agent import Agent
+from autogen import logger
from autogen.agentchat import UserProxyAgent
-from autogen.retrieve_utils import create_vector_db_from_dir, query_vector_db, TEXT_FORMATS
-from autogen.token_count_utils import count_token
+from autogen.agentchat.agent import Agent
from autogen.code_utils import extract_code
-from autogen import logger
-from ...formatting_utils import colored
+from autogen.retrieve_utils import TEXT_FORMATS, create_vector_db_from_dir, query_vector_db
+from autogen.token_count_utils import count_token
+from ...formatting_utils import colored
PROMPT_DEFAULT = """You're a retrieve augmented chatbot. You answer user's questions based on your own knowledge and the
context provided by the user. You should follow the following steps to answer a question:
diff --git a/autogen/agentchat/contrib/society_of_mind_agent.py b/autogen/agentchat/contrib/society_of_mind_agent.py
index 6a6f4aa21..97cf6aee1 100644
--- a/autogen/agentchat/contrib/society_of_mind_agent.py
+++ b/autogen/agentchat/contrib/society_of_mind_agent.py
@@ -1,10 +1,11 @@
# ruff: noqa: E722
+import copy
import json
import traceback
-import copy
from dataclasses import dataclass
-from typing import Dict, List, Optional, Union, Callable, Literal, Tuple
-from autogen import Agent, ConversableAgent, GroupChatManager, GroupChat, OpenAIWrapper
+from typing import Callable, Dict, List, Literal, Optional, Tuple, Union
+
+from autogen import Agent, ConversableAgent, GroupChat, GroupChatManager, OpenAIWrapper
class SocietyOfMindAgent(ConversableAgent):
diff --git a/autogen/agentchat/contrib/text_analyzer_agent.py b/autogen/agentchat/contrib/text_analyzer_agent.py
index 10100c9e5..e917cca57 100644
--- a/autogen/agentchat/contrib/text_analyzer_agent.py
+++ b/autogen/agentchat/contrib/text_analyzer_agent.py
@@ -1,7 +1,8 @@
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
from autogen import oai
from autogen.agentchat.agent import Agent
from autogen.agentchat.assistant_agent import ConversableAgent
-from typing import Callable, Dict, Optional, Union, List, Tuple, Any
system_message = """You are an expert in text analysis.
The user will give you TEXT to analyze.
diff --git a/autogen/agentchat/contrib/web_surfer.py b/autogen/agentchat/contrib/web_surfer.py
index 6cd71dc63..1a54aeebe 100644
--- a/autogen/agentchat/contrib/web_surfer.py
+++ b/autogen/agentchat/contrib/web_surfer.py
@@ -1,16 +1,18 @@
-import json
import copy
+import json
import logging
import re
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional, Union, Callable, Literal, Tuple
+from datetime import datetime
+from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
+
from typing_extensions import Annotated
-from ... import Agent, ConversableAgent, AssistantAgent, UserProxyAgent, GroupChatManager, GroupChat, OpenAIWrapper
+
+from ... import Agent, AssistantAgent, ConversableAgent, GroupChat, GroupChatManager, OpenAIWrapper, UserProxyAgent
from ...browser_utils import SimpleTextBrowser
from ...code_utils import content_str
-from datetime import datetime
-from ...token_count_utils import count_token, get_max_token_limit
from ...oai.openai_utils import filter_config
+from ...token_count_utils import count_token, get_max_token_limit
logger = logging.getLogger(__name__)
diff --git a/autogen/agentchat/conversable_agent.py b/autogen/agentchat/conversable_agent.py
index 2ca06e2fe..a2f021f57 100644
--- a/autogen/agentchat/conversable_agent.py
+++ b/autogen/agentchat/conversable_agent.py
@@ -29,10 +29,10 @@ from ..coding.base import CodeExecutor
from ..coding.factory import CodeExecutorFactory
from ..formatting_utils import colored
from ..function_utils import get_function_schema, load_basemodels_if_needed, serialize_to_str
+from ..io.base import IOStream
from ..oai.client import ModelClient, OpenAIWrapper
from ..runtime_logging import log_new_agent, logging_enabled
from .agent import Agent, LLMAgent
-from ..io.base import IOStream
from .chat import ChatResult, a_initiate_chats, initiate_chats
from .utils import consolidate_chat_info, gather_usage_summary
diff --git a/autogen/agentchat/groupchat.py b/autogen/agentchat/groupchat.py
index 9990f8067..f5b610686 100644
--- a/autogen/agentchat/groupchat.py
+++ b/autogen/agentchat/groupchat.py
@@ -5,13 +5,13 @@ import sys
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Literal, Optional, Tuple, Union
-from .agent import Agent
-from .conversable_agent import ConversableAgent
-from ..io.base import IOStream
from ..code_utils import content_str
from ..exception_utils import AgentNameConflict, NoEligibleSpeaker, UndefinedNextAgent
from ..graph_utils import check_graph_validity, invert_disallowed_to_allowed
+from ..io.base import IOStream
from ..runtime_logging import log_new_agent, logging_enabled
+from .agent import Agent
+from .conversable_agent import ConversableAgent
logger = logging.getLogger(__name__)
diff --git a/autogen/agentchat/user_proxy_agent.py b/autogen/agentchat/user_proxy_agent.py
index d1d7f89ab..a80296a83 100644
--- a/autogen/agentchat/user_proxy_agent.py
+++ b/autogen/agentchat/user_proxy_agent.py
@@ -1,7 +1,7 @@
from typing import Callable, Dict, List, Literal, Optional, Union
+from ..runtime_logging import log_new_agent, logging_enabled
from .conversable_agent import ConversableAgent
-from ..runtime_logging import logging_enabled, log_new_agent
class UserProxyAgent(ConversableAgent):
diff --git a/autogen/browser_utils.py b/autogen/browser_utils.py
index 41d2d62f8..c6ccbba38 100644
--- a/autogen/browser_utils.py
+++ b/autogen/browser_utils.py
@@ -1,14 +1,15 @@
+import io
import json
+import mimetypes
import os
-import requests
import re
-import markdownify
-import io
import uuid
-import mimetypes
+from typing import Any, Dict, List, Optional, Tuple, Union
from urllib.parse import urljoin, urlparse
+
+import markdownify
+import requests
from bs4 import BeautifulSoup
-from typing import Any, Dict, List, Optional, Union, Tuple
# Optional PDF support
IS_PDF_CAPABLE = False
diff --git a/autogen/cache/abstract_cache_base.py b/autogen/cache/abstract_cache_base.py
index ebf1cecfa..cfe501083 100644
--- a/autogen/cache/abstract_cache_base.py
+++ b/autogen/cache/abstract_cache_base.py
@@ -1,6 +1,6 @@
+import sys
from types import TracebackType
from typing import Any, Optional, Protocol, Type
-import sys
if sys.version_info >= (3, 11):
from typing import Self
diff --git a/autogen/cache/cache.py b/autogen/cache/cache.py
index 31bbfa135..0770079f2 100644
--- a/autogen/cache/cache.py
+++ b/autogen/cache/cache.py
@@ -1,13 +1,12 @@
from __future__ import annotations
+
+import sys
from types import TracebackType
-from typing import Dict, Any, Optional, Type, Union
+from typing import Any, Dict, Optional, Type, Union
from .abstract_cache_base import AbstractCache
-
from .cache_factory import CacheFactory
-import sys
-
if sys.version_info >= (3, 11):
from typing import Self
else:
diff --git a/autogen/cache/cache_factory.py b/autogen/cache/cache_factory.py
index e3c50e9eb..8fc4713f0 100644
--- a/autogen/cache/cache_factory.py
+++ b/autogen/cache/cache_factory.py
@@ -1,9 +1,9 @@
+import logging
from typing import Optional, Union
+
from .abstract_cache_base import AbstractCache
from .disk_cache import DiskCache
-import logging
-
class CacheFactory:
@staticmethod
diff --git a/autogen/cache/disk_cache.py b/autogen/cache/disk_cache.py
index 2cca53e6d..7c68e7e90 100644
--- a/autogen/cache/disk_cache.py
+++ b/autogen/cache/disk_cache.py
@@ -1,8 +1,10 @@
+import sys
from types import TracebackType
from typing import Any, Optional, Type, Union
+
import diskcache
+
from .abstract_cache_base import AbstractCache
-import sys
if sys.version_info >= (3, 11):
from typing import Self
diff --git a/autogen/cache/in_memory_cache.py b/autogen/cache/in_memory_cache.py
index cc14e5c18..b79f9ecfa 100644
--- a/autogen/cache/in_memory_cache.py
+++ b/autogen/cache/in_memory_cache.py
@@ -1,6 +1,7 @@
+import sys
from types import TracebackType
from typing import Any, Dict, Optional, Type, Union
-import sys
+
from .abstract_cache_base import AbstractCache
if sys.version_info >= (3, 11):
diff --git a/autogen/cache/redis_cache.py b/autogen/cache/redis_cache.py
index d125d3ba2..36d601af7 100644
--- a/autogen/cache/redis_cache.py
+++ b/autogen/cache/redis_cache.py
@@ -1,8 +1,10 @@
import pickle
+import sys
from types import TracebackType
from typing import Any, Optional, Type, Union
+
import redis
-import sys
+
from .abstract_cache_base import AbstractCache
if sys.version_info >= (3, 11):
diff --git a/autogen/code_utils.py b/autogen/code_utils.py
index 57a817855..d4b2ae99c 100644
--- a/autogen/code_utils.py
+++ b/autogen/code_utils.py
@@ -10,10 +10,10 @@ from concurrent.futures import ThreadPoolExecutor, TimeoutError
from hashlib import md5
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
-from autogen import oai
-
import docker
+from autogen import oai
+
from .types import UserMessageImageContentPart, UserMessageTextContentPart
SENTINEL = object()
diff --git a/autogen/coding/__init__.py b/autogen/coding/__init__.py
index 2ba4e9b07..2f53b88ca 100644
--- a/autogen/coding/__init__.py
+++ b/autogen/coding/__init__.py
@@ -1,8 +1,8 @@
from .base import CodeBlock, CodeExecutor, CodeExtractor, CodeResult
+from .docker_commandline_code_executor import DockerCommandLineCodeExecutor
from .factory import CodeExecutorFactory
-from .markdown_code_extractor import MarkdownCodeExtractor
from .local_commandline_code_executor import LocalCommandLineCodeExecutor
-from .docker_commandline_code_executor import DockerCommandLineCodeExecutor
+from .markdown_code_extractor import MarkdownCodeExtractor
__all__ = (
"CodeBlock",
diff --git a/autogen/coding/base.py b/autogen/coding/base.py
index f60ff0de8..ccbfe6b92 100644
--- a/autogen/coding/base.py
+++ b/autogen/coding/base.py
@@ -1,4 +1,5 @@
from __future__ import annotations
+
from typing import Any, List, Literal, Mapping, Optional, Protocol, TypedDict, Union, runtime_checkable
from pydantic import BaseModel, Field
diff --git a/autogen/coding/docker_commandline_code_executor.py b/autogen/coding/docker_commandline_code_executor.py
index 8d8931a83..143b241c2 100644
--- a/autogen/coding/docker_commandline_code_executor.py
+++ b/autogen/coding/docker_commandline_code_executor.py
@@ -1,22 +1,22 @@
from __future__ import annotations
+
import atexit
-from hashlib import md5
import logging
+import sys
+import uuid
+from hashlib import md5
from pathlib import Path
from time import sleep
from types import TracebackType
-import uuid
from typing import Any, List, Optional, Type, Union
+
import docker
from docker.errors import ImageNotFound
-from .utils import _get_file_name_from_content, silence_pip
-from .base import CommandLineCodeResult
-
from ..code_utils import TIMEOUT_MSG, _cmd
-from .base import CodeBlock, CodeExecutor, CodeExtractor
+from .base import CodeBlock, CodeExecutor, CodeExtractor, CommandLineCodeResult
from .markdown_code_extractor import MarkdownCodeExtractor
-import sys
+from .utils import _get_file_name_from_content, silence_pip
if sys.version_info >= (3, 11):
from typing import Self
diff --git a/autogen/coding/factory.py b/autogen/coding/factory.py
index 0c2d41b89..b484d99cd 100644
--- a/autogen/coding/factory.py
+++ b/autogen/coding/factory.py
@@ -1,4 +1,4 @@
-from .base import CodeExecutor, CodeExecutionConfig
+from .base import CodeExecutionConfig, CodeExecutor
__all__ = ("CodeExecutorFactory",)
diff --git a/autogen/coding/func_with_reqs.py b/autogen/coding/func_with_reqs.py
index 21e415d1f..6f1995738 100644
--- a/autogen/coding/func_with_reqs.py
+++ b/autogen/coding/func_with_reqs.py
@@ -1,12 +1,14 @@
from __future__ import annotations
-import inspect
+
import functools
-from typing import Any, Callable, List, TypeVar, Generic, Union
-from typing_extensions import ParamSpec
-from textwrap import indent, dedent
+import importlib
+import inspect
from dataclasses import dataclass, field
from importlib.abc import SourceLoader
-import importlib
+from textwrap import dedent, indent
+from typing import Any, Callable, Generic, List, TypeVar, Union
+
+from typing_extensions import ParamSpec
T = TypeVar("T")
P = ParamSpec("P")
diff --git a/autogen/coding/jupyter/__init__.py b/autogen/coding/jupyter/__init__.py
index 5c1a9607f..f6f02313e 100644
--- a/autogen/coding/jupyter/__init__.py
+++ b/autogen/coding/jupyter/__init__.py
@@ -1,9 +1,9 @@
from .base import JupyterConnectable, JupyterConnectionInfo
-from .jupyter_client import JupyterClient
-from .local_jupyter_server import LocalJupyterServer
from .docker_jupyter_server import DockerJupyterServer
from .embedded_ipython_code_executor import EmbeddedIPythonCodeExecutor
+from .jupyter_client import JupyterClient
from .jupyter_code_executor import JupyterCodeExecutor
+from .local_jupyter_server import LocalJupyterServer
__all__ = [
"JupyterConnectable",
diff --git a/autogen/coding/jupyter/docker_jupyter_server.py b/autogen/coding/jupyter/docker_jupyter_server.py
index 3b9462186..83455e272 100644
--- a/autogen/coding/jupyter/docker_jupyter_server.py
+++ b/autogen/coding/jupyter/docker_jupyter_server.py
@@ -1,15 +1,16 @@
from __future__ import annotations
-from pathlib import Path
+import atexit
+import io
+import logging
+import secrets
import sys
-from types import TracebackType
import uuid
+from pathlib import Path
+from types import TracebackType
from typing import Dict, Optional, Type, Union
+
import docker
-import secrets
-import io
-import atexit
-import logging
from ..docker_commandline_code_executor import _wait_for_ready
@@ -19,8 +20,8 @@ else:
from typing_extensions import Self
-from .jupyter_client import JupyterClient
from .base import JupyterConnectable, JupyterConnectionInfo
+from .jupyter_client import JupyterClient
class DockerJupyterServer(JupyterConnectable):
diff --git a/autogen/coding/jupyter/embedded_ipython_code_executor.py b/autogen/coding/jupyter/embedded_ipython_code_executor.py
index 0d647082a..f9200c7a5 100644
--- a/autogen/coding/jupyter/embedded_ipython_code_executor.py
+++ b/autogen/coding/jupyter/embedded_ipython_code_executor.py
@@ -1,9 +1,9 @@
import base64
import json
import os
-from pathlib import Path
import re
import uuid
+from pathlib import Path
from queue import Empty
from typing import Any, ClassVar, List
diff --git a/autogen/coding/jupyter/jupyter_client.py b/autogen/coding/jupyter/jupyter_client.py
index 8f97ab824..44aafd8f5 100644
--- a/autogen/coding/jupyter/jupyter_client.py
+++ b/autogen/coding/jupyter/jupyter_client.py
@@ -1,22 +1,22 @@
from __future__ import annotations
+import sys
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Dict, List, Optional, Type, cast
-import sys
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
+import datetime
import json
import uuid
-import datetime
-import requests
-from requests.adapters import HTTPAdapter, Retry
+import requests
import websocket
+from requests.adapters import HTTPAdapter, Retry
from websocket import WebSocket
from .base import JupyterConnectionInfo
diff --git a/autogen/coding/jupyter/jupyter_code_executor.py b/autogen/coding/jupyter/jupyter_code_executor.py
index 4d9267735..833565ab4 100644
--- a/autogen/coding/jupyter/jupyter_code_executor.py
+++ b/autogen/coding/jupyter/jupyter_code_executor.py
@@ -1,12 +1,12 @@
import base64
import json
import os
-from pathlib import Path
import re
-from types import TracebackType
+import sys
import uuid
+from pathlib import Path
+from types import TracebackType
from typing import Any, ClassVar, List, Optional, Type, Union
-import sys
from autogen.coding.utils import silence_pip
diff --git a/autogen/coding/jupyter/local_jupyter_server.py b/autogen/coding/jupyter/local_jupyter_server.py
index 0709f55ee..9b8923038 100644
--- a/autogen/coding/jupyter/local_jupyter_server.py
+++ b/autogen/coding/jupyter/local_jupyter_server.py
@@ -1,14 +1,14 @@
from __future__ import annotations
-from types import TracebackType
-from typing import Optional, Type, Union, cast
-import subprocess
-import signal
-import sys
+import atexit
import json
import secrets
+import signal
import socket
-import atexit
+import subprocess
+import sys
+from types import TracebackType
+from typing import Optional, Type, Union, cast
if sys.version_info >= (3, 11):
from typing import Self
diff --git a/autogen/coding/local_commandline_code_executor.py b/autogen/coding/local_commandline_code_executor.py
index e012b3226..44ba85926 100644
--- a/autogen/coding/local_commandline_code_executor.py
+++ b/autogen/coding/local_commandline_code_executor.py
@@ -1,11 +1,15 @@
-from hashlib import md5
-from pathlib import Path
+import logging
import re
-from string import Template
+import subprocess
import sys
import warnings
+from hashlib import md5
+from pathlib import Path
+from string import Template
from typing import Any, Callable, ClassVar, List, TypeVar, Union, cast
+
from typing_extensions import ParamSpec
+
from autogen.coding.func_with_reqs import (
FunctionWithRequirements,
FunctionWithRequirementsStr,
@@ -16,13 +20,8 @@ from autogen.coding.func_with_reqs import (
from ..code_utils import TIMEOUT_MSG, WIN32, _cmd
from .base import CodeBlock, CodeExecutor, CodeExtractor, CommandLineCodeResult
from .markdown_code_extractor import MarkdownCodeExtractor
-
from .utils import _get_file_name_from_content, silence_pip
-import subprocess
-
-import logging
-
__all__ = ("LocalCommandLineCodeExecutor",)
A = ParamSpec("A")
diff --git a/autogen/coding/markdown_code_extractor.py b/autogen/coding/markdown_code_extractor.py
index 58ad4a09e..7a1084194 100644
--- a/autogen/coding/markdown_code_extractor.py
+++ b/autogen/coding/markdown_code_extractor.py
@@ -2,8 +2,8 @@ import re
from typing import Any, Dict, List, Optional, Union
from ..code_utils import CODE_BLOCK_PATTERN, UNKNOWN, content_str, infer_lang
-from .base import CodeBlock, CodeExtractor
from ..types import UserMessageImageContentPart, UserMessageTextContentPart
+from .base import CodeBlock, CodeExtractor
__all__ = ("MarkdownCodeExtractor",)
diff --git a/autogen/graph_utils.py b/autogen/graph_utils.py
index a84fc89f9..88c218fde 100644
--- a/autogen/graph_utils.py
+++ b/autogen/graph_utils.py
@@ -1,7 +1,7 @@
-from typing import Dict, List
import logging
+from typing import Dict, List
-from autogen.agentchat.groupchat import Agent
+from autogen.agentchat import Agent
def has_self_loops(allowed_speaker_transitions: Dict) -> bool:
@@ -115,8 +115,8 @@ def visualize_speaker_transitions_dict(speaker_transitions_dict: dict, agents: L
Visualize the speaker_transitions_dict using networkx.
"""
try:
- import networkx as nx
import matplotlib.pyplot as plt
+ import networkx as nx
except ImportError as e:
logging.fatal("Failed to import networkx or matplotlib. Try running 'pip install autogen[graphs]'")
raise e
diff --git a/autogen/io/base.py b/autogen/io/base.py
index ccdd1d183..ba05767d3 100644
--- a/autogen/io/base.py
+++ b/autogen/io/base.py
@@ -1,6 +1,6 @@
+import logging
from contextlib import contextmanager
from contextvars import ContextVar
-import logging
from typing import Any, Iterator, Optional, Protocol, runtime_checkable
__all__ = ("OutputStream", "InputStream", "IOStream")
diff --git a/autogen/io/websockets.py b/autogen/io/websockets.py
index 45caffcdc..9d38a7187 100644
--- a/autogen/io/websockets.py
+++ b/autogen/io/websockets.py
@@ -4,7 +4,7 @@ import threading
from contextlib import contextmanager
from functools import partial
from time import sleep
-from typing import Any, Callable, Dict, Iterable, Iterator, Optional, TYPE_CHECKING, Protocol, Union
+from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, Optional, Protocol, Union
from .base import IOStream
diff --git a/autogen/logger/base_logger.py b/autogen/logger/base_logger.py
index 97508b488..24e19c475 100644
--- a/autogen/logger/base_logger.py
+++ b/autogen/logger/base_logger.py
@@ -1,11 +1,11 @@
from __future__ import annotations
-from abc import ABC, abstractmethod
-from typing import Any, Dict, List, TYPE_CHECKING, Union
import sqlite3
import uuid
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, Dict, List, Union
-from openai import OpenAI, AzureOpenAI
+from openai import AzureOpenAI, OpenAI
from openai.types.chat import ChatCompletion
if TYPE_CHECKING:
diff --git a/autogen/logger/logger_factory.py b/autogen/logger/logger_factory.py
index 282efc326..8073c0c07 100644
--- a/autogen/logger/logger_factory.py
+++ b/autogen/logger/logger_factory.py
@@ -1,4 +1,5 @@
from typing import Any, Dict, Optional
+
from autogen.logger.base_logger import BaseLogger
from autogen.logger.sqlite_logger import SqliteLogger
diff --git a/autogen/logger/sqlite_logger.py b/autogen/logger/sqlite_logger.py
index 227d57f91..62f758c51 100644
--- a/autogen/logger/sqlite_logger.py
+++ b/autogen/logger/sqlite_logger.py
@@ -6,16 +6,16 @@ import os
import sqlite3
import threading
import uuid
+from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
+
+from openai import AzureOpenAI, OpenAI
+from openai.types.chat import ChatCompletion
from autogen.logger.base_logger import BaseLogger
from autogen.logger.logger_utils import get_current_ts, to_dict
-from openai import OpenAI, AzureOpenAI
-from openai.types.chat import ChatCompletion
-from typing import Any, Dict, List, TYPE_CHECKING, Tuple, Union
from .base_logger import LLMConfig
-
if TYPE_CHECKING:
from autogen import ConversableAgent, OpenAIWrapper
diff --git a/autogen/math_utils.py b/autogen/math_utils.py
index 00fcae57a..aeac2fc97 100644
--- a/autogen/math_utils.py
+++ b/autogen/math_utils.py
@@ -1,5 +1,6 @@
from typing import Optional
-from autogen import oai, DEFAULT_MODEL
+
+from autogen import DEFAULT_MODEL, oai
_MATH_PROMPT = "{problem} Solve the problem carefully. Simplify your answer as much as possible. Put the final answer in \\boxed{{}}."
_MATH_CONFIG = {
diff --git a/autogen/oai/__init__.py b/autogen/oai/__init__.py
index 9e8437cec..d5e2000f7 100644
--- a/autogen/oai/__init__.py
+++ b/autogen/oai/__init__.py
@@ -1,15 +1,15 @@
-from autogen.oai.client import OpenAIWrapper, ModelClient
-from autogen.oai.completion import Completion, ChatCompletion
+from autogen.cache.cache import Cache
+from autogen.oai.client import ModelClient, OpenAIWrapper
+from autogen.oai.completion import ChatCompletion, Completion
from autogen.oai.openai_utils import (
- get_config_list,
+ config_list_from_dotenv,
+ config_list_from_json,
+ config_list_from_models,
config_list_gpt4_gpt35,
config_list_openai_aoai,
- config_list_from_models,
- config_list_from_json,
- config_list_from_dotenv,
filter_config,
+ get_config_list,
)
-from autogen.cache.cache import Cache
__all__ = [
"OpenAIWrapper",
diff --git a/autogen/oai/client.py b/autogen/oai/client.py
index f288ece39..a5f44d2bb 100644
--- a/autogen/oai/client.py
+++ b/autogen/oai/client.py
@@ -1,22 +1,20 @@
from __future__ import annotations
-import sys
-from typing import Any, List, Optional, Dict, Callable, Tuple, Union
-import logging
import inspect
+import logging
+import sys
import uuid
-from flaml.automl.logger import logger_formatter
+from typing import Any, Callable, Dict, List, Optional, Protocol, Tuple, Union
+from flaml.automl.logger import logger_formatter
from pydantic import BaseModel
-from typing import Protocol
from autogen.cache import Cache
from autogen.io.base import IOStream
-from autogen.oai.openai_utils import get_key, is_valid_api_key, OAI_PRICE1K
-from autogen.token_count_utils import count_token
-
-from autogen.runtime_logging import logging_enabled, log_chat_completion, log_new_client, log_new_wrapper
from autogen.logger.logger_utils import get_current_ts
+from autogen.oai.openai_utils import OAI_PRICE1K, get_key, is_valid_api_key
+from autogen.runtime_logging import log_chat_completion, log_new_client, log_new_wrapper, logging_enabled
+from autogen.token_count_utils import count_token
TOOL_ENABLED = False
try:
@@ -27,14 +25,15 @@ except ImportError:
AzureOpenAI = object
else:
# raises exception if openai>=1 is installed and something is wrong with imports
- from openai import OpenAI, AzureOpenAI, APIError, APITimeoutError, __version__ as OPENAIVERSION
+ from openai import APIError, APITimeoutError, AzureOpenAI, OpenAI
+ from openai import __version__ as OPENAIVERSION
from openai.resources import Completions
from openai.types.chat import ChatCompletion
from openai.types.chat.chat_completion import ChatCompletionMessage, Choice # type: ignore [attr-defined]
from openai.types.chat.chat_completion_chunk import (
+ ChoiceDeltaFunctionCall,
ChoiceDeltaToolCall,
ChoiceDeltaToolCallFunction,
- ChoiceDeltaFunctionCall,
)
from openai.types.completion import Completion
from openai.types.completion_usage import CompletionUsage
diff --git a/autogen/oai/completion.py b/autogen/oai/completion.py
index 43ccd0b3b..e3b01ee4d 100644
--- a/autogen/oai/completion.py
+++ b/autogen/oai/completion.py
@@ -1,28 +1,30 @@
-from time import sleep
import logging
-import time
-from typing import List, Optional, Dict, Callable, Union
-import sys
import shutil
+import sys
+import time
+from collections import defaultdict
+from time import sleep
+from typing import Callable, Dict, List, Optional, Union
+
import numpy as np
-from flaml import tune, BlendSearch
-from flaml.tune.space import is_constant
+from flaml import BlendSearch, tune
from flaml.automl.logger import logger_formatter
+from flaml.tune.space import is_constant
+
from .openai_utils import get_key
-from collections import defaultdict
try:
+ import diskcache
import openai
from openai import (
- RateLimitError,
+ APIConnectionError,
APIError,
+ AuthenticationError,
BadRequestError,
- APIConnectionError,
+ RateLimitError,
Timeout,
- AuthenticationError,
)
from openai import Completion as openai_Completion
- import diskcache
ERROR = None
assert openai.__version__ < "1"
diff --git a/autogen/oai/openai_utils.py b/autogen/oai/openai_utils.py
index b6f888906..7b5063c0b 100644
--- a/autogen/oai/openai_utils.py
+++ b/autogen/oai/openai_utils.py
@@ -7,7 +7,6 @@ from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Union
from dotenv import find_dotenv, load_dotenv
-
from openai import OpenAI
from openai.types.beta.assistant import Assistant
diff --git a/autogen/retrieve_utils.py b/autogen/retrieve_utils.py
index c3e50c7a9..875ceb13c 100644
--- a/autogen/retrieve_utils.py
+++ b/autogen/retrieve_utils.py
@@ -1,18 +1,21 @@
-from typing import List, Union, Callable
+import glob
import os
-import requests
+from typing import Callable, List, Union
from urllib.parse import urlparse
-import glob
+
import chromadb
+import requests
if chromadb.__version__ < "0.4.15":
from chromadb.api import API
else:
from chromadb.api import ClientAPI as API
-from chromadb.api.types import QueryResult
-import chromadb.utils.embedding_functions as ef
import logging
+
+import chromadb.utils.embedding_functions as ef
import pypdf
+from chromadb.api.types import QueryResult
+
from autogen.token_count_utils import count_token
try:
diff --git a/autogen/runtime_logging.py b/autogen/runtime_logging.py
index 94d7460cd..8c704b438 100644
--- a/autogen/runtime_logging.py
+++ b/autogen/runtime_logging.py
@@ -1,16 +1,16 @@
from __future__ import annotations
-from autogen.logger.logger_factory import LoggerFactory
-from autogen.logger.base_logger import LLMConfig
-
import logging
import sqlite3
-from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union
import uuid
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
-from openai import OpenAI, AzureOpenAI
+from openai import AzureOpenAI, OpenAI
from openai.types.chat import ChatCompletion
+from autogen.logger.base_logger import LLMConfig
+from autogen.logger.logger_factory import LoggerFactory
+
if TYPE_CHECKING:
from autogen import ConversableAgent, OpenAIWrapper
diff --git a/autogen/token_count_utils.py b/autogen/token_count_utils.py
index 84fe147fd..9bda6c50f 100644
--- a/autogen/token_count_utils.py
+++ b/autogen/token_count_utils.py
@@ -1,9 +1,9 @@
-from typing import List, Union, Dict
-import logging
import json
-import tiktoken
+import logging
import re
+from typing import Dict, List, Union
+import tiktoken
logger = logging.getLogger(__name__)
diff --git a/notebook/agentchat_agentoptimizer.ipynb b/notebook/agentchat_agentoptimizer.ipynb
index 9d34c6896..b23476cdd 100644
--- a/notebook/agentchat_agentoptimizer.ipynb
+++ b/notebook/agentchat_agentoptimizer.ipynb
@@ -5,7 +5,10 @@
"metadata": {
"front_matter": {
"description": "AgentOptimizer is able to prompt LLMs to iteratively optimize function/skills of AutoGen agents according to the historical conversation and performance.",
- "tags": ["optimization", "tool/function"]
+ "tags": [
+ "optimization",
+ "tool/function"
+ ]
}
},
"source": [
@@ -36,17 +39,19 @@
"metadata": {},
"outputs": [],
"source": [
+ "import copy\n",
+ "import json\n",
"from typing import Any, Callable, Dict, List, Optional, Tuple, Union\n",
+ "\n",
+ "from openai import BadRequestError\n",
+ "\n",
+ "import autogen\n",
+ "from autogen import config_list_from_json\n",
+ "from autogen.agentchat import Agent\n",
"from autogen.agentchat.contrib.agent_optimizer import AgentOptimizer\n",
"from autogen.agentchat.contrib.math_user_proxy_agent import MathUserProxyAgent\n",
- "from autogen.agentchat import Agent\n",
- "from openai import BadRequestError\n",
"from autogen.code_utils import extract_code\n",
- "from autogen.math_utils import get_answer\n",
- "from autogen import config_list_from_json\n",
- "import autogen\n",
- "import json\n",
- "import copy"
+ "from autogen.math_utils import get_answer"
]
},
{
diff --git a/notebook/agentchat_auto_feedback_from_code_execution.ipynb b/notebook/agentchat_auto_feedback_from_code_execution.ipynb
index e639a6475..834e1e7df 100644
--- a/notebook/agentchat_auto_feedback_from_code_execution.ipynb
+++ b/notebook/agentchat_auto_feedback_from_code_execution.ipynb
@@ -33,11 +33,11 @@
"metadata": {},
"outputs": [],
"source": [
+ "import csv\n",
"from typing import Dict, Union\n",
"\n",
"from IPython import get_ipython\n",
- "from IPython.display import display, Image\n",
- "import csv\n",
+ "from IPython.display import Image, display\n",
"\n",
"import autogen\n",
"\n",
diff --git a/notebook/agentchat_capability_long_context_handling.ipynb b/notebook/agentchat_capability_long_context_handling.ipynb
index 4848990b1..bf2224f5a 100644
--- a/notebook/agentchat_capability_long_context_handling.ipynb
+++ b/notebook/agentchat_capability_long_context_handling.ipynb
@@ -31,6 +31,7 @@
"outputs": [],
"source": [
"import os\n",
+ "\n",
"import autogen\n",
"from autogen.agentchat.contrib.capabilities import context_handling"
]
diff --git a/notebook/agentchat_cost_token_tracking.ipynb b/notebook/agentchat_cost_token_tracking.ipynb
index 491fa1b1e..7334f2e36 100644
--- a/notebook/agentchat_cost_token_tracking.ipynb
+++ b/notebook/agentchat_cost_token_tracking.ipynb
@@ -60,9 +60,7 @@
"outputs": [],
"source": [
"import autogen\n",
- "from autogen import OpenAIWrapper\n",
- "from autogen import AssistantAgent, UserProxyAgent\n",
- "from autogen import gather_usage_summary\n",
+ "from autogen import AssistantAgent, OpenAIWrapper, UserProxyAgent, gather_usage_summary\n",
"\n",
"# config_list = autogen.config_list_from_json(\n",
"# \"OAI_CONFIG_LIST\",\n",
diff --git a/notebook/agentchat_custom_model.ipynb b/notebook/agentchat_custom_model.ipynb
index d4cf14e57..b06d2c3cf 100644
--- a/notebook/agentchat_custom_model.ipynb
+++ b/notebook/agentchat_custom_model.ipynb
@@ -36,10 +36,12 @@
"metadata": {},
"outputs": [],
"source": [
+ "from types import SimpleNamespace\n",
+ "\n",
+ "from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig\n",
+ "\n",
"import autogen\n",
- "from autogen import AssistantAgent, UserProxyAgent\n",
- "from transformers import AutoTokenizer, GenerationConfig, AutoModelForCausalLM\n",
- "from types import SimpleNamespace"
+ "from autogen import AssistantAgent, UserProxyAgent"
]
},
{
diff --git a/notebook/agentchat_dalle_and_gpt4v.ipynb b/notebook/agentchat_dalle_and_gpt4v.ipynb
index dd84ad238..258b49d69 100644
--- a/notebook/agentchat_dalle_and_gpt4v.ipynb
+++ b/notebook/agentchat_dalle_and_gpt4v.ipynb
@@ -46,7 +46,7 @@
"\n",
"import autogen\n",
"from autogen import Agent, AssistantAgent, ConversableAgent, UserProxyAgent\n",
- "from autogen.agentchat.contrib.img_utils import _to_pil, get_image_data, gpt4v_formatter, get_pil_image\n",
+ "from autogen.agentchat.contrib.img_utils import _to_pil, get_image_data, get_pil_image, gpt4v_formatter\n",
"from autogen.agentchat.contrib.multimodal_conversable_agent import MultimodalConversableAgent"
]
},
diff --git a/notebook/agentchat_function_call_currency_calculator.ipynb b/notebook/agentchat_function_call_currency_calculator.ipynb
index 6709aec77..c7ec32ad8 100644
--- a/notebook/agentchat_function_call_currency_calculator.ipynb
+++ b/notebook/agentchat_function_call_currency_calculator.ipynb
@@ -65,7 +65,6 @@
"import autogen\n",
"from autogen.cache import Cache\n",
"\n",
- "\n",
"config_list = autogen.config_list_from_json(\n",
" \"OAI_CONFIG_LIST\",\n",
" filter_dict={\n",
diff --git a/notebook/agentchat_groupchat_RAG.ipynb b/notebook/agentchat_groupchat_RAG.ipynb
index 83528de93..35ab96909 100644
--- a/notebook/agentchat_groupchat_RAG.ipynb
+++ b/notebook/agentchat_groupchat_RAG.ipynb
@@ -47,8 +47,8 @@
}
],
"source": [
- "from typing_extensions import Annotated\n",
"import chromadb\n",
+ "from typing_extensions import Annotated\n",
"\n",
"import autogen\n",
"from autogen import AssistantAgent\n",
diff --git a/notebook/agentchat_groupchat_customized.ipynb b/notebook/agentchat_groupchat_customized.ipynb
index 253a0ec93..dde124aef 100644
--- a/notebook/agentchat_groupchat_customized.ipynb
+++ b/notebook/agentchat_groupchat_customized.ipynb
@@ -155,8 +155,9 @@
" }, # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.\n",
")\n",
"\n",
+ "from typing import Dict, List\n",
+ "\n",
"from autogen import Agent\n",
- "from typing import List, Dict\n",
"\n",
"\n",
"def custom_speaker_selection_func(last_speaker: Agent, groupchat: autogen.GroupChat):\n",
diff --git a/notebook/agentchat_image_generation_capability.ipynb b/notebook/agentchat_image_generation_capability.ipynb
index f6743ff46..7c0c366a5 100644
--- a/notebook/agentchat_image_generation_capability.ipynb
+++ b/notebook/agentchat_image_generation_capability.ipynb
@@ -40,14 +40,14 @@
"import re\n",
"from typing import Dict, Optional\n",
"\n",
+ "from IPython.display import display\n",
"from PIL.Image import Image\n",
"\n",
"import autogen\n",
- "from autogen.cache import Cache\n",
"from autogen.agentchat.contrib import img_utils\n",
"from autogen.agentchat.contrib.capabilities import generate_images\n",
- "from autogen.oai import openai_utils\n",
- "from IPython.display import display"
+ "from autogen.cache import Cache\n",
+ "from autogen.oai import openai_utils"
]
},
{
diff --git a/notebook/agentchat_lmm_gpt-4v.ipynb b/notebook/agentchat_lmm_gpt-4v.ipynb
index 3da51028b..7c9e3ea12 100644
--- a/notebook/agentchat_lmm_gpt-4v.ipynb
+++ b/notebook/agentchat_lmm_gpt-4v.ipynb
@@ -43,17 +43,17 @@
"from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union\n",
"\n",
"import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
"import requests\n",
"from PIL import Image\n",
"from termcolor import colored\n",
- "import numpy as np\n",
"\n",
"import autogen\n",
- "from autogen.code_utils import content_str\n",
"from autogen import Agent, AssistantAgent, ConversableAgent, UserProxyAgent\n",
"from autogen.agentchat.contrib.capabilities.vision_capability import VisionCapability\n",
+ "from autogen.agentchat.contrib.img_utils import get_pil_image, pil_to_data_uri\n",
"from autogen.agentchat.contrib.multimodal_conversable_agent import MultimodalConversableAgent\n",
- "from autogen.agentchat.contrib.img_utils import get_pil_image, pil_to_data_uri"
+ "from autogen.code_utils import content_str"
]
},
{
diff --git a/notebook/agentchat_logging.ipynb b/notebook/agentchat_logging.ipynb
index c06a8fd74..2ad19e799 100644
--- a/notebook/agentchat_logging.ipynb
+++ b/notebook/agentchat_logging.ipynb
@@ -38,9 +38,11 @@
],
"source": [
"import json\n",
+ "\n",
+ "import pandas as pd\n",
+ "\n",
"import autogen\n",
"from autogen import AssistantAgent, UserProxyAgent\n",
- "import pandas as pd\n",
"\n",
"# Setup API key. Add your own API key to config file or environment variable\n",
"llm_config = {\n",
diff --git a/notebook/agentchat_nested_chats_chess.ipynb b/notebook/agentchat_nested_chats_chess.ipynb
index 52a53de10..1cfa4ba95 100644
--- a/notebook/agentchat_nested_chats_chess.ipynb
+++ b/notebook/agentchat_nested_chats_chess.ipynb
@@ -98,10 +98,11 @@
"metadata": {},
"outputs": [],
"source": [
+ "from typing import List\n",
+ "\n",
"import chess\n",
"import chess.svg\n",
"from IPython.display import display\n",
- "from typing import List\n",
"from typing_extensions import Annotated\n",
"\n",
"# Initialize the board.\n",
diff --git a/notebook/agentchat_nestedchat.ipynb b/notebook/agentchat_nestedchat.ipynb
index 7c48813aa..5448d4a31 100644
--- a/notebook/agentchat_nestedchat.ipynb
+++ b/notebook/agentchat_nestedchat.ipynb
@@ -31,9 +31,10 @@
"metadata": {},
"outputs": [],
"source": [
- "import autogen\n",
"from typing_extensions import Annotated\n",
"\n",
+ "import autogen\n",
+ "\n",
"config_list = autogen.config_list_from_json(env_or_file=\"OAI_CONFIG_LIST\")\n",
"llm_config = {\"config_list\": config_list}"
]
@@ -656,9 +657,10 @@
}
],
"metadata": {
- "extra_files_to_copy": [
- "nested_chat_1.png", "nested_chat_2.png"
- ],
+ "extra_files_to_copy": [
+ "nested_chat_1.png",
+ "nested_chat_2.png"
+ ],
"front_matter": {
"description": "Solve complex tasks with a chat nested as inner monologue.",
"tags": [
diff --git a/notebook/agentchat_nestedchat_optiguide.ipynb b/notebook/agentchat_nestedchat_optiguide.ipynb
index 52210cbe5..11441d3e9 100644
--- a/notebook/agentchat_nestedchat_optiguide.ipynb
+++ b/notebook/agentchat_nestedchat_optiguide.ipynb
@@ -36,18 +36,19 @@
"metadata": {},
"outputs": [],
"source": [
- "import autogen\n",
+ "import re\n",
"from typing import Union\n",
"\n",
+ "# import auxiliary packages\n",
+ "import requests # for loading the example source code\n",
+ "from eventlet.timeout import Timeout\n",
+ "\n",
"# test Gurobi installation\n",
"from gurobipy import GRB\n",
- "from eventlet.timeout import Timeout\n",
- "import re\n",
"from termcolor import colored\n",
- "from autogen.code_utils import extract_code\n",
"\n",
- "# import auxiliary packages\n",
- "import requests # for loading the example source code\n",
+ "import autogen\n",
+ "from autogen.code_utils import extract_code\n",
"\n",
"config_list_gpt4 = autogen.config_list_from_json(\n",
" \"OAI_CONFIG_LIST\",\n",
diff --git a/notebook/agentchat_sql_spider.ipynb b/notebook/agentchat_sql_spider.ipynb
index 0c850b7e0..e27471006 100644
--- a/notebook/agentchat_sql_spider.ipynb
+++ b/notebook/agentchat_sql_spider.ipynb
@@ -45,12 +45,13 @@
],
"source": [
"# %pip install spider-env\n",
- "from spider_env import SpiderEnv\n",
- "\n",
- "from autogen import UserProxyAgent, ConversableAgent, config_list_from_json\n",
- "from typing import Annotated, Dict\n",
"import json\n",
"import os\n",
+ "from typing import Annotated, Dict\n",
+ "\n",
+ "from spider_env import SpiderEnv\n",
+ "\n",
+ "from autogen import ConversableAgent, UserProxyAgent, config_list_from_json\n",
"\n",
"gym = SpiderEnv()\n",
"\n",
diff --git a/notebook/agentchat_transform_messages.ipynb b/notebook/agentchat_transform_messages.ipynb
index 1b05d108b..ab8bc762f 100644
--- a/notebook/agentchat_transform_messages.ipynb
+++ b/notebook/agentchat_transform_messages.ipynb
@@ -29,14 +29,14 @@
"metadata": {},
"outputs": [],
"source": [
+ "import copy\n",
"import os\n",
"import pprint\n",
- "import copy\n",
"import re\n",
+ "from typing import Dict, List\n",
"\n",
"import autogen\n",
- "from autogen.agentchat.contrib.capabilities import transform_messages, transforms\n",
- "from typing import Dict, List"
+ "from autogen.agentchat.contrib.capabilities import transform_messages, transforms"
]
},
{
diff --git a/notebook/agentchat_video_transcript_translate_with_whisper.ipynb b/notebook/agentchat_video_transcript_translate_with_whisper.ipynb
index be955d5d7..48812ad01 100644
--- a/notebook/agentchat_video_transcript_translate_with_whisper.ipynb
+++ b/notebook/agentchat_video_transcript_translate_with_whisper.ipynb
@@ -84,8 +84,8 @@
"\n",
"import whisper\n",
"from openai import OpenAI\n",
- "import autogen\n",
"\n",
+ "import autogen\n",
"\n",
"source_language = \"English\"\n",
"target_language = \"Chinese\"\n",
diff --git a/notebook/agentchat_webscraping_with_apify.ipynb b/notebook/agentchat_webscraping_with_apify.ipynb
index ad80f0d96..0429c10f8 100644
--- a/notebook/agentchat_webscraping_with_apify.ipynb
+++ b/notebook/agentchat_webscraping_with_apify.ipynb
@@ -1,389 +1,389 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Web Scraping using Apify Tools\n",
- "\n",
- "This notebook shows how to use Apify tools with AutoGen agents to\n",
- "scrape data from a website and formate the output."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "First we need to install the Apify SDK and the AutoGen library."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "! pip install -qqq pyautogen apify-client"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Setting up the LLM configuration and the Apify API key is also required."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "\n",
- "config_list = [\n",
- " {\"model\": \"gpt-4\", \"api_key\": os.getenv(\"OPENAI_API_KEY\")},\n",
- "]\n",
- "\n",
- "apify_api_key = os.getenv(\"APIFY_API_KEY\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Let's define the tool for scraping data from the website using Apify actor.\n",
- "Read more about tool use in this [tutorial chapter](/docs/tutorial/tool-use)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {},
- "outputs": [],
- "source": [
- "from typing_extensions import Annotated\n",
- "from apify_client import ApifyClient\n",
- "\n",
- "\n",
- "def scrape_page(url: Annotated[str, \"The URL of the web page to scrape\"]) -> Annotated[str, \"Scraped content\"]:\n",
- " # Initialize the ApifyClient with your API token\n",
- " client = ApifyClient(token=apify_api_key)\n",
- "\n",
- " # Prepare the Actor input\n",
- " run_input = {\n",
- " \"startUrls\": [{\"url\": url}],\n",
- " \"useSitemaps\": False,\n",
- " \"crawlerType\": \"playwright:firefox\",\n",
- " \"includeUrlGlobs\": [],\n",
- " \"excludeUrlGlobs\": [],\n",
- " \"ignoreCanonicalUrl\": False,\n",
- " \"maxCrawlDepth\": 0,\n",
- " \"maxCrawlPages\": 1,\n",
- " \"initialConcurrency\": 0,\n",
- " \"maxConcurrency\": 200,\n",
- " \"initialCookies\": [],\n",
- " \"proxyConfiguration\": {\"useApifyProxy\": True},\n",
- " \"maxSessionRotations\": 10,\n",
- " \"maxRequestRetries\": 5,\n",
- " \"requestTimeoutSecs\": 60,\n",
- " \"dynamicContentWaitSecs\": 10,\n",
- " \"maxScrollHeightPixels\": 5000,\n",
- " \"removeElementsCssSelector\": \"\"\"nav, footer, script, style, noscript, svg,\n",
- " [role=\\\"alert\\\"],\n",
- " [role=\\\"banner\\\"],\n",
- " [role=\\\"dialog\\\"],\n",
- " [role=\\\"alertdialog\\\"],\n",
- " [role=\\\"region\\\"][aria-label*=\\\"skip\\\" i],\n",
- " [aria-modal=\\\"true\\\"]\"\"\",\n",
- " \"removeCookieWarnings\": True,\n",
- " \"clickElementsCssSelector\": '[aria-expanded=\"false\"]',\n",
- " \"htmlTransformer\": \"readableText\",\n",
- " \"readableTextCharThreshold\": 100,\n",
- " \"aggressivePrune\": False,\n",
- " \"debugMode\": True,\n",
- " \"debugLog\": True,\n",
- " \"saveHtml\": True,\n",
- " \"saveMarkdown\": True,\n",
- " \"saveFiles\": False,\n",
- " \"saveScreenshots\": False,\n",
- " \"maxResults\": 9999999,\n",
- " \"clientSideMinChangePercentage\": 15,\n",
- " \"renderingTypeDetectionPercentage\": 10,\n",
- " }\n",
- "\n",
- " # Run the Actor and wait for it to finish\n",
- " run = client.actor(\"aYG0l9s7dbB7j3gbS\").call(run_input=run_input)\n",
- "\n",
- " # Fetch and print Actor results from the run's dataset (if there are any)\n",
- " text_data = \"\"\n",
- " for item in client.dataset(run[\"defaultDatasetId\"]).iterate_items():\n",
- " text_data += item.get(\"text\", \"\") + \"\\n\"\n",
- "\n",
- " average_token = 0.75\n",
- " max_tokens = 20000 # slightly less than max to be safe 32k\n",
- " text_data = text_data[: int(average_token * max_tokens)]\n",
- " return text_data"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Create the agents and register the tool."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 34,
- "metadata": {},
- "outputs": [],
- "source": [
- "from autogen import ConversableAgent, register_function\n",
- "\n",
- "# Create web scrapper agent.\n",
- "scraper_agent = ConversableAgent(\n",
- " \"WebScraper\",\n",
- " llm_config={\"config_list\": config_list},\n",
- " system_message=\"You are a web scrapper and you can scrape any web page using the tools provided. \"\n",
- " \"Returns 'TERMINATE' when the scraping is done.\",\n",
- ")\n",
- "\n",
- "# Create user proxy agent.\n",
- "user_proxy_agent = ConversableAgent(\n",
- " \"UserProxy\",\n",
- " llm_config=False, # No LLM for this agent.\n",
- " human_input_mode=\"NEVER\",\n",
- " code_execution_config=False, # No code execution for this agent.\n",
- " is_termination_msg=lambda x: x.get(\"content\", \"\") is not None and \"terminate\" in x[\"content\"].lower(),\n",
- " default_auto_reply=\"Please continue if not finished, otherwise return 'TERMINATE'.\",\n",
- ")\n",
- "\n",
- "# Register the function with the agents.\n",
- "register_function(\n",
- " scrape_page,\n",
- " caller=scraper_agent,\n",
- " executor=user_proxy_agent,\n",
- " name=\"scrape_page\",\n",
- " description=\"Scrape a web page and return the content.\",\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Start the conversation for scraping web data. We used the\n",
- "`reflection_with_llm` option for summary method\n",
- "to perform the formatting of the output into a desired format.\n",
- "The summary method is called after the conversation is completed\n",
- "given the complete history of the conversation."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
- "\n",
- "Can you scrape agentops.ai for me?\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[31m\n",
- ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
- "\u001b[33mWebScraper\u001b[0m (to UserProxy):\n",
- "\n",
- "\u001b[32m***** Suggested tool call (call_0qok2jvCxOfv7HOA0oxPWneM): scrape_page *****\u001b[0m\n",
- "Arguments: \n",
- "{\n",
- "\"url\": \"https://www.agentops.ai\"\n",
- "}\n",
- "\u001b[32m****************************************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[35m\n",
- ">>>>>>>> EXECUTING FUNCTION scrape_page...\u001b[0m\n",
- "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
- "\n",
- "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
- "\n",
- "\u001b[32m***** Response from calling tool (call_0qok2jvCxOfv7HOA0oxPWneM) *****\u001b[0m\n",
- "START NOW\n",
- "Take your business to the next level with our features \n",
- "AI Agents Suck.\n",
- "We're Fixing That. \n",
- "Build compliant AI agents with observability, evals, and replay analytics. No more black boxes and prompt guessing.\n",
- "New! Introducing AgentOps\n",
- "Three Lines of Code. Unlimited Testing. \n",
- "Instant Testing + Debugging = Compliant AI Agents That Work\n",
- "5\n",
- "# Beginning of program's code (i.e. main.py, __init__.py)\n",
- "6\n",
- "ao_client = agentops.Client(<INSERT YOUR API KEY HERE>)\n",
- "9\n",
- "# (optional: record specific functions)\n",
- "10\n",
- "@ao_client.record_action('sample function being record')\n",
- "11\n",
- "def sample_function(...):\n",
- "15\n",
- "ao_client.end_session('Success')\n",
- "Prototype to Production\n",
- "Generous free limits, upgrade only when you need it.\n",
- "\n",
- "\u001b[32m**********************************************************************\u001b[0m\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[31m\n",
- ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
- "\u001b[33mWebScraper\u001b[0m (to UserProxy):\n",
- "\n",
- "Sure, here's the information from the website agentops.ai:\n",
- "\n",
- "- Their main value proposition is to fix bad AI Agents and replace black boxes and prompt guessing with compliant, observable AI agents that come with evals and replay analytics.\n",
- "- Their latest product is AgentOps. The simple and instant testing & debugging offered promises better-performing compliant AI agents.\n",
- "- Integration is easy with just three lines of code.\n",
- "- They let you record specific functions.\n",
- "- They provide generous free limits and you only need to upgrade when necessary.\n",
- "\n",
- "Here's a sample of their code:\n",
- "```python\n",
- "ao_client = agentops.Client(<INSERT YOUR API KEY HERE>)\n",
- "\n",
- "# optional: record specific functions\n",
- "@ao_client.record_action('sample function being record')\n",
- "def sample_function(...):\n",
- " ...\n",
- "\n",
- "ao_client.end_session('Success')\n",
- "```\n",
- "This code is for sample usage of their libraries/functions.\n",
- "\n",
- "Let me know if you need more specific details.\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
- "\n",
- "Please continue if not finished, otherwise return 'TERMINATE'.\n",
- "\n",
- "--------------------------------------------------------------------------------\n",
- "\u001b[31m\n",
- ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
- "\u001b[33mWebScraper\u001b[0m (to UserProxy):\n",
- "\n",
- "TERMINATE\n",
- "\n",
- "--------------------------------------------------------------------------------\n"
- ]
- }
- ],
- "source": [
- "chat_result = user_proxy_agent.initiate_chat(\n",
- " scraper_agent,\n",
- " message=\"Can you scrape agentops.ai for me?\",\n",
- " summary_method=\"reflection_with_llm\",\n",
- " summary_args={\n",
- " \"summary_prompt\": \"\"\"Summarize the scraped content and format summary EXACTLY as follows:\n",
- "---\n",
- "*Company name*:\n",
- "`Acme Corp`\n",
- "---\n",
- "*Website*:\n",
- "`acmecorp.com`\n",
- "---\n",
- "*Description*:\n",
- "`Company that does things.`\n",
- "---\n",
- "*Tags*:\n",
- "`Manufacturing. Retail. E-commerce.`\n",
- "---\n",
- "*Takeaways*:\n",
- "`Provides shareholders with value by selling products.`\n",
- "---\n",
- "*Questions*:\n",
- "`What products do they sell? How do they make money? What is their market share?`\n",
- "---\n",
- "\"\"\"\n",
- " },\n",
- ")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The output is stored in the summary."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 37,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "---\n",
- "*Company name*:\n",
- "`AgentOps`\n",
- "---\n",
- "*Website*:\n",
- "`agentops.ai`\n",
- "---\n",
- "*Description*:\n",
- "`Company that aims to improve AI agents. They offer observed and evaluable AI agents with replay analytics as an alternative to black box models and blind prompting.`\n",
- "---\n",
- "*Tags*:\n",
- "`Artificial Intelligence, AI agents, Observability, Analytics.`\n",
- "---\n",
- "*Takeaways*:\n",
- "`Their product, AgentOps, allows for easy and instant testing and debugging of AI agents. Integration is as simple as writing three lines of code. They also provide generous free limits and mandate upgrades only when necessary.`\n",
- "---\n",
- "*Questions*:\n",
- "`What differentiates AgentOps from other, similar products? How does their pricing scale with usage? What are the details of their \"generous free limits\"?`\n",
- "---\n"
- ]
- }
- ],
- "source": [
- "print(chat_result.summary)"
- ]
- }
- ],
- "metadata": {
- "front_matter": {
- "description": "Scrapping web pages and summarizing the content using agents with tools.",
- "tags": [
- "web scraping",
- "apify",
- "tool use"
- ],
- "title": "Web Scraper Agent using Apify Tools"
- },
- "kernelspec": {
- "display_name": "autogen",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.5"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Web Scraping using Apify Tools\n",
+ "\n",
+ "This notebook shows how to use Apify tools with AutoGen agents to\n",
+ "scrape data from a website and formate the output."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First we need to install the Apify SDK and the AutoGen library."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install -qqq pyautogen apify-client"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Setting up the LLM configuration and the Apify API key is also required."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "config_list = [\n",
+ " {\"model\": \"gpt-4\", \"api_key\": os.getenv(\"OPENAI_API_KEY\")},\n",
+ "]\n",
+ "\n",
+ "apify_api_key = os.getenv(\"APIFY_API_KEY\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's define the tool for scraping data from the website using Apify actor.\n",
+ "Read more about tool use in this [tutorial chapter](/docs/tutorial/tool-use)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from apify_client import ApifyClient\n",
+ "from typing_extensions import Annotated\n",
+ "\n",
+ "\n",
+ "def scrape_page(url: Annotated[str, \"The URL of the web page to scrape\"]) -> Annotated[str, \"Scraped content\"]:\n",
+ " # Initialize the ApifyClient with your API token\n",
+ " client = ApifyClient(token=apify_api_key)\n",
+ "\n",
+ " # Prepare the Actor input\n",
+ " run_input = {\n",
+ " \"startUrls\": [{\"url\": url}],\n",
+ " \"useSitemaps\": False,\n",
+ " \"crawlerType\": \"playwright:firefox\",\n",
+ " \"includeUrlGlobs\": [],\n",
+ " \"excludeUrlGlobs\": [],\n",
+ " \"ignoreCanonicalUrl\": False,\n",
+ " \"maxCrawlDepth\": 0,\n",
+ " \"maxCrawlPages\": 1,\n",
+ " \"initialConcurrency\": 0,\n",
+ " \"maxConcurrency\": 200,\n",
+ " \"initialCookies\": [],\n",
+ " \"proxyConfiguration\": {\"useApifyProxy\": True},\n",
+ " \"maxSessionRotations\": 10,\n",
+ " \"maxRequestRetries\": 5,\n",
+ " \"requestTimeoutSecs\": 60,\n",
+ " \"dynamicContentWaitSecs\": 10,\n",
+ " \"maxScrollHeightPixels\": 5000,\n",
+ " \"removeElementsCssSelector\": \"\"\"nav, footer, script, style, noscript, svg,\n",
+ " [role=\\\"alert\\\"],\n",
+ " [role=\\\"banner\\\"],\n",
+ " [role=\\\"dialog\\\"],\n",
+ " [role=\\\"alertdialog\\\"],\n",
+ " [role=\\\"region\\\"][aria-label*=\\\"skip\\\" i],\n",
+ " [aria-modal=\\\"true\\\"]\"\"\",\n",
+ " \"removeCookieWarnings\": True,\n",
+ " \"clickElementsCssSelector\": '[aria-expanded=\"false\"]',\n",
+ " \"htmlTransformer\": \"readableText\",\n",
+ " \"readableTextCharThreshold\": 100,\n",
+ " \"aggressivePrune\": False,\n",
+ " \"debugMode\": True,\n",
+ " \"debugLog\": True,\n",
+ " \"saveHtml\": True,\n",
+ " \"saveMarkdown\": True,\n",
+ " \"saveFiles\": False,\n",
+ " \"saveScreenshots\": False,\n",
+ " \"maxResults\": 9999999,\n",
+ " \"clientSideMinChangePercentage\": 15,\n",
+ " \"renderingTypeDetectionPercentage\": 10,\n",
+ " }\n",
+ "\n",
+ " # Run the Actor and wait for it to finish\n",
+ " run = client.actor(\"aYG0l9s7dbB7j3gbS\").call(run_input=run_input)\n",
+ "\n",
+ " # Fetch and print Actor results from the run's dataset (if there are any)\n",
+ " text_data = \"\"\n",
+ " for item in client.dataset(run[\"defaultDatasetId\"]).iterate_items():\n",
+ " text_data += item.get(\"text\", \"\") + \"\\n\"\n",
+ "\n",
+ " average_token = 0.75\n",
+ " max_tokens = 20000 # slightly less than max to be safe 32k\n",
+ " text_data = text_data[: int(average_token * max_tokens)]\n",
+ " return text_data"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Create the agents and register the tool."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from autogen import ConversableAgent, register_function\n",
+ "\n",
+ "# Create web scrapper agent.\n",
+ "scraper_agent = ConversableAgent(\n",
+ " \"WebScraper\",\n",
+ " llm_config={\"config_list\": config_list},\n",
+ " system_message=\"You are a web scrapper and you can scrape any web page using the tools provided. \"\n",
+ " \"Returns 'TERMINATE' when the scraping is done.\",\n",
+ ")\n",
+ "\n",
+ "# Create user proxy agent.\n",
+ "user_proxy_agent = ConversableAgent(\n",
+ " \"UserProxy\",\n",
+ " llm_config=False, # No LLM for this agent.\n",
+ " human_input_mode=\"NEVER\",\n",
+ " code_execution_config=False, # No code execution for this agent.\n",
+ " is_termination_msg=lambda x: x.get(\"content\", \"\") is not None and \"terminate\" in x[\"content\"].lower(),\n",
+ " default_auto_reply=\"Please continue if not finished, otherwise return 'TERMINATE'.\",\n",
+ ")\n",
+ "\n",
+ "# Register the function with the agents.\n",
+ "register_function(\n",
+ " scrape_page,\n",
+ " caller=scraper_agent,\n",
+ " executor=user_proxy_agent,\n",
+ " name=\"scrape_page\",\n",
+ " description=\"Scrape a web page and return the content.\",\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Start the conversation for scraping web data. We used the\n",
+ "`reflection_with_llm` option for summary method\n",
+ "to perform the formatting of the output into a desired format.\n",
+ "The summary method is called after the conversation is completed\n",
+ "given the complete history of the conversation."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
+ "\n",
+ "Can you scrape agentops.ai for me?\n",
+ "\n",
+ "--------------------------------------------------------------------------------\n",
+ "\u001b[31m\n",
+ ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
+ "\u001b[33mWebScraper\u001b[0m (to UserProxy):\n",
+ "\n",
+ "\u001b[32m***** Suggested tool call (call_0qok2jvCxOfv7HOA0oxPWneM): scrape_page *****\u001b[0m\n",
+ "Arguments: \n",
+ "{\n",
+ "\"url\": \"https://www.agentops.ai\"\n",
+ "}\n",
+ "\u001b[32m****************************************************************************\u001b[0m\n",
+ "\n",
+ "--------------------------------------------------------------------------------\n",
+ "\u001b[35m\n",
+ ">>>>>>>> EXECUTING FUNCTION scrape_page...\u001b[0m\n",
+ "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
+ "\n",
+ "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
+ "\n",
+ "\u001b[32m***** Response from calling tool (call_0qok2jvCxOfv7HOA0oxPWneM) *****\u001b[0m\n",
+ "START NOW\n",
+ "Take your business to the next level with our features \n",
+ "AI Agents Suck.\n",
+ "We're Fixing That. \n",
+ "Build compliant AI agents with observability, evals, and replay analytics. No more black boxes and prompt guessing.\n",
+ "New! Introducing AgentOps\n",
+ "Three Lines of Code. Unlimited Testing. \n",
+ "Instant Testing + Debugging = Compliant AI Agents That Work\n",
+ "5\n",
+ "# Beginning of program's code (i.e. main.py, __init__.py)\n",
+ "6\n",
+ "ao_client = agentops.Client(<INSERT YOUR API KEY HERE>)\n",
+ "9\n",
+ "# (optional: record specific functions)\n",
+ "10\n",
+ "@ao_client.record_action('sample function being record')\n",
+ "11\n",
+ "def sample_function(...):\n",
+ "15\n",
+ "ao_client.end_session('Success')\n",
+ "Prototype to Production\n",
+ "Generous free limits, upgrade only when you need it.\n",
+ "\n",
+ "\u001b[32m**********************************************************************\u001b[0m\n",
+ "\n",
+ "--------------------------------------------------------------------------------\n",
+ "\u001b[31m\n",
+ ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
+ "\u001b[33mWebScraper\u001b[0m (to UserProxy):\n",
+ "\n",
+ "Sure, here's the information from the website agentops.ai:\n",
+ "\n",
+ "- Their main value proposition is to fix bad AI Agents and replace black boxes and prompt guessing with compliant, observable AI agents that come with evals and replay analytics.\n",
+ "- Their latest product is AgentOps. The simple and instant testing & debugging offered promises better-performing compliant AI agents.\n",
+ "- Integration is easy with just three lines of code.\n",
+ "- They let you record specific functions.\n",
+ "- They provide generous free limits and you only need to upgrade when necessary.\n",
+ "\n",
+ "Here's a sample of their code:\n",
+ "```python\n",
+ "ao_client = agentops.Client(<INSERT YOUR API KEY HERE>)\n",
+ "\n",
+ "# optional: record specific functions\n",
+ "@ao_client.record_action('sample function being record')\n",
+ "def sample_function(...):\n",
+ " ...\n",
+ "\n",
+ "ao_client.end_session('Success')\n",
+ "```\n",
+ "This code is for sample usage of their libraries/functions.\n",
+ "\n",
+ "Let me know if you need more specific details.\n",
+ "\n",
+ "--------------------------------------------------------------------------------\n",
+ "\u001b[33mUserProxy\u001b[0m (to WebScraper):\n",
+ "\n",
+ "Please continue if not finished, otherwise return 'TERMINATE'.\n",
+ "\n",
+ "--------------------------------------------------------------------------------\n",
+ "\u001b[31m\n",
+ ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
+ "\u001b[33mWebScraper\u001b[0m (to UserProxy):\n",
+ "\n",
+ "TERMINATE\n",
+ "\n",
+ "--------------------------------------------------------------------------------\n"
+ ]
+ }
+ ],
+ "source": [
+ "chat_result = user_proxy_agent.initiate_chat(\n",
+ " scraper_agent,\n",
+ " message=\"Can you scrape agentops.ai for me?\",\n",
+ " summary_method=\"reflection_with_llm\",\n",
+ " summary_args={\n",
+ " \"summary_prompt\": \"\"\"Summarize the scraped content and format summary EXACTLY as follows:\n",
+ "---\n",
+ "*Company name*:\n",
+ "`Acme Corp`\n",
+ "---\n",
+ "*Website*:\n",
+ "`acmecorp.com`\n",
+ "---\n",
+ "*Description*:\n",
+ "`Company that does things.`\n",
+ "---\n",
+ "*Tags*:\n",
+ "`Manufacturing. Retail. E-commerce.`\n",
+ "---\n",
+ "*Takeaways*:\n",
+ "`Provides shareholders with value by selling products.`\n",
+ "---\n",
+ "*Questions*:\n",
+ "`What products do they sell? How do they make money? What is their market share?`\n",
+ "---\n",
+ "\"\"\"\n",
+ " },\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The output is stored in the summary."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "---\n",
+ "*Company name*:\n",
+ "`AgentOps`\n",
+ "---\n",
+ "*Website*:\n",
+ "`agentops.ai`\n",
+ "---\n",
+ "*Description*:\n",
+ "`Company that aims to improve AI agents. They offer observed and evaluable AI agents with replay analytics as an alternative to black box models and blind prompting.`\n",
+ "---\n",
+ "*Tags*:\n",
+ "`Artificial Intelligence, AI agents, Observability, Analytics.`\n",
+ "---\n",
+ "*Takeaways*:\n",
+ "`Their product, AgentOps, allows for easy and instant testing and debugging of AI agents. Integration is as simple as writing three lines of code. They also provide generous free limits and mandate upgrades only when necessary.`\n",
+ "---\n",
+ "*Questions*:\n",
+ "`What differentiates AgentOps from other, similar products? How does their pricing scale with usage? What are the details of their \"generous free limits\"?`\n",
+ "---\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(chat_result.summary)"
+ ]
+ }
+ ],
+ "metadata": {
+ "front_matter": {
+ "description": "Scrapping web pages and summarizing the content using agents with tools.",
+ "tags": [
+ "web scraping",
+ "apify",
+ "tool use"
+ ],
+ "title": "Web Scraper Agent using Apify Tools"
+ },
+ "kernelspec": {
+ "display_name": "autogen",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
}
diff --git a/notebook/agenteval_cq_math.ipynb b/notebook/agenteval_cq_math.ipynb
index b1b893975..71a19b044 100644
--- a/notebook/agenteval_cq_math.ipynb
+++ b/notebook/agenteval_cq_math.ipynb
@@ -82,7 +82,6 @@
"outputs": [],
"source": [
"import json\n",
- "\n",
"import os\n",
"from pathlib import Path\n",
"\n",
diff --git a/pyproject.toml b/pyproject.toml
index 3cd32f17a..3b8c71ad2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -29,6 +29,7 @@ select = [
# "D", # see: https://pypi.org/project/pydocstyle
# "N", # see: https://pypi.org/project/pep8-naming
# "S", # see: https://pypi.org/project/flake8-bandit
+ "I", # see: https://pypi.org/project/isort/
]
ignore = [
diff --git a/samples/apps/auto-anny/bot.py b/samples/apps/auto-anny/bot.py
index ef3759c73..6b901c339 100644
--- a/samples/apps/auto-anny/bot.py
+++ b/samples/apps/auto-anny/bot.py
@@ -1,11 +1,10 @@
-import os
import logging
import logging.handlers
+import os
import discord
-from discord.ext import commands
-
from agent_utils import solve_task
+from discord.ext import commands
logger = logging.getLogger("anny")
logger.setLevel(logging.INFO)
diff --git a/samples/apps/autogen-studio/autogenstudio/__init__.py b/samples/apps/autogen-studio/autogenstudio/__init__.py
index 611b1c520..acc477c5c 100644
--- a/samples/apps/autogen-studio/autogenstudio/__init__.py
+++ b/samples/apps/autogen-studio/autogenstudio/__init__.py
@@ -1,4 +1,4 @@
from .chatmanager import *
-from .workflowmanager import *
from .datamodel import *
from .version import __version__
+from .workflowmanager import *
diff --git a/samples/apps/autogen-studio/autogenstudio/chatmanager.py b/samples/apps/autogen-studio/autogenstudio/chatmanager.py
index 222e7951e..674ae3506 100644
--- a/samples/apps/autogen-studio/autogenstudio/chatmanager.py
+++ b/samples/apps/autogen-studio/autogenstudio/chatmanager.py
@@ -1,12 +1,14 @@
import asyncio
-from datetime import datetime
import json
-from queue import Queue
-import time
-from typing import Any, List, Dict, Optional, Tuple
import os
-from fastapi import WebSocket, WebSocketDisconnect
+import time
+from datetime import datetime
+from queue import Queue
+from typing import Any, Dict, List, Optional, Tuple
+
import websockets
+from fastapi import WebSocket, WebSocketDisconnect
+
from .datamodel import AgentWorkFlowConfig, Message, SocketMessage
from .utils import extract_successful_code_blocks, get_modified_files, summarize_chat_history
from .workflowmanager import AutoGenWorkFlowManager
diff --git a/samples/apps/autogen-studio/autogenstudio/cli.py b/samples/apps/autogen-studio/autogenstudio/cli.py
index ed4e89f2a..aafb13317 100644
--- a/samples/apps/autogen-studio/autogenstudio/cli.py
+++ b/samples/apps/autogen-studio/autogenstudio/cli.py
@@ -1,10 +1,11 @@
import os
-from typing_extensions import Annotated
+
import typer
import uvicorn
+from typing_extensions import Annotated
-from .version import VERSION
from .utils.dbutils import DBManager
+from .version import VERSION
app = typer.Typer()
diff --git a/samples/apps/autogen-studio/autogenstudio/datamodel.py b/samples/apps/autogen-studio/autogenstudio/datamodel.py
index 8bebdb63e..083bddccf 100644
--- a/samples/apps/autogen-studio/autogenstudio/datamodel.py
+++ b/samples/apps/autogen-studio/autogenstudio/datamodel.py
@@ -1,8 +1,9 @@
import uuid
+from dataclasses import asdict, field
from datetime import datetime
from typing import Any, Callable, Dict, List, Literal, Optional, Union
+
from pydantic.dataclasses import dataclass
-from dataclasses import asdict, field
@dataclass
diff --git a/samples/apps/autogen-studio/autogenstudio/utils/dbutils.py b/samples/apps/autogen-studio/autogenstudio/utils/dbutils.py
index a7c4b7d4c..dca0fc6b0 100644
--- a/samples/apps/autogen-studio/autogenstudio/utils/dbutils.py
+++ b/samples/apps/autogen-studio/autogenstudio/utils/dbutils.py
@@ -1,13 +1,13 @@
import json
import logging
+import os
import sqlite3
import threading
-import os
-from typing import Any, List, Dict, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple
+
from ..datamodel import AgentFlowSpec, AgentWorkFlowConfig, Gallery, Message, Model, Session, Skill
from ..version import __version__ as __db_version__
-
VERSION_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS version (
diff --git a/samples/apps/autogen-studio/autogenstudio/utils/utils.py b/samples/apps/autogen-studio/autogenstudio/utils/utils.py
index 8795037cf..49a8ac91a 100644
--- a/samples/apps/autogen-studio/autogenstudio/utils/utils.py
+++ b/samples/apps/autogen-studio/autogenstudio/utils/utils.py
@@ -1,14 +1,17 @@
import base64
import hashlib
-from typing import List, Dict, Tuple, Union
import os
+import re
import shutil
from pathlib import Path
-import re
+from typing import Dict, List, Tuple, Union
+
+from dotenv import load_dotenv
+
import autogen
from autogen.oai.client import OpenAIWrapper
+
from ..datamodel import AgentConfig, AgentFlowSpec, AgentWorkFlowConfig, LLMConfig, Model, Skill
-from dotenv import load_dotenv
from ..version import APP_NAME
diff --git a/samples/apps/autogen-studio/autogenstudio/web/app.py b/samples/apps/autogen-studio/autogenstudio/web/app.py
index 48c29ac38..6d5412e9f 100644
--- a/samples/apps/autogen-studio/autogenstudio/web/app.py
+++ b/samples/apps/autogen-studio/autogenstudio/web/app.py
@@ -1,26 +1,25 @@
import asyncio
-from contextlib import asynccontextmanager
import json
import os
import queue
import threading
import traceback
-from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+from contextlib import asynccontextmanager
+
+from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
-from fastapi import HTTPException
from openai import OpenAIError
-from ..version import VERSION, APP_NAME
+from ..chatmanager import AutoGenChatManager, WebSocketConnectionManager
from ..datamodel import (
DBWebRequestModel,
DeleteMessageWebRequestModel,
Message,
Session,
)
-from ..utils import md5_hash, init_app_folders, DBManager, dbutils, test_model
-from ..chatmanager import AutoGenChatManager, WebSocketConnectionManager
-
+from ..utils import DBManager, dbutils, init_app_folders, md5_hash, test_model
+from ..version import APP_NAME, VERSION
managers = {"chat": None} # manage calls to autogen
# Create thread-safe queue for messages between api thread and autogen threads
diff --git a/samples/apps/autogen-studio/autogenstudio/workflowmanager.py b/samples/apps/autogen-studio/autogenstudio/workflowmanager.py
index 628c7f9f7..c5475e58d 100644
--- a/samples/apps/autogen-studio/autogenstudio/workflowmanager.py
+++ b/samples/apps/autogen-studio/autogenstudio/workflowmanager.py
@@ -1,12 +1,13 @@
import os
-from typing import List, Optional, Union, Dict
+from datetime import datetime
+from typing import Dict, List, Optional, Union
from requests import Session
import autogen
+
from .datamodel import AgentConfig, AgentFlowSpec, AgentWorkFlowConfig, Message, SocketMessage
-from .utils import get_skills_from_prompt, clear_folder, sanitize_model
-from datetime import datetime
+from .utils import clear_folder, get_skills_from_prompt, sanitize_model
class AutoGenWorkFlowManager:
diff --git a/samples/apps/autogen-studio/notebooks/tutorial.ipynb b/samples/apps/autogen-studio/notebooks/tutorial.ipynb
index 050089986..da7585937 100644
--- a/samples/apps/autogen-studio/notebooks/tutorial.ipynb
+++ b/samples/apps/autogen-studio/notebooks/tutorial.ipynb
@@ -7,6 +7,7 @@
"outputs": [],
"source": [
"import json\n",
+ "\n",
"from autogenstudio import AgentWorkFlowConfig, AutoGenWorkFlowManager"
]
},
diff --git a/samples/apps/cap/py/autogencap/Actor.py b/samples/apps/cap/py/autogencap/Actor.py
index f757e4803..7057ddc81 100644
--- a/samples/apps/cap/py/autogencap/Actor.py
+++ b/samples/apps/cap/py/autogencap/Actor.py
@@ -1,9 +1,11 @@
-import zmq
import threading
-import traceback
import time
-from .DebugLog import Debug, Info, Error
+import traceback
+
+import zmq
+
from .Config import xpub_url
+from .DebugLog import Debug, Error, Info
class Actor:
diff --git a/samples/apps/cap/py/autogencap/ActorConnector.py b/samples/apps/cap/py/autogencap/ActorConnector.py
index 44c9bc447..c7b16157d 100644
--- a/samples/apps/cap/py/autogencap/ActorConnector.py
+++ b/samples/apps/cap/py/autogencap/ActorConnector.py
@@ -1,14 +1,16 @@
# Agent_Sender takes a zmq context, Topic and creates a
# socket that can publish to that topic. It exposes this functionality
# using send_msg method
-import zmq
-from zmq.utils.monitor import recv_monitor_message
import time
import uuid
-from .DebugLog import Debug, Error, Info
-from .Config import xsub_url, xpub_url, router_url
from typing import Any, Dict
+import zmq
+from zmq.utils.monitor import recv_monitor_message
+
+from .Config import router_url, xpub_url, xsub_url
+from .DebugLog import Debug, Error, Info
+
class ActorSender:
def __init__(self, context, topic):
diff --git a/samples/apps/cap/py/autogencap/Broker.py b/samples/apps/cap/py/autogencap/Broker.py
index 03e101e02..2fd430d1b 100644
--- a/samples/apps/cap/py/autogencap/Broker.py
+++ b/samples/apps/cap/py/autogencap/Broker.py
@@ -1,8 +1,10 @@
+import threading
import time
+
import zmq
-import threading
+
+from autogencap.Config import router_url, xpub_url, xsub_url
from autogencap.DebugLog import Debug, Info, Warn
-from autogencap.Config import xsub_url, xpub_url, router_url
class Broker:
diff --git a/samples/apps/cap/py/autogencap/DebugLog.py b/samples/apps/cap/py/autogencap/DebugLog.py
index b86a497c6..e03712355 100644
--- a/samples/apps/cap/py/autogencap/DebugLog.py
+++ b/samples/apps/cap/py/autogencap/DebugLog.py
@@ -1,8 +1,10 @@
-import threading
import datetime
-import autogencap.Config as Config
+import threading
+
from termcolor import colored
+import autogencap.Config as Config
+
# Define log levels as constants
DEBUG = 0
INFO = 1
diff --git a/samples/apps/cap/py/autogencap/DirectorySvc.py b/samples/apps/cap/py/autogencap/DirectorySvc.py
index bde156062..0bc9bcf03 100644
--- a/samples/apps/cap/py/autogencap/DirectorySvc.py
+++ b/samples/apps/cap/py/autogencap/DirectorySvc.py
@@ -1,27 +1,30 @@
-from autogencap.Constants import Directory_Svc_Topic
-from autogencap.Config import xpub_url, xsub_url, router_url
-from autogencap.DebugLog import Debug, Info, Error
-from autogencap.ActorConnector import ActorConnector, ActorSender
+import re
+import threading
+import time
+
+import zmq
+
from autogencap.Actor import Actor
+from autogencap.ActorConnector import ActorConnector, ActorSender
from autogencap.Broker import Broker
+from autogencap.Config import router_url, xpub_url, xsub_url
+from autogencap.Constants import Directory_Svc_Topic
+from autogencap.DebugLog import Debug, Error, Info
from autogencap.proto.CAP_pb2 import (
- ActorRegistration,
ActorInfo,
+ ActorInfoCollection,
ActorLookup,
ActorLookupResponse,
+ ActorRegistration,
+ ErrorCode,
Ping,
Pong,
- ActorInfoCollection,
+)
+from autogencap.proto.CAP_pb2 import (
Error as ErrorMsg,
- ErrorCode,
)
from autogencap.utility import report_error_msg
-import zmq
-import threading
-import time
-import re
-
# TODO (Future DirectorySv PR) use actor description, network_id, other properties to make directory
# service more generic and powerful
diff --git a/samples/apps/cap/py/autogencap/LocalActorNetwork.py b/samples/apps/cap/py/autogencap/LocalActorNetwork.py
index 907e852d3..336555368 100644
--- a/samples/apps/cap/py/autogencap/LocalActorNetwork.py
+++ b/samples/apps/cap/py/autogencap/LocalActorNetwork.py
@@ -1,13 +1,15 @@
+import time
+from typing import List
+
import zmq
-from .DebugLog import Debug, Warn
+
+from .Actor import Actor
from .ActorConnector import ActorConnector
from .Broker import Broker
-from .DirectorySvc import DirectorySvc
from .Constants import Termination_Topic
-from .Actor import Actor
+from .DebugLog import Debug, Warn
+from .DirectorySvc import DirectorySvc
from .proto.CAP_pb2 import ActorInfo, ActorInfoCollection
-from typing import List
-import time
# TODO: remove time import
diff --git a/samples/apps/cap/py/autogencap/ag_adapter/AG2CAP.py b/samples/apps/cap/py/autogencap/ag_adapter/AG2CAP.py
index 6dfd6c518..5ce12a538 100644
--- a/samples/apps/cap/py/autogencap/ag_adapter/AG2CAP.py
+++ b/samples/apps/cap/py/autogencap/ag_adapter/AG2CAP.py
@@ -1,8 +1,10 @@
import time
from typing import Callable, Dict, List, Optional, Union
+
from autogen import Agent, ConversableAgent
-from .AutoGenConnector import AutoGenConnector
+
from ..LocalActorNetwork import LocalActorNetwork
+from .AutoGenConnector import AutoGenConnector
class AG2CAP(ConversableAgent):
diff --git a/samples/apps/cap/py/autogencap/ag_adapter/AGActor.py b/samples/apps/cap/py/autogencap/ag_adapter/AGActor.py
index f53d9c0a0..fd14a8805 100644
--- a/samples/apps/cap/py/autogencap/ag_adapter/AGActor.py
+++ b/samples/apps/cap/py/autogencap/ag_adapter/AGActor.py
@@ -1,4 +1,5 @@
import zmq
+
from autogencap.Actor import Actor
from autogencap.Constants import Termination_Topic
from autogencap.DebugLog import Debug
diff --git a/samples/apps/cap/py/autogencap/ag_adapter/AutoGenConnector.py b/samples/apps/cap/py/autogencap/ag_adapter/AutoGenConnector.py
index ee94cdabb..3fbb0db64 100644
--- a/samples/apps/cap/py/autogencap/ag_adapter/AutoGenConnector.py
+++ b/samples/apps/cap/py/autogencap/ag_adapter/AutoGenConnector.py
@@ -1,5 +1,7 @@
from typing import Dict, Optional, Union
+
from autogen import Agent
+
from ..ActorConnector import ActorConnector
from ..proto.Autogen_pb2 import GenReplyReq, GenReplyResp, PrepChat, ReceiveReq, Terminate
diff --git a/samples/apps/cap/py/autogencap/ag_adapter/CAP2AG.py b/samples/apps/cap/py/autogencap/ag_adapter/CAP2AG.py
index f21da46dd..50a0a4751 100644
--- a/samples/apps/cap/py/autogencap/ag_adapter/CAP2AG.py
+++ b/samples/apps/cap/py/autogencap/ag_adapter/CAP2AG.py
@@ -1,11 +1,13 @@
from enum import Enum
from typing import Optional
+
+from autogen import ConversableAgent
+
from ..DebugLog import Debug, Error, Info, Warn, shorten
from ..LocalActorNetwork import LocalActorNetwork
from ..proto.Autogen_pb2 import GenReplyReq, GenReplyResp, PrepChat, ReceiveReq, Terminate
-from .AGActor import AGActor
from .AG2CAP import AG2CAP
-from autogen import ConversableAgent
+from .AGActor import AGActor
class CAP2AG(AGActor):
diff --git a/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChat.py b/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChat.py
index 1e8b2ec5f..5d0a152a5 100644
--- a/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChat.py
+++ b/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChat.py
@@ -1,8 +1,9 @@
+from typing import List
+
from autogen import Agent, AssistantAgent, GroupChat
from autogencap.ag_adapter.AG2CAP import AG2CAP
from autogencap.ag_adapter.CAP2AG import CAP2AG
from autogencap.LocalActorNetwork import LocalActorNetwork
-from typing import List
class CAPGroupChat(GroupChat):
diff --git a/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChatManager.py b/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChatManager.py
index e7fa2804b..65823d75a 100644
--- a/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChatManager.py
+++ b/samples/apps/cap/py/autogencap/ag_adapter/CAPGroupChatManager.py
@@ -1,9 +1,10 @@
+import time
+
from autogen import GroupChatManager
from autogencap.ActorConnector import ActorConnector
-from autogencap.LocalActorNetwork import LocalActorNetwork
from autogencap.ag_adapter.CAP2AG import CAP2AG
from autogencap.ag_adapter.CAPGroupChat import CAPGroupChat
-import time
+from autogencap.LocalActorNetwork import LocalActorNetwork
class CAPGroupChatManager:
diff --git a/samples/apps/cap/py/autogencap/setup.py b/samples/apps/cap/py/autogencap/setup.py
index 0e239864e..5fd1dcfe6 100644
--- a/samples/apps/cap/py/autogencap/setup.py
+++ b/samples/apps/cap/py/autogencap/setup.py
@@ -1,4 +1,4 @@
-from setuptools import setup, find_packages
+from setuptools import find_packages, setup
setup(
name="autogencap",
diff --git a/samples/apps/cap/py/autogencap/utility.py b/samples/apps/cap/py/autogencap/utility.py
index ca45690f2..2083e565f 100644
--- a/samples/apps/cap/py/autogencap/utility.py
+++ b/samples/apps/cap/py/autogencap/utility.py
@@ -1,5 +1,6 @@
from autogencap.DebugLog import Error
-from autogencap.proto.CAP_pb2 import Error as ErrorMsg, ErrorCode
+from autogencap.proto.CAP_pb2 import Error as ErrorMsg
+from autogencap.proto.CAP_pb2 import ErrorCode
def report_error_msg(msg: ErrorMsg, src: str):
diff --git a/samples/apps/cap/py/demo/App.py b/samples/apps/cap/py/demo/App.py
index a952a27c3..19411a9b3 100644
--- a/samples/apps/cap/py/demo/App.py
+++ b/samples/apps/cap/py/demo/App.py
@@ -3,17 +3,18 @@ Demo App
"""
import argparse
+
import _paths
import autogencap.Config as Config
import autogencap.DebugLog as DebugLog
-from SimpleActorDemo import simple_actor_demo
from AGDemo import ag_demo
from AGGroupChatDemo import ag_groupchat_demo
from CAPAutGenGroupDemo import cap_ag_group_demo
from CAPAutoGenPairDemo import cap_ag_pair_demo
from ComplexActorDemo import complex_actor_demo
-from RemoteAGDemo import remote_ag_demo
from list_agents import list_agents
+from RemoteAGDemo import remote_ag_demo
+from SimpleActorDemo import simple_actor_demo
####################################################################################################
diff --git a/samples/apps/cap/py/demo/AppAgents.py b/samples/apps/cap/py/demo/AppAgents.py
index 3109f74a4..1a035b751 100644
--- a/samples/apps/cap/py/demo/AppAgents.py
+++ b/samples/apps/cap/py/demo/AppAgents.py
@@ -4,10 +4,10 @@ Each agent represents a different role and knows how to connect to external syst
to retrieve information.
"""
+from autogencap.Actor import Actor
+from autogencap.ActorConnector import ActorConnector
from autogencap.DebugLog import Debug, Info, shorten
from autogencap.LocalActorNetwork import LocalActorNetwork
-from autogencap.ActorConnector import ActorConnector
-from autogencap.Actor import Actor
class GreeterAgent(Actor):
diff --git a/samples/apps/cap/py/demo/CAPAutGenGroupDemo.py b/samples/apps/cap/py/demo/CAPAutGenGroupDemo.py
index d3f650eb0..ec9250867 100644
--- a/samples/apps/cap/py/demo/CAPAutGenGroupDemo.py
+++ b/samples/apps/cap/py/demo/CAPAutGenGroupDemo.py
@@ -1,8 +1,9 @@
-from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
-from autogencap.DebugLog import Info
-from autogencap.LocalActorNetwork import LocalActorNetwork
from autogencap.ag_adapter.CAPGroupChat import CAPGroupChat
from autogencap.ag_adapter.CAPGroupChatManager import CAPGroupChatManager
+from autogencap.DebugLog import Info
+from autogencap.LocalActorNetwork import LocalActorNetwork
+
+from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
def cap_ag_group_demo():
diff --git a/samples/apps/cap/py/demo/CAPAutoGenPairDemo.py b/samples/apps/cap/py/demo/CAPAutoGenPairDemo.py
index 76a7d67bc..84aad4c8f 100644
--- a/samples/apps/cap/py/demo/CAPAutoGenPairDemo.py
+++ b/samples/apps/cap/py/demo/CAPAutoGenPairDemo.py
@@ -1,9 +1,11 @@
import time
-from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
-from autogencap.DebugLog import Info
+
from autogencap.ag_adapter.CAPPair import CAPPair
+from autogencap.DebugLog import Info
from autogencap.LocalActorNetwork import LocalActorNetwork
+from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
+
def cap_ag_pair_demo():
config_list = config_list_from_json(env_or_file="OAI_CONFIG_LIST")
diff --git a/samples/apps/cap/py/demo/ComplexActorDemo.py b/samples/apps/cap/py/demo/ComplexActorDemo.py
index 623668298..29ce2b31d 100644
--- a/samples/apps/cap/py/demo/ComplexActorDemo.py
+++ b/samples/apps/cap/py/demo/ComplexActorDemo.py
@@ -1,7 +1,8 @@
import time
-from termcolor import colored
-from autogencap.LocalActorNetwork import LocalActorNetwork
+
from AppAgents import FidelityAgent, FinancialPlannerAgent, PersonalAssistant, QuantAgent, RiskManager
+from autogencap.LocalActorNetwork import LocalActorNetwork
+from termcolor import colored
def complex_actor_demo():
diff --git a/samples/apps/cap/py/demo/SimpleActorDemo.py b/samples/apps/cap/py/demo/SimpleActorDemo.py
index a7662074d..c0d753a9d 100644
--- a/samples/apps/cap/py/demo/SimpleActorDemo.py
+++ b/samples/apps/cap/py/demo/SimpleActorDemo.py
@@ -1,7 +1,8 @@
import time
+
from AppAgents import GreeterAgent
-from autogencap.LocalActorNetwork import LocalActorNetwork
from autogencap.DebugLog import Error
+from autogencap.LocalActorNetwork import LocalActorNetwork
def simple_actor_demo():
diff --git a/samples/apps/cap/py/demo/_paths.py b/samples/apps/cap/py/demo/_paths.py
index 82e5877f0..6627383aa 100644
--- a/samples/apps/cap/py/demo/_paths.py
+++ b/samples/apps/cap/py/demo/_paths.py
@@ -1,7 +1,7 @@
# Add autogencap to system path in case autogencap is not pip installed
# Since this library has not been published to PyPi, it is not easy to install using pip
-import sys
import os
+import sys
absparent = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(absparent)
diff --git a/samples/apps/cap/py/demo/list_agents.py b/samples/apps/cap/py/demo/list_agents.py
index f96045896..050020946 100644
--- a/samples/apps/cap/py/demo/list_agents.py
+++ b/samples/apps/cap/py/demo/list_agents.py
@@ -1,9 +1,10 @@
import time
from typing import List
-from AppAgents import GreeterAgent, FidelityAgent
+
+from AppAgents import FidelityAgent, GreeterAgent
+from autogencap.DebugLog import Info
from autogencap.LocalActorNetwork import LocalActorNetwork
from autogencap.proto.CAP_pb2 import ActorInfo
-from autogencap.DebugLog import Info
def list_agents():
diff --git a/samples/apps/cap/py/demo/standalone/Assistant.py b/samples/apps/cap/py/demo/standalone/Assistant.py
index 81e9580eb..9d3d497fd 100644
--- a/samples/apps/cap/py/demo/standalone/Assistant.py
+++ b/samples/apps/cap/py/demo/standalone/Assistant.py
@@ -1,9 +1,11 @@
import time
+
import _paths
-from autogen import AssistantAgent, config_list_from_json
+from autogencap.ag_adapter.CAP2AG import CAP2AG
from autogencap.DebugLog import Info
from autogencap.LocalActorNetwork import LocalActorNetwork
-from autogencap.ag_adapter.CAP2AG import CAP2AG
+
+from autogen import AssistantAgent, config_list_from_json
# Starts the Broker and the Assistant. The UserProxy is started separately.
diff --git a/samples/apps/cap/py/demo/standalone/UserProxy.py b/samples/apps/cap/py/demo/standalone/UserProxy.py
index 6b70ae730..691b55d21 100644
--- a/samples/apps/cap/py/demo/standalone/UserProxy.py
+++ b/samples/apps/cap/py/demo/standalone/UserProxy.py
@@ -1,10 +1,12 @@
import time
+
import _paths
-from autogen import UserProxyAgent, config_list_from_json
-from autogencap.DebugLog import Info
-from autogencap.LocalActorNetwork import LocalActorNetwork
from autogencap.ag_adapter.CAP2AG import CAP2AG
from autogencap.Config import IGNORED_LOG_CONTEXTS
+from autogencap.DebugLog import Info
+from autogencap.LocalActorNetwork import LocalActorNetwork
+
+from autogen import UserProxyAgent, config_list_from_json
# Starts the Broker and the Assistant. The UserProxy is started separately.
diff --git a/samples/apps/cap/py/demo/standalone/_paths.py b/samples/apps/cap/py/demo/standalone/_paths.py
index 7b4559f82..b61d8f82d 100644
--- a/samples/apps/cap/py/demo/standalone/_paths.py
+++ b/samples/apps/cap/py/demo/standalone/_paths.py
@@ -1,7 +1,7 @@
# Add autogencap to system path in case autogencap is not pip installed
# Since this library has not been published to PyPi, it is not easy to install using pip
-import sys
import os
+import sys
absparent = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
sys.path.append(absparent)
diff --git a/samples/apps/cap/py/demo/zmq_tests.py b/samples/apps/cap/py/demo/zmq_tests.py
index b53adb00c..8550ce6c2 100644
--- a/samples/apps/cap/py/demo/zmq_tests.py
+++ b/samples/apps/cap/py/demo/zmq_tests.py
@@ -1,10 +1,11 @@
-import _paths
import sys
import time
from typing import Any, Dict
+
+import _paths
import zmq
+from autogencap.Config import dealer_url, router_url, xpub_url, xsub_url
from zmq.utils.monitor import recv_monitor_message
-from autogencap.Config import xsub_url, xpub_url, router_url, dealer_url
def zmq_sub_test():
diff --git a/samples/simple_chat.py b/samples/simple_chat.py
index 1a251c5e2..a0eb33a1c 100644
--- a/samples/simple_chat.py
+++ b/samples/simple_chat.py
@@ -1,4 +1,4 @@
-from autogen import UserProxyAgent, ConversableAgent, config_list_from_json
+from autogen import ConversableAgent, UserProxyAgent, config_list_from_json
def main():
diff --git a/samples/tools/autogenbench/autogenbench/cli.py b/samples/tools/autogenbench/autogenbench/cli.py
index 6b27a8aeb..8733bb915 100644
--- a/samples/tools/autogenbench/autogenbench/cli.py
+++ b/samples/tools/autogenbench/autogenbench/cli.py
@@ -1,8 +1,9 @@
import sys
-from .version import __version__
-from .run_cmd import run_cli
+
from .clone_cmd import clone_cli
+from .run_cmd import run_cli
from .tabulate_cmd import tabulate_cli
+from .version import __version__
def main(args=None):
diff --git a/samples/tools/autogenbench/autogenbench/clone_cmd.py b/samples/tools/autogenbench/autogenbench/clone_cmd.py
index db9904d68..553ef108e 100644
--- a/samples/tools/autogenbench/autogenbench/clone_cmd.py
+++ b/samples/tools/autogenbench/autogenbench/clone_cmd.py
@@ -1,7 +1,9 @@
-import os
-import json
import argparse
+import json
+import os
+
import requests
+
from .load_module import load_module
# Figure out where everything is
diff --git a/samples/tools/autogenbench/autogenbench/load_module.py b/samples/tools/autogenbench/autogenbench/load_module.py
index bf1824259..fc4e14ff9 100644
--- a/samples/tools/autogenbench/autogenbench/load_module.py
+++ b/samples/tools/autogenbench/autogenbench/load_module.py
@@ -1,6 +1,6 @@
+import importlib.util
import os
import sys
-import importlib.util
def load_module(module_path):
diff --git a/samples/tools/autogenbench/autogenbench/run_cmd.py b/samples/tools/autogenbench/autogenbench/run_cmd.py
index d8f9faeac..9e3c48ce5 100644
--- a/samples/tools/autogenbench/autogenbench/run_cmd.py
+++ b/samples/tools/autogenbench/autogenbench/run_cmd.py
@@ -1,16 +1,19 @@
-import os
+import argparse
import errno
+import json
+import os
+import pathlib
+import random
import shutil
import subprocess
-import json
import sys
import time
-import pathlib
-import argparse
+
import docker
-import random
+
from autogen import config_list_from_json
from autogen.oai.openai_utils import filter_config
+
from .version import __version__
# Figure out where everything is
diff --git a/samples/tools/autogenbench/autogenbench/tabulate_cmd.py b/samples/tools/autogenbench/autogenbench/tabulate_cmd.py
index b4b90da80..b93125cfc 100644
--- a/samples/tools/autogenbench/autogenbench/tabulate_cmd.py
+++ b/samples/tools/autogenbench/autogenbench/tabulate_cmd.py
@@ -1,7 +1,9 @@
+import argparse
import os
import sys
-import argparse
+
import tabulate as tb
+
from .load_module import load_module
# Figure out where everything is
diff --git a/samples/tools/autogenbench/autogenbench/template/testbed_utils.py b/samples/tools/autogenbench/autogenbench/template/testbed_utils.py
index a9a956158..05ef9662e 100644
--- a/samples/tools/autogenbench/autogenbench/template/testbed_utils.py
+++ b/samples/tools/autogenbench/autogenbench/template/testbed_utils.py
@@ -1,8 +1,10 @@
-from pkg_resources import packaging
-from datetime import datetime
+import json
import os
+from datetime import datetime
+
+from pkg_resources import packaging
+
import autogen
-import json
AUTOGEN_VERSION = packaging.version.parse(autogen.__version__)
diff --git a/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/custom_tabulate.py b/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/custom_tabulate.py
index ba8700d1f..7c689cdfe 100644
--- a/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/custom_tabulate.py
+++ b/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/custom_tabulate.py
@@ -1,5 +1,6 @@
import os
import sys
+
from autogenbench.tabulate_cmd import default_tabulate
diff --git a/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/init_tasks.py b/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/init_tasks.py
index 2f5ba5f40..a5c7556f3 100644
--- a/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/init_tasks.py
+++ b/samples/tools/autogenbench/scenarios/AutoGPT/Scripts/init_tasks.py
@@ -3,12 +3,13 @@
# (default: ../scenarios/human_eval_two_agents_gpt4.jsonl and ./scenarios/human_eval_two_agents_gpt35.jsonl)
#
+import base64
+import glob
import json
import os
-import sys
-import glob
-import base64
import re
+import sys
+
from huggingface_hub import snapshot_download
SCRIPT_PATH = os.path.realpath(__file__)
diff --git a/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/check.py b/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/check.py
index c9b4c0e0f..9bd289d15 100644
--- a/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/check.py
+++ b/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/check.py
@@ -2,11 +2,11 @@
# ruff: noqa: F821
import glob
+import json
import os
+import shutil
import subprocess
import sys
-import shutil
-import json
def scoring(content: str, should_contain: list, should_not_contain: list):
diff --git a/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/scenario.py b/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/scenario.py
index eba850334..42dcbadbe 100644
--- a/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/scenario.py
+++ b/samples/tools/autogenbench/scenarios/AutoGPT/Templates/TwoAgents/scenario.py
@@ -2,9 +2,11 @@
# ruff: noqa: E722
import traceback
-from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
+
import testbed_utils
+from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
+
# Assistant agent can call check.py to check if all the unit tests have passed
testbed_utils.init()
diff --git a/samples/tools/autogenbench/scenarios/Examples/Templates/ThreeAgents/scenario.py b/samples/tools/autogenbench/scenarios/Examples/Templates/ThreeAgents/scenario.py
index 6aa2456de..526569f68 100644
--- a/samples/tools/autogenbench/scenarios/Examples/Templates/ThreeAgents/scenario.py
+++ b/samples/tools/autogenbench/scenarios/Examples/Templates/ThreeAgents/scenario.py
@@ -1,8 +1,10 @@
-import os
import json
-import autogen
+import os
+
import testbed_utils
+import autogen
+
testbed_utils.init()
##############################
diff --git a/samples/tools/autogenbench/scenarios/Examples/Templates/TwoAgents/scenario.py b/samples/tools/autogenbench/scenarios/Examples/Templates/TwoAgents/scenario.py
index ae2682562..4b9f48304 100644
--- a/samples/tools/autogenbench/scenarios/Examples/Templates/TwoAgents/scenario.py
+++ b/samples/tools/autogenbench/scenarios/Examples/Templates/TwoAgents/scenario.py
@@ -1,8 +1,10 @@
-import os
import json
-import autogen
+import os
+
import testbed_utils
+import autogen
+
testbed_utils.init()
##############################
diff --git a/samples/tools/autogenbench/scenarios/GAIA/Scripts/custom_tabulate.py b/samples/tools/autogenbench/scenarios/GAIA/Scripts/custom_tabulate.py
index 144f882af..7a76019a3 100644
--- a/samples/tools/autogenbench/scenarios/GAIA/Scripts/custom_tabulate.py
+++ b/samples/tools/autogenbench/scenarios/GAIA/Scripts/custom_tabulate.py
@@ -1,7 +1,8 @@
-import os
-import sys
import json
+import os
import re
+import sys
+
from autogenbench.tabulate_cmd import default_tabulate
diff --git a/samples/tools/autogenbench/scenarios/GAIA/Scripts/init_tasks.py b/samples/tools/autogenbench/scenarios/GAIA/Scripts/init_tasks.py
index 61e2864a2..437a24cf9 100644
--- a/samples/tools/autogenbench/scenarios/GAIA/Scripts/init_tasks.py
+++ b/samples/tools/autogenbench/scenarios/GAIA/Scripts/init_tasks.py
@@ -5,8 +5,9 @@
import json
import os
-import sys
import re
+import sys
+
from huggingface_hub import snapshot_download
SCRIPT_PATH = os.path.realpath(__file__)
diff --git a/samples/tools/autogenbench/scenarios/GAIA/Templates/BasicTwoAgents/scenario.py b/samples/tools/autogenbench/scenarios/GAIA/Templates/BasicTwoAgents/scenario.py
index 3f3f53f18..2ab489346 100644
--- a/samples/tools/autogenbench/scenarios/GAIA/Templates/BasicTwoAgents/scenario.py
+++ b/samples/tools/autogenbench/scenarios/GAIA/Templates/BasicTwoAgents/scenario.py
@@ -1,9 +1,11 @@
-import os
import json
-import autogen
+import os
from datetime import datetime
+
import testbed_utils
+import autogen
+
testbed_utils.init()
##############################
diff --git a/samples/tools/autogenbench/scenarios/GAIA/Templates/SocietyOfMind/scenario.py b/samples/tools/autogenbench/scenarios/GAIA/Templates/SocietyOfMind/scenario.py
index bacd22e09..337515dc7 100644
--- a/samples/tools/autogenbench/scenarios/GAIA/Templates/SocietyOfMind/scenario.py
+++ b/samples/tools/autogenbench/scenarios/GAIA/Templates/SocietyOfMind/scenario.py
@@ -1,15 +1,17 @@
# ruff: noqa: E722
+import copy
+import json
import os
import sys
-import json
-import autogen
-import copy
import traceback
from datetime import datetime
+
import testbed_utils
-from autogen.agentchat.contrib.web_surfer import WebSurferAgent
-from autogen.agentchat.contrib.society_of_mind_agent import SocietyOfMindAgent
+
+import autogen
from autogen.agentchat.contrib.group_chat_moderator import GroupChatModerator
+from autogen.agentchat.contrib.society_of_mind_agent import SocietyOfMindAgent
+from autogen.agentchat.contrib.web_surfer import WebSurferAgent
from autogen.token_count_utils import count_token, get_max_token_limit
testbed_utils.init()
diff --git a/samples/tools/autogenbench/scenarios/HumanEval/Scripts/custom_tabulate.py b/samples/tools/autogenbench/scenarios/HumanEval/Scripts/custom_tabulate.py
index ba8700d1f..7c689cdfe 100644
--- a/samples/tools/autogenbench/scenarios/HumanEval/Scripts/custom_tabulate.py
+++ b/samples/tools/autogenbench/scenarios/HumanEval/Scripts/custom_tabulate.py
@@ -1,5 +1,6 @@
import os
import sys
+
from autogenbench.tabulate_cmd import default_tabulate
diff --git a/samples/tools/autogenbench/scenarios/HumanEval/Scripts/init_tasks.py b/samples/tools/autogenbench/scenarios/HumanEval/Scripts/init_tasks.py
index 04480f5d2..c8d31d3a2 100644
--- a/samples/tools/autogenbench/scenarios/HumanEval/Scripts/init_tasks.py
+++ b/samples/tools/autogenbench/scenarios/HumanEval/Scripts/init_tasks.py
@@ -3,13 +3,14 @@
# (default: ../scenarios/human_eval_two_agents_gpt4.jsonl and ./scenarios/human_eval_two_agents_gpt35.jsonl)
#
-import requests
+import base64
import gzip
import io
import json
import os
import re
-import base64
+
+import requests
URL = "https://github.com/openai/human-eval/raw/master/data/HumanEval.jsonl.gz"
diff --git a/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatFourAgents/scenario.py b/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatFourAgents/scenario.py
index dacf7b839..f3408eed8 100644
--- a/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatFourAgents/scenario.py
+++ b/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatFourAgents/scenario.py
@@ -1,9 +1,11 @@
-import os
-import json
import base64
-import autogen
+import json
+import os
+
import testbed_utils
+import autogen
+
# NOTE:
# This scenario runs Human Eval in a slightly unconventional way:
# The agents have access to the unit tests, and can keep trying
diff --git a/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/scenario.py b/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/scenario.py
index 06b88638d..96fa94c49 100644
--- a/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/scenario.py
+++ b/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/scenario.py
@@ -1,9 +1,11 @@
-import os
-import json
import base64
-import autogen
+import json
+import os
+
import testbed_utils
+import autogen
+
# NOTE:
# This scenario runs Human Eval in a slightly unconventional way:
# The agents have access to the unit tests, and can keep trying
diff --git a/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/scenario.py b/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/scenario.py
index a4708a558..89a00021c 100644
--- a/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/scenario.py
+++ b/samples/tools/autogenbench/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/scenario.py
@@ -1,9 +1,11 @@
-import os
-import json
import base64
-import autogen
+import json
+import os
+
import testbed_utils
+import autogen
+
# NOTE:
# This scenario runs Human Eval in a slightly unconventional way:
# The agents have access to the unit tests, and can keep trying
diff --git a/samples/tools/autogenbench/scenarios/HumanEval/Templates/TwoAgents/scenario.py b/samples/tools/autogenbench/scenarios/HumanEval/Templates/TwoAgents/scenario.py
index 2d0815f6a..113417fb2 100644
--- a/samples/tools/autogenbench/scenarios/HumanEval/Templates/TwoAgents/scenario.py
+++ b/samples/tools/autogenbench/scenarios/HumanEval/Templates/TwoAgents/scenario.py
@@ -1,7 +1,9 @@
-import os
-import json
import base64
+import json
+import os
+
import testbed_utils
+
import autogen
# NOTE:
diff --git a/samples/tools/autogenbench/scenarios/MATH/Scripts/custom_tabulate.py b/samples/tools/autogenbench/scenarios/MATH/Scripts/custom_tabulate.py
index 2571145db..64c11a32e 100644
--- a/samples/tools/autogenbench/scenarios/MATH/Scripts/custom_tabulate.py
+++ b/samples/tools/autogenbench/scenarios/MATH/Scripts/custom_tabulate.py
@@ -1,6 +1,7 @@
+import json
import os
import sys
-import json
+
from autogenbench.tabulate_cmd import default_tabulate
diff --git a/samples/tools/autogenbench/scenarios/MATH/Scripts/init_tasks.py b/samples/tools/autogenbench/scenarios/MATH/Scripts/init_tasks.py
index 8b2d07995..eb532ee85 100644
--- a/samples/tools/autogenbench/scenarios/MATH/Scripts/init_tasks.py
+++ b/samples/tools/autogenbench/scenarios/MATH/Scripts/init_tasks.py
@@ -3,13 +3,14 @@
# (default: ../scenarios/human_eval_two_agents_gpt4.jsonl and ./scenarios/human_eval_two_agents_gpt35.jsonl)
#
-import requests
-import tarfile
import io
import json
import os
import re
import sys
+import tarfile
+
+import requests
URL = "https://people.eecs.berkeley.edu/~hendrycks/MATH.tar"
diff --git a/samples/tools/autogenbench/scenarios/MATH/Templates/TwoAgents/scenario.py b/samples/tools/autogenbench/scenarios/MATH/Templates/TwoAgents/scenario.py
index b9d92a335..1995ac4e1 100644
--- a/samples/tools/autogenbench/scenarios/MATH/Templates/TwoAgents/scenario.py
+++ b/samples/tools/autogenbench/scenarios/MATH/Templates/TwoAgents/scenario.py
@@ -1,8 +1,10 @@
-import os
import json
-import autogen
+import os
+
import testbed_utils
+import autogen
+
testbed_utils.init()
PROMPT = ""
diff --git a/samples/tools/finetuning/finetuning/update_model.py b/samples/tools/finetuning/finetuning/update_model.py
index df9fc6496..ad2fec523 100644
--- a/samples/tools/finetuning/finetuning/update_model.py
+++ b/samples/tools/finetuning/finetuning/update_model.py
@@ -1,6 +1,7 @@
-from autogen import ConversableAgent, Agent, OpenAIWrapper, ModelClient
from typing import Any, Dict, List, Protocol
+from autogen import Agent, ConversableAgent, ModelClient, OpenAIWrapper
+
class UpdateableModelClient(ModelClient, Protocol):
def update_model(
diff --git a/samples/tools/finetuning/tests/test_conversable_agent_update_model.py b/samples/tools/finetuning/tests/test_conversable_agent_update_model.py
index 56f9474a2..369bc4b17 100644
--- a/samples/tools/finetuning/tests/test_conversable_agent_update_model.py
+++ b/samples/tools/finetuning/tests/test_conversable_agent_update_model.py
@@ -1,12 +1,15 @@
+import sys
+
import pytest
+
from autogen import AssistantAgent, UserProxyAgent
-import sys
sys.path.append("samples/tools/finetuning")
-from finetuning import update_model # noqa: E402
from typing import Dict # noqa: E402
+from finetuning import update_model # noqa: E402
+
sys.path.append("test")
TEST_CUSTOM_RESPONSE = "This is a custom response."
diff --git a/samples/tools/webarena/webarena/run.py b/samples/tools/webarena/webarena/run.py
index a9411ea12..2fb15f7c1 100644
--- a/samples/tools/webarena/webarena/run.py
+++ b/samples/tools/webarena/webarena/run.py
@@ -12,16 +12,12 @@ import time
from pathlib import Path
import openai
-import autogen
-from webarena_agents import ActionTakingCapability, EnvironmentAgent
-
from agent import (
Agent,
PromptAgent,
TeacherForcingAgent,
construct_agent,
)
-
from agent.prompts import *
from browser_env import (
ScriptBrowserEnv,
@@ -31,6 +27,9 @@ from browser_env.helper_functions import (
RenderHelper,
)
from evaluation_harness import evaluator_router
+from webarena_agents import ActionTakingCapability, EnvironmentAgent
+
+import autogen
LOG_FOLDER = "log_files"
Path(LOG_FOLDER).mkdir(parents=True, exist_ok=True)
diff --git a/samples/tools/webarena/webarena/webarena_agents.py b/samples/tools/webarena/webarena/webarena_agents.py
index 103057259..ab97d6982 100644
--- a/samples/tools/webarena/webarena/webarena_agents.py
+++ b/samples/tools/webarena/webarena/webarena_agents.py
@@ -1,26 +1,23 @@
-import autogen
-
-from browser_env.actions import (
- ActionParsingError,
- Action,
- create_none_action,
- create_id_based_action,
- create_playwright_action,
-)
-
from browser_env import (
ActionTypes,
StateInfo,
Trajectory,
create_stop_action,
)
-
+from browser_env.actions import (
+ Action,
+ ActionParsingError,
+ create_id_based_action,
+ create_none_action,
+ create_playwright_action,
+ is_equivalent,
+)
from browser_env.helper_functions import (
RenderHelper,
get_action_description,
)
-from browser_env.actions import is_equivalent
+import autogen
def early_stop(trajectory: Trajectory, max_steps: int, thresholds: dict[str, int]) -> tuple[bool, str]:
diff --git a/test/agentchat/contrib/capabilities/chat_with_teachable_agent.py b/test/agentchat/contrib/capabilities/chat_with_teachable_agent.py
index 27f030045..14599c063 100755
--- a/test/agentchat/contrib/capabilities/chat_with_teachable_agent.py
+++ b/test/agentchat/contrib/capabilities/chat_with_teachable_agent.py
@@ -2,14 +2,13 @@
import os
import sys
-from autogen import UserProxyAgent, config_list_from_json
+
+from autogen import ConversableAgent, UserProxyAgent, config_list_from_json
from autogen.agentchat.contrib.capabilities.teachability import Teachability
-from autogen import ConversableAgent
from autogen.formatting_utils import colored
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
-from test_assistant_agent import OAI_CONFIG_LIST, KEY_LOC # noqa: E402
-
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST # noqa: E402
# Specify the model to use. GPT-3.5 is less reliable than GPT-4 at learning from user input.
filter_dict = {"model": ["gpt-4-0125-preview"]}
diff --git a/test/agentchat/contrib/capabilities/test_context_handling.py b/test/agentchat/contrib/capabilities/test_context_handling.py
index 6d7a77411..17cd7e9a6 100755
--- a/test/agentchat/contrib/capabilities/test_context_handling.py
+++ b/test/agentchat/contrib/capabilities/test_context_handling.py
@@ -1,12 +1,13 @@
#!/usr/bin/env python3 -m pytest
-import pytest
import os
import sys
+
+import pytest
+
import autogen
-from autogen import token_count_utils
+from autogen import AssistantAgent, UserProxyAgent, token_count_utils
from autogen.agentchat.contrib.capabilities.context_handling import TransformChatHistory
-from autogen import AssistantAgent, UserProxyAgent
# from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
@@ -14,7 +15,7 @@ sys.path.append(os.path.join(os.path.dirname(__file__), "../../.."))
from conftest import skip_openai # noqa: E402
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
-from test_assistant_agent import OAI_CONFIG_LIST, KEY_LOC # noqa: E402
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST # noqa: E402
try:
from openai import OpenAI
diff --git a/test/agentchat/contrib/capabilities/test_image_generation_capability.py b/test/agentchat/contrib/capabilities/test_image_generation_capability.py
index ff05fe728..fa62d1f46 100644
--- a/test/agentchat/contrib/capabilities/test_image_generation_capability.py
+++ b/test/agentchat/contrib/capabilities/test_image_generation_capability.py
@@ -1,9 +1,11 @@
import itertools
import os
+import sys
import tempfile
from typing import Any, Dict, Tuple
+
import pytest
-import sys
+
from autogen import code_utils
from autogen.agentchat.conversable_agent import ConversableAgent
from autogen.agentchat.user_proxy_agent import UserProxyAgent
diff --git a/test/agentchat/contrib/capabilities/test_teachable_agent.py b/test/agentchat/contrib/capabilities/test_teachable_agent.py
index e9fdf68c8..261bd4801 100755
--- a/test/agentchat/contrib/capabilities/test_teachable_agent.py
+++ b/test/agentchat/contrib/capabilities/test_teachable_agent.py
@@ -1,16 +1,18 @@
#!/usr/bin/env python3 -m pytest
-import pytest
import os
import sys
-from autogen.formatting_utils import colored
+
+import pytest
+
from autogen import ConversableAgent, config_list_from_json
+from autogen.formatting_utils import colored
sys.path.append(os.path.join(os.path.dirname(__file__), "../../.."))
from conftest import skip_openai # noqa: E402
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
-from test_assistant_agent import OAI_CONFIG_LIST, KEY_LOC # noqa: E402
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST # noqa: E402
try:
from autogen.agentchat.contrib.capabilities.teachability import Teachability
diff --git a/test/agentchat/contrib/test_agent_builder.py b/test/agentchat/contrib/test_agent_builder.py
index 58df86a32..614aa106a 100755
--- a/test/agentchat/contrib/test_agent_builder.py
+++ b/test/agentchat/contrib/test_agent_builder.py
@@ -1,15 +1,17 @@
#!/usr/bin/env python3 -m pytest
-import pytest
-import os
import json
+import os
import sys
+
+import pytest
+
from autogen.agentchat.contrib.agent_builder import AgentBuilder
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
from conftest import skip_openai as skip # noqa: E402
-from test_assistant_agent import OAI_CONFIG_LIST, KEY_LOC # noqa: E402
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST # noqa: E402
here = os.path.abspath(os.path.dirname(__file__))
diff --git a/test/agentchat/contrib/test_agent_optimizer.py b/test/agentchat/contrib/test_agent_optimizer.py
index fe0ba2dc2..e68eca57d 100644
--- a/test/agentchat/contrib/test_agent_optimizer.py
+++ b/test/agentchat/contrib/test_agent_optimizer.py
@@ -1,11 +1,11 @@
-import pytest
import os
+
+import pytest
from conftest import skip_openai as skip
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
import autogen
-from test_assistant_agent import OAI_CONFIG_LIST, KEY_LOC
from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
-
from autogen.agentchat.contrib.agent_optimizer import AgentOptimizer
here = os.path.abspath(os.path.dirname(__file__))
diff --git a/test/agentchat/contrib/test_compressible_agent.py b/test/agentchat/contrib/test_compressible_agent.py
index eeb08c010..b6e34a6d8 100755
--- a/test/agentchat/contrib/test_compressible_agent.py
+++ b/test/agentchat/contrib/test_compressible_agent.py
@@ -1,9 +1,11 @@
#!/usr/bin/env python3 -m pytest
-import pytest
+import os
import sys
+
+import pytest
+
import autogen
-import os
from autogen.agentchat.contrib.compressible_agent import CompressibleAgent
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
@@ -12,7 +14,7 @@ from conftest import skip_openai # noqa: E402
here = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
-from test_assistant_agent import OAI_CONFIG_LIST, KEY_LOC # noqa: E402
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST # noqa: E402
try:
import openai
diff --git a/test/agentchat/contrib/test_gpt_assistant.py b/test/agentchat/contrib/test_gpt_assistant.py
index 6c6198a74..916475491 100755
--- a/test/agentchat/contrib/test_gpt_assistant.py
+++ b/test/agentchat/contrib/test_gpt_assistant.py
@@ -1,14 +1,15 @@
#!/usr/bin/env python3 -m pytest
-from unittest.mock import MagicMock
-import uuid
-import pytest
import os
import sys
+import uuid
+from unittest.mock import MagicMock
+
import openai
+import pytest
+
import autogen
-from autogen import OpenAIWrapper
-from autogen import UserProxyAgent
+from autogen import OpenAIWrapper, UserProxyAgent
from autogen.agentchat.contrib.gpt_assistant_agent import GPTAssistantAgent
from autogen.oai.openai_utils import retrieve_assistants_by_name
diff --git a/test/agentchat/contrib/test_llava.py b/test/agentchat/contrib/test_llava.py
index 11fcd3ab5..a77088816 100755
--- a/test/agentchat/contrib/test_llava.py
+++ b/test/agentchat/contrib/test_llava.py
@@ -4,9 +4,10 @@ import unittest
from unittest.mock import MagicMock, patch
import pytest
-import autogen
from conftest import MOCK_OPEN_AI_API_KEY
+import autogen
+
try:
from autogen.agentchat.contrib.llava_agent import LLaVAAgent, _llava_call_binary_with_config, llava_call
except ImportError:
diff --git a/test/agentchat/contrib/test_lmm.py b/test/agentchat/contrib/test_lmm.py
index e97617e8e..3374f28b6 100755
--- a/test/agentchat/contrib/test_lmm.py
+++ b/test/agentchat/contrib/test_lmm.py
@@ -4,12 +4,11 @@ import unittest
from unittest.mock import MagicMock
import pytest
+from conftest import MOCK_OPEN_AI_API_KEY
import autogen
from autogen.agentchat.conversable_agent import ConversableAgent
-from conftest import MOCK_OPEN_AI_API_KEY
-
try:
from autogen.agentchat.contrib.img_utils import get_pil_image
from autogen.agentchat.contrib.multimodal_conversable_agent import MultimodalConversableAgent
diff --git a/test/agentchat/contrib/test_qdrant_retrievechat.py b/test/agentchat/contrib/test_qdrant_retrievechat.py
index 5d30ad8c2..e4bede174 100755
--- a/test/agentchat/contrib/test_qdrant_retrievechat.py
+++ b/test/agentchat/contrib/test_qdrant_retrievechat.py
@@ -2,9 +2,11 @@
import os
import sys
+
import pytest
-from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent
+
from autogen import config_list_from_json
+from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
from conftest import skip_openai # noqa: E402
@@ -13,13 +15,14 @@ sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST # noqa: E402
try:
+ import fastembed
from qdrant_client import QdrantClient
+
from autogen.agentchat.contrib.qdrant_retrieve_user_proxy_agent import (
- create_qdrant_from_dir,
QdrantRetrieveUserProxyAgent,
+ create_qdrant_from_dir,
query_qdrant,
)
- import fastembed
QDRANT_INSTALLED = True
except ImportError:
diff --git a/test/agentchat/contrib/test_retrievechat.py b/test/agentchat/contrib/test_retrievechat.py
index bed407a13..e7bbc9750 100755
--- a/test/agentchat/contrib/test_retrievechat.py
+++ b/test/agentchat/contrib/test_retrievechat.py
@@ -1,8 +1,10 @@
#!/usr/bin/env python3 -m pytest
-import pytest
import os
import sys
+
+import pytest
+
import autogen
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
@@ -12,15 +14,16 @@ sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST # noqa: E402
try:
+ import chromadb
import openai
+ from chromadb.utils import embedding_functions as ef
+
from autogen.agentchat.contrib.retrieve_assistant_agent import (
RetrieveAssistantAgent,
)
from autogen.agentchat.contrib.retrieve_user_proxy_agent import (
RetrieveUserProxyAgent,
)
- import chromadb
- from chromadb.utils import embedding_functions as ef
except ImportError:
skip = True
else:
diff --git a/test/agentchat/contrib/test_society_of_mind_agent.py b/test/agentchat/contrib/test_society_of_mind_agent.py
index b439a1773..ff83b97eb 100755
--- a/test/agentchat/contrib/test_society_of_mind_agent.py
+++ b/test/agentchat/contrib/test_society_of_mind_agent.py
@@ -1,10 +1,12 @@
#!/usr/bin/env python3 -m pytest
-import pytest
-import sys
-import autogen
import os
+import sys
+
+import pytest
from typing_extensions import Annotated
+
+import autogen
from autogen.agentchat.contrib.society_of_mind_agent import SocietyOfMindAgent
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
diff --git a/test/agentchat/contrib/test_web_surfer.py b/test/agentchat/contrib/test_web_surfer.py
index e53342fd8..697d145fc 100755
--- a/test/agentchat/contrib/test_web_surfer.py
+++ b/test/agentchat/contrib/test_web_surfer.py
@@ -1,9 +1,11 @@
#!/usr/bin/env python3 -m pytest
import os
-import sys
import re
+import sys
+
import pytest
+
from autogen import UserProxyAgent, config_list_from_json
from autogen.oai.openai_utils import filter_config
diff --git a/test/agentchat/test_agent_logging.py b/test/agentchat/test_agent_logging.py
index 8de4712de..870704db3 100644
--- a/test/agentchat/test_agent_logging.py
+++ b/test/agentchat/test_agent_logging.py
@@ -1,14 +1,14 @@
-import pytest
-import autogen
-import autogen.runtime_logging
import json
+import sqlite3
import sys
import uuid
-import sqlite3
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+import pytest
from conftest import skip_openai
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+import autogen
+import autogen.runtime_logging
TEACHER_MESSAGE = """
You are roleplaying a math teacher, and your job is to help your students with linear algebra.
diff --git a/test/agentchat/test_agent_setup_with_use_docker_settings.py b/test/agentchat/test_agent_setup_with_use_docker_settings.py
index 4ec05ae1a..4669232cf 100644
--- a/test/agentchat/test_agent_setup_with_use_docker_settings.py
+++ b/test/agentchat/test_agent_setup_with_use_docker_settings.py
@@ -1,11 +1,12 @@
-from autogen import UserProxyAgent
+import os
+
import pytest
from conftest import skip_openai
-import os
+from autogen import UserProxyAgent
from autogen.code_utils import (
- is_docker_running,
in_docker_container,
+ is_docker_running,
)
try:
diff --git a/test/agentchat/test_agent_usage.py b/test/agentchat/test_agent_usage.py
index 7622e908f..212c5513e 100755
--- a/test/agentchat/test_agent_usage.py
+++ b/test/agentchat/test_agent_usage.py
@@ -1,13 +1,14 @@
#!/usr/bin/env python3 -m pytest
-from autogen import gather_usage_summary
-from autogen import AssistantAgent, UserProxyAgent
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+import io
+from contextlib import redirect_stdout
+
import pytest
from conftest import skip_openai
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+
import autogen
-import io
-from contextlib import redirect_stdout
+from autogen import AssistantAgent, UserProxyAgent, gather_usage_summary
try:
import openai
diff --git a/test/agentchat/test_agentchat_utils.py b/test/agentchat/test_agentchat_utils.py
index 99ccb9c13..a52b4ed77 100644
--- a/test/agentchat/test_agentchat_utils.py
+++ b/test/agentchat/test_agentchat_utils.py
@@ -1,7 +1,9 @@
from typing import Dict, List, Union
-from autogen import agentchat
+
import pytest
+from autogen import agentchat
+
TAG_PARSING_TESTS = [
{
"message": "Hello agent, can you take a look at this image <img http://example.com/image.png>",
diff --git a/test/agentchat/test_assistant_agent.py b/test/agentchat/test_assistant_agent.py
index b99ed5766..a2c99ba63 100755
--- a/test/agentchat/test_assistant_agent.py
+++ b/test/agentchat/test_assistant_agent.py
@@ -2,7 +2,9 @@
import os
import sys
+
import pytest
+
import autogen
from autogen.agentchat import AssistantAgent, UserProxyAgent
diff --git a/test/agentchat/test_async.py b/test/agentchat/test_async.py
index 5fe99dd67..5d6db1ab7 100755
--- a/test/agentchat/test_async.py
+++ b/test/agentchat/test_async.py
@@ -1,11 +1,13 @@
#!/usr/bin/env python3 -m pytest
-import pytest
import asyncio
-import autogen
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
-import sys
import os
+import sys
+
+import pytest
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+
+import autogen
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
diff --git a/test/agentchat/test_async_chats.py b/test/agentchat/test_async_chats.py
index 883becc43..6b04658dc 100755
--- a/test/agentchat/test_async_chats.py
+++ b/test/agentchat/test_async_chats.py
@@ -1,12 +1,14 @@
#!/usr/bin/env python3 -m pytest
-import pytest
import asyncio
-import sys
import os
+import sys
+
+import pytest
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+
import autogen
from autogen import AssistantAgent, UserProxyAgent
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
diff --git a/test/agentchat/test_async_get_human_input.py b/test/agentchat/test_async_get_human_input.py
index 536762607..bcc2a1cc9 100755
--- a/test/agentchat/test_async_get_human_input.py
+++ b/test/agentchat/test_async_get_human_input.py
@@ -5,10 +5,11 @@ import os
import sys
from unittest.mock import AsyncMock
-import autogen
import pytest
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+import autogen
+
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
diff --git a/test/agentchat/test_chats.py b/test/agentchat/test_chats.py
index b16052017..d31199fa3 100755
--- a/test/agentchat/test_chats.py
+++ b/test/agentchat/test_chats.py
@@ -1,15 +1,15 @@
#!/usr/bin/env python3 -m pytest
-from autogen import AssistantAgent, UserProxyAgent
-from autogen import GroupChat, GroupChatManager
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
-import pytest
-import sys
import os
-import autogen
+import sys
from typing import Literal
+
+import pytest
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
from typing_extensions import Annotated
-from autogen import initiate_chats
+
+import autogen
+from autogen import AssistantAgent, GroupChat, GroupChatManager, UserProxyAgent, initiate_chats
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
diff --git a/test/agentchat/test_conversable_agent.py b/test/agentchat/test_conversable_agent.py
index 5ff2c0c10..f1818d9db 100755
--- a/test/agentchat/test_conversable_agent.py
+++ b/test/agentchat/test_conversable_agent.py
@@ -2,22 +2,23 @@
import asyncio
import copy
+import inspect
+import os
import sys
import time
-from typing import Any, Callable, Dict, Literal
import unittest
-import inspect
+from typing import Any, Callable, Dict, Literal
from unittest.mock import MagicMock
import pytest
from pydantic import BaseModel, Field
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
from typing_extensions import Annotated
+
import autogen
-import os
from autogen.agentchat import ConversableAgent, UserProxyAgent
from autogen.agentchat.conversable_agent import register_function
from autogen.exception_utils import InvalidCarryOverType, SenderRequired
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import MOCK_OPEN_AI_API_KEY, skip_openai # noqa: E402
diff --git a/test/agentchat/test_function_call.py b/test/agentchat/test_function_call.py
index d5ceccca7..793af6a30 100755
--- a/test/agentchat/test_function_call.py
+++ b/test/agentchat/test_function_call.py
@@ -1,13 +1,15 @@
#!/usr/bin/env python3 -m pytest
-import pytest
import asyncio
import json
+import os
+import sys
+
+import pytest
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+
import autogen
from autogen.math_utils import eval_math_responses
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
-import sys
-import os
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
@@ -140,9 +142,10 @@ def test_execute_function():
@pytest.mark.asyncio
async def test_a_execute_function():
- from autogen.agentchat import UserProxyAgent
import time
+ from autogen.agentchat import UserProxyAgent
+
# Create an async function
async def add_num(num_to_be_added):
given_num = 10
diff --git a/test/agentchat/test_function_call_groupchat.py b/test/agentchat/test_function_call_groupchat.py
index 0217f4cc6..6faea6a31 100755
--- a/test/agentchat/test_function_call_groupchat.py
+++ b/test/agentchat/test_function_call_groupchat.py
@@ -1,12 +1,14 @@
#!/usr/bin/env python3 -m pytest
-import autogen
-import pytest
import asyncio
-import sys
import os
+import sys
+
+import pytest
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+import autogen
+
try:
from openai import OpenAI
except ImportError:
diff --git a/test/agentchat/test_human_input.py b/test/agentchat/test_human_input.py
index 52686232b..b023ab47a 100755
--- a/test/agentchat/test_human_input.py
+++ b/test/agentchat/test_human_input.py
@@ -1,11 +1,13 @@
#!/usr/bin/env python3 -m pytest
-import autogen
-import pytest
+import os
+import sys
from unittest.mock import MagicMock
+
+import pytest
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
-import sys
-import os
+
+import autogen
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai as skip # noqa: E402
diff --git a/test/agentchat/test_math_user_proxy_agent.py b/test/agentchat/test_math_user_proxy_agent.py
index be93b9cad..1e85a7481 100755
--- a/test/agentchat/test_math_user_proxy_agent.py
+++ b/test/agentchat/test_math_user_proxy_agent.py
@@ -1,15 +1,17 @@
#!/usr/bin/env python3 -m pytest
-import pytest
-import sys
import os
+import sys
+
+import pytest
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+
import autogen
from autogen.agentchat.contrib.math_user_proxy_agent import (
MathUserProxyAgent,
- _remove_print,
_add_print_to_last_line,
+ _remove_print,
)
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
diff --git a/test/agentchat/test_nested.py b/test/agentchat/test_nested.py
index c7856772b..56ca28f62 100755
--- a/test/agentchat/test_nested.py
+++ b/test/agentchat/test_nested.py
@@ -1,8 +1,10 @@
#!/usr/bin/env python3 -m pytest
-import pytest
-import sys
import os
+import sys
+
+import pytest
+
import autogen
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
diff --git a/test/agentchat/test_tool_calls.py b/test/agentchat/test_tool_calls.py
index e6395463b..710ab14f5 100755
--- a/test/agentchat/test_tool_calls.py
+++ b/test/agentchat/test_tool_calls.py
@@ -1,13 +1,15 @@
#!/usr/bin/env python3 -m pytest
import inspect
-import pytest
import json
-import sys
import os
+import sys
+
+import pytest
+from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
+
import autogen
from autogen.math_utils import eval_math_responses
-from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST
from autogen.oai.client import TOOL_ENABLED
try:
diff --git a/test/cache/test_cache.py b/test/cache/test_cache.py
index 04c12e4ff..45043ccc9 100755
--- a/test/cache/test_cache.py
+++ b/test/cache/test_cache.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python3 -m pytest
import unittest
-from unittest.mock import patch, MagicMock
+from unittest.mock import MagicMock, patch
+
from autogen.cache.cache import Cache
diff --git a/test/cache/test_disk_cache.py b/test/cache/test_disk_cache.py
index 43879eb24..e7fa4df48 100755
--- a/test/cache/test_disk_cache.py
+++ b/test/cache/test_disk_cache.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python3 -m pytest
import unittest
-from unittest.mock import patch, MagicMock
+from unittest.mock import MagicMock, patch
+
from autogen.cache.disk_cache import DiskCache
diff --git a/test/cache/test_redis_cache.py b/test/cache/test_redis_cache.py
index 95f220729..c915ef5ac 100755
--- a/test/cache/test_redis_cache.py
+++ b/test/cache/test_redis_cache.py
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 -m pytest
-import unittest
import pickle
-from unittest.mock import patch, MagicMock
+import unittest
+from unittest.mock import MagicMock, patch
import pytest
diff --git a/test/coding/test_commandline_code_executor.py b/test/coding/test_commandline_code_executor.py
index 49d4d35cf..5c20e856d 100644
--- a/test/coding/test_commandline_code_executor.py
+++ b/test/coding/test_commandline_code_executor.py
@@ -1,14 +1,16 @@
-from pathlib import Path
-import sys
import os
+import sys
import tempfile
import uuid
+from pathlib import Path
+
import pytest
+
from autogen.agentchat.conversable_agent import ConversableAgent
from autogen.code_utils import is_docker_running
from autogen.coding.base import CodeBlock, CodeExecutor
-from autogen.coding.factory import CodeExecutorFactory
from autogen.coding.docker_commandline_code_executor import DockerCommandLineCodeExecutor
+from autogen.coding.factory import CodeExecutorFactory
from autogen.coding.local_commandline_code_executor import LocalCommandLineCodeExecutor
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
diff --git a/test/coding/test_embedded_ipython_code_executor.py b/test/coding/test_embedded_ipython_code_executor.py
index bc3c0eb31..376760af8 100644
--- a/test/coding/test_embedded_ipython_code_executor.py
+++ b/test/coding/test_embedded_ipython_code_executor.py
@@ -1,15 +1,17 @@
import os
import sys
-from pathlib import Path
import tempfile
-from typing import Dict, Type, Union
import uuid
+from pathlib import Path
+from typing import Dict, Type, Union
+
import pytest
+from conftest import MOCK_OPEN_AI_API_KEY, skip_docker, skip_openai # noqa: E402
+
from autogen.agentchat.conversable_agent import ConversableAgent
from autogen.coding.base import CodeBlock, CodeExecutor
from autogen.coding.factory import CodeExecutorFactory
from autogen.oai.openai_utils import config_list_from_json
-from conftest import MOCK_OPEN_AI_API_KEY, skip_openai, skip_docker # noqa: E402
try:
from autogen.coding.jupyter import (
diff --git a/test/coding/test_factory.py b/test/coding/test_factory.py
index a4f40ec91..4316721e3 100644
--- a/test/coding/test_factory.py
+++ b/test/coding/test_factory.py
@@ -1,4 +1,5 @@
import pytest
+
from autogen.coding.factory import CodeExecutorFactory
diff --git a/test/coding/test_user_defined_functions.py b/test/coding/test_user_defined_functions.py
index 53b3c5045..6cd3e115f 100644
--- a/test/coding/test_user_defined_functions.py
+++ b/test/coding/test_user_defined_functions.py
@@ -1,5 +1,7 @@
import tempfile
+
import pytest
+
from autogen.coding.base import CodeBlock
from autogen.coding.local_commandline_code_executor import LocalCommandLineCodeExecutor
diff --git a/test/io/test_websockets.py b/test/io/test_websockets.py
index 2c7fbbc5f..1458afcd8 100644
--- a/test/io/test_websockets.py
+++ b/test/io/test_websockets.py
@@ -2,12 +2,12 @@ from tempfile import TemporaryDirectory
from typing import Dict
import pytest
-from autogen.io.base import IOStream
from conftest import skip_openai
import autogen
from autogen.cache.cache import Cache
from autogen.io import IOWebsockets
+from autogen.io.base import IOStream
KEY_LOC = "notebook"
OAI_CONFIG_LIST = "OAI_CONFIG_LIST"
diff --git a/test/oai/_test_completion.py b/test/oai/_test_completion.py
index 6a26629a8..05798911c 100755
--- a/test/oai/_test_completion.py
+++ b/test/oai/_test_completion.py
@@ -1,21 +1,23 @@
#!/usr/bin/env python3 -m pytest
-import datasets
+import json
+import os
import sys
+from functools import partial
+from test.oai.test_utils import KEY_LOC, OAI_CONFIG_LIST
+
+import datasets
import numpy as np
import pytest
-from functools import partial
-import os
-import json
+
import autogen
from autogen.code_utils import (
eval_function_completions,
generate_assertions,
- implement,
generate_code,
+ implement,
)
from autogen.math_utils import eval_math_responses, solve_problem
-from test.oai.test_utils import KEY_LOC, OAI_CONFIG_LIST
here = os.path.abspath(os.path.dirname(__file__))
@@ -121,8 +123,8 @@ def test_multi_model():
def test_nocontext():
try:
- import openai
import diskcache
+ import openai
except ImportError as exc:
print(exc)
return
@@ -216,8 +218,8 @@ def test_humaneval(num_samples=1):
autogen.Completion.clear_cache(cache_path_root="{here}/cache")
autogen.Completion.set_cache(seed)
try:
- import openai
import diskcache
+ import openai
except ImportError as exc:
print(exc)
return
@@ -338,8 +340,8 @@ def test_humaneval(num_samples=1):
def test_math(num_samples=-1):
try:
- import openai
import diskcache
+ import openai
except ImportError as exc:
print(exc)
return
diff --git a/test/oai/test_client.py b/test/oai/test_client.py
index 10117506c..ba2ac0fbe 100755
--- a/test/oai/test_client.py
+++ b/test/oai/test_client.py
@@ -1,21 +1,23 @@
#!/usr/bin/env python3 -m pytest
+import os
import shutil
+import sys
import time
+
import pytest
+
from autogen import OpenAIWrapper, config_list_from_json, config_list_openai_aoai
-from autogen.oai.client import LEGACY_CACHE_DIR, LEGACY_DEFAULT_CACHE_SEED
-import sys
-import os
from autogen.cache.cache import Cache
+from autogen.oai.client import LEGACY_CACHE_DIR, LEGACY_DEFAULT_CACHE_SEED
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
TOOL_ENABLED = False
try:
- from openai import OpenAI
import openai
+ from openai import OpenAI
if openai.__version__ >= "1.1.0":
TOOL_ENABLED = True
diff --git a/test/oai/test_client_stream.py b/test/oai/test_client_stream.py
index 92e249dfd..9e85bff70 100755
--- a/test/oai/test_client_stream.py
+++ b/test/oai/test_client_stream.py
@@ -1,12 +1,14 @@
#!/usr/bin/env python3 -m pytest
import json
+import os
+import sys
from typing import Any, Dict, List, Literal, Optional, Union
from unittest.mock import MagicMock
+
import pytest
+
from autogen import OpenAIWrapper, config_list_from_json, config_list_openai_aoai
-import sys
-import os
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from conftest import skip_openai # noqa: E402
@@ -20,12 +22,12 @@ else:
# raises exception if openai>=1 is installed and something is wrong with imports
# otherwise the test will be skipped
+ from openai.types.chat.chat_completion import ChatCompletionMessage # type: ignore [attr-defined]
from openai.types.chat.chat_completion_chunk import (
ChoiceDeltaFunctionCall,
ChoiceDeltaToolCall,
ChoiceDeltaToolCallFunction,
)
- from openai.types.chat.chat_completion import ChatCompletionMessage # type: ignore [attr-defined]
KEY_LOC = "notebook"
OAI_CONFIG_LIST = "OAI_CONFIG_LIST"
diff --git a/test/oai/test_custom_client.py b/test/oai/test_custom_client.py
index 04669a3e0..009093390 100644
--- a/test/oai/test_custom_client.py
+++ b/test/oai/test_custom_client.py
@@ -1,7 +1,9 @@
+from typing import Dict
+
import pytest
+
from autogen import OpenAIWrapper
from autogen.oai import ModelClient
-from typing import Dict
try:
from openai import OpenAI
diff --git a/test/oai/test_utils.py b/test/oai/test_utils.py
index b69958739..65ec7a014 100755
--- a/test/oai/test_utils.py
+++ b/test/oai/test_utils.py
@@ -8,12 +8,11 @@ from unittest import mock
from unittest.mock import patch
import pytest
+from conftest import MOCK_OPEN_AI_API_KEY
import autogen # noqa: E402
from autogen.oai.openai_utils import DEFAULT_AZURE_API_VERSION, filter_config, is_valid_api_key
-from conftest import MOCK_OPEN_AI_API_KEY
-
# Example environment variables
ENV_VARS = {
"OPENAI_API_KEY": "sk-********************",
diff --git a/test/test_browser_utils.py b/test/test_browser_utils.py
index ffcaca40c..5551130a6 100755
--- a/test/test_browser_utils.py
+++ b/test/test_browser_utils.py
@@ -1,13 +1,13 @@
#!/usr/bin/env python3 -m pytest
-import pytest
-import os
-import sys
-import requests
import hashlib
-import re
import math
+import os
+import re
+import sys
+import pytest
+import requests
from agentchat.test_assistant_agent import KEY_LOC # noqa: E402
BLOG_POST_URL = "https://microsoft.github.io/autogen/blog/2023/04/21/LLM-tuning-math"
diff --git a/test/test_code_utils.py b/test/test_code_utils.py
index 1d45a9b4e..a4c6cf697 100755
--- a/test/test_code_utils.py
+++ b/test/test_code_utils.py
@@ -1,29 +1,30 @@
#!/usr/bin/env python3 -m pytest
import os
+import sys
import tempfile
import unittest
+from io import StringIO
from unittest.mock import patch
-import sys
+
import pytest
-from io import StringIO
+from conftest import skip_docker
import autogen
from autogen.code_utils import (
UNKNOWN,
+ check_can_use_docker_or_throw,
content_str,
+ decide_use_docker,
execute_code,
extract_code,
- improve_code,
get_powershell_command,
+ improve_code,
improve_function,
+ in_docker_container,
infer_lang,
is_docker_running,
- in_docker_container,
- decide_use_docker,
- check_can_use_docker_or_throw,
)
-from conftest import skip_docker
KEY_LOC = "notebook"
OAI_CONFIG_LIST = "OAI_CONFIG_LIST"
diff --git a/test/test_graph_utils.py b/test/test_graph_utils.py
index 5bdcab3c6..a8b290212 100644
--- a/test/test_graph_utils.py
+++ b/test/test_graph_utils.py
@@ -1,8 +1,10 @@
+import logging
from typing import Any
+
import pytest
-import logging
-from autogen.agentchat import Agent
+
import autogen.graph_utils as gru
+from autogen.agentchat import Agent
class FakeAgent(Agent):
diff --git a/test/test_logging.py b/test/test_logging.py
index 7f331a85a..d824cc914 100644
--- a/test/test_logging.py
+++ b/test/test_logging.py
@@ -1,13 +1,13 @@
-import autogen.runtime_logging
-import uuid
import json
-import pytest
import sqlite3
+import uuid
+from unittest.mock import Mock, patch
-from autogen.logger.logger_utils import get_current_ts, to_dict
+import pytest
from openai import AzureOpenAI
-from unittest.mock import patch, Mock
+import autogen.runtime_logging
+from autogen.logger.logger_utils import get_current_ts, to_dict
SAMPLE_CHAT_REQUEST = json.loads(
"""
diff --git a/test/test_notebook.py b/test/test_notebook.py
index cc17c3540..46622c287 100755
--- a/test/test_notebook.py
+++ b/test/test_notebook.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python3 -m pytest
-import sys
import os
+import sys
+
import pytest
from conftest import skip_openai
@@ -18,8 +19,7 @@ here = os.path.abspath(os.path.dirname(__file__))
def run_notebook(input_nb, output_nb="executed_openai_notebook.ipynb", save=False):
import nbformat
- from nbconvert.preprocessors import ExecutePreprocessor
- from nbconvert.preprocessors import CellExecutionError
+ from nbconvert.preprocessors import CellExecutionError, ExecutePreprocessor
try:
nb_loc = os.path.join(here, os.pardir, "notebook")
diff --git a/test/test_retrieve_utils.py b/test/test_retrieve_utils.py
index c2ade2352..f978b06e5 100755
--- a/test/test_retrieve_utils.py
+++ b/test/test_retrieve_utils.py
@@ -7,14 +7,15 @@ import pytest
try:
import chromadb
+
from autogen.retrieve_utils import (
- split_text_to_chunks,
+ create_vector_db_from_dir,
extract_text_from_pdf,
- split_files_to_chunks,
get_files_from_dir,
is_url,
- create_vector_db_from_dir,
query_vector_db,
+ split_files_to_chunks,
+ split_text_to_chunks,
)
from autogen.token_count_utils import count_token
except ImportError:
diff --git a/test/test_token_count.py b/test/test_token_count.py
index aa9175ca8..e9a731465 100755
--- a/test/test_token_count.py
+++ b/test/test_token_count.py
@@ -1,13 +1,14 @@
#!/usr/bin/env python3 -m pytest
+import pytest
+
from autogen.token_count_utils import (
count_token,
+ get_max_token_limit,
num_tokens_from_functions,
- token_left,
percentile_used,
- get_max_token_limit,
+ token_left,
)
-import pytest
func1 = {
"name": "sh",
diff --git a/website/docs/topics/code-execution/cli-code-executor.ipynb b/website/docs/topics/code-execution/cli-code-executor.ipynb
index 26ce165b6..d8b45bfe6 100644
--- a/website/docs/topics/code-execution/cli-code-executor.ipynb
+++ b/website/docs/topics/code-execution/cli-code-executor.ipynb
@@ -41,8 +41,8 @@
],
"source": [
"from pathlib import Path\n",
- "from autogen.coding import CodeBlock\n",
- "from autogen.coding import DockerCommandLineCodeExecutor\n",
+ "\n",
+ "from autogen.coding import CodeBlock, DockerCommandLineCodeExecutor\n",
"\n",
"work_dir = Path(\"coding\")\n",
"work_dir.mkdir(exist_ok=True)\n",
@@ -108,8 +108,8 @@
],
"source": [
"from pathlib import Path\n",
- "from autogen.coding import CodeBlock\n",
- "from autogen.coding import LocalCommandLineCodeExecutor\n",
+ "\n",
+ "from autogen.coding import CodeBlock, LocalCommandLineCodeExecutor\n",
"\n",
"work_dir = Path(\"coding\")\n",
"work_dir.mkdir(exist_ok=True)\n",
@@ -139,9 +139,10 @@
"metadata": {},
"outputs": [],
"source": [
+ "from pathlib import Path\n",
+ "\n",
"from autogen import ConversableAgent\n",
"from autogen.coding import DockerCommandLineCodeExecutor\n",
- "from pathlib import Path\n",
"\n",
"work_dir = Path(\"coding\")\n",
"work_dir.mkdir(exist_ok=True)\n",
diff --git a/website/docs/topics/code-execution/jupyter-code-executor.ipynb b/website/docs/topics/code-execution/jupyter-code-executor.ipynb
index 3e338fabb..09f35f1fd 100644
--- a/website/docs/topics/code-execution/jupyter-code-executor.ipynb
+++ b/website/docs/topics/code-execution/jupyter-code-executor.ipynb
@@ -166,7 +166,7 @@
"outputs": [],
"source": [
"from autogen.coding import CodeBlock\n",
- "from autogen.coding.jupyter import LocalJupyterServer, JupyterCodeExecutor\n",
+ "from autogen.coding.jupyter import JupyterCodeExecutor, LocalJupyterServer\n",
"\n",
"with LocalJupyterServer() as server:\n",
" executor = JupyterCodeExecutor(server)\n",
@@ -215,9 +215,10 @@
"metadata": {},
"outputs": [],
"source": [
+ "from pathlib import Path\n",
+ "\n",
"from autogen import ConversableAgent\n",
"from autogen.coding.jupyter import DockerJupyterServer, JupyterCodeExecutor\n",
- "from pathlib import Path\n",
"\n",
"server = DockerJupyterServer()\n",
"\n",
diff --git a/website/docs/topics/code-execution/user-defined-functions.ipynb b/website/docs/topics/code-execution/user-defined-functions.ipynb
index ce48031a6..ade02dfc0 100644
--- a/website/docs/topics/code-execution/user-defined-functions.ipynb
+++ b/website/docs/topics/code-execution/user-defined-functions.ipynb
@@ -68,6 +68,7 @@
"outputs": [],
"source": [
"import pandas\n",
+ "\n",
"from autogen.coding.func_with_reqs import with_requirements\n",
"\n",
"\n",
@@ -134,8 +135,8 @@
"outputs": [],
"source": [
"from pathlib import Path\n",
- "from autogen.coding import CodeBlock\n",
- "from autogen.coding import LocalCommandLineCodeExecutor\n",
+ "\n",
+ "from autogen.coding import CodeBlock, LocalCommandLineCodeExecutor\n",
"\n",
"work_dir = Path(\"coding\")\n",
"work_dir.mkdir(exist_ok=True)\n",
@@ -305,10 +306,10 @@
"metadata": {},
"outputs": [],
"source": [
- "from autogen import ConversableAgent\n",
- "\n",
"import os\n",
"\n",
+ "from autogen import ConversableAgent\n",
+ "\n",
"code_writer_agent = ConversableAgent(\n",
" \"code_writer\",\n",
" system_message=code_writer_system_message,\n",
diff --git a/website/docs/topics/non-openai-models/cloud-mistralai.ipynb b/website/docs/topics/non-openai-models/cloud-mistralai.ipynb
index 883cd46db..a95e0bc51 100644
--- a/website/docs/topics/non-openai-models/cloud-mistralai.ipynb
+++ b/website/docs/topics/non-openai-models/cloud-mistralai.ipynb
@@ -69,6 +69,7 @@
"outputs": [],
"source": [
"from pathlib import Path\n",
+ "\n",
"from autogen import AssistantAgent, UserProxyAgent\n",
"from autogen.coding import LocalCommandLineCodeExecutor\n",
"\n",
@@ -209,10 +210,11 @@
"metadata": {},
"outputs": [],
"source": [
+ "import random\n",
+ "\n",
"import chess\n",
"import chess.svg\n",
"from IPython.display import display\n",
- "import random\n",
"from typing_extensions import Annotated\n",
"\n",
"board = chess.Board()\n",
diff --git a/website/docs/topics/prompting-and-reasoning/react.ipynb b/website/docs/topics/prompting-and-reasoning/react.ipynb
index e0ebaf5d1..1edfc6b14 100644
--- a/website/docs/topics/prompting-and-reasoning/react.ipynb
+++ b/website/docs/topics/prompting-and-reasoning/react.ipynb
@@ -28,8 +28,9 @@
"metadata": {},
"outputs": [],
"source": [
- "from langchain_community.tools.tavily_search import TavilySearchResults\n",
"from langchain.utilities.tavily_search import TavilySearchAPIWrapper\n",
+ "from langchain_community.tools.tavily_search import TavilySearchResults\n",
+ "\n",
"import autogen\n",
"\n",
"config_list = autogen.config_list_from_json(\n",
diff --git a/website/docs/topics/task_decomposition.ipynb b/website/docs/topics/task_decomposition.ipynb
index d6278c9c7..333b45996 100644
--- a/website/docs/topics/task_decomposition.ipynb
+++ b/website/docs/topics/task_decomposition.ipynb
@@ -825,9 +825,9 @@
" }, # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.\n",
")\n",
"\n",
- "from autogen import Agent\n",
- "from typing import List, Dict\n",
+ "from typing import Dict, List\n",
"\n",
+ "from autogen import Agent\n",
"\n",
"groupchat = autogen.GroupChat(\n",
" agents=[user_proxy, engineer, executor, writer, planner],\n",
@@ -1617,6 +1617,7 @@
"outputs": [],
"source": [
"from typing import Callable, Literal, Optional, Union\n",
+ "\n",
"from autogen.agentchat.conversable_agent import ConversableAgent\n",
"\n",
"\n",
diff --git a/website/docs/tutorial/chat-termination.ipynb b/website/docs/tutorial/chat-termination.ipynb
index ff3f2db2f..8a12a6748 100644
--- a/website/docs/tutorial/chat-termination.ipynb
+++ b/website/docs/tutorial/chat-termination.ipynb
@@ -34,6 +34,7 @@
"outputs": [],
"source": [
"import os\n",
+ "\n",
"from autogen import ConversableAgent"
]
},
diff --git a/website/docs/tutorial/code-executors.ipynb b/website/docs/tutorial/code-executors.ipynb
index 53ee0a9cd..dcd7ace42 100644
--- a/website/docs/tutorial/code-executors.ipynb
+++ b/website/docs/tutorial/code-executors.ipynb
@@ -83,6 +83,7 @@
"outputs": [],
"source": [
"import tempfile\n",
+ "\n",
"from autogen import ConversableAgent\n",
"from autogen.coding import LocalCommandLineCodeExecutor\n",
"\n",
@@ -773,6 +774,7 @@
],
"source": [
"import pprint\n",
+ "\n",
"from autogen import AssistantAgent\n",
"\n",
"pprint.pprint(AssistantAgent.DEFAULT_SYSTEM_MESSAGE)"
diff --git a/website/docs/tutorial/conversation-patterns.ipynb b/website/docs/tutorial/conversation-patterns.ipynb
index d032175e0..da02fd24a 100644
--- a/website/docs/tutorial/conversation-patterns.ipynb
+++ b/website/docs/tutorial/conversation-patterns.ipynb
@@ -110,6 +110,7 @@
],
"source": [
"import os\n",
+ "\n",
"from autogen import ConversableAgent\n",
"\n",
"student_agent = ConversableAgent(\n",
@@ -1183,29 +1184,29 @@
]
},
{
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Changing the select speaker role name\n",
- "\n",
- "As part of the Group chat process, when the select_speaker_method is set to 'auto' (the default value),\n",
- "a select speaker message is sent to the LLM to determine the next speaker.\n",
- "\n",
- "Each message in the chat sequence has a `role` attribute that is typically `user`,\n",
- "`assistant`, or `system`. The select speaker message is the last in the chat\n",
- "sequence when used and, by default, has a role of `system`.\n",
- "\n",
- "When using some models, such as Mistral through Mistral.AI's API, the role on\n",
- "the last message in the chat sequence has to be `user`.\n",
- "\n",
- "To change the default behaviour, Autogen provides a way to set the value of the\n",
- "select speaker message's role to any string value by setting the\n",
- "`role_for_select_speaker_messages` parameter in the GroupChat's constructor. The\n",
- "default value is `system` and by setting it to `user` you can accommodate the\n",
- "last message role requirement of Mistral.AI's API."
- ]
- },
- {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Changing the select speaker role name\n",
+ "\n",
+ "As part of the Group chat process, when the select_speaker_method is set to 'auto' (the default value),\n",
+ "a select speaker message is sent to the LLM to determine the next speaker.\n",
+ "\n",
+ "Each message in the chat sequence has a `role` attribute that is typically `user`,\n",
+ "`assistant`, or `system`. The select speaker message is the last in the chat\n",
+ "sequence when used and, by default, has a role of `system`.\n",
+ "\n",
+ "When using some models, such as Mistral through Mistral.AI's API, the role on\n",
+ "the last message in the chat sequence has to be `user`.\n",
+ "\n",
+ "To change the default behaviour, Autogen provides a way to set the value of the\n",
+ "select speaker message's role to any string value by setting the\n",
+ "`role_for_select_speaker_messages` parameter in the GroupChat's constructor. The\n",
+ "default value is `system` and by setting it to `user` you can accommodate the\n",
+ "last message role requirement of Mistral.AI's API."
+ ]
+ },
+ {
"cell_type": "markdown",
"metadata": {},
"source": [
diff --git a/website/docs/tutorial/human-in-the-loop.ipynb b/website/docs/tutorial/human-in-the-loop.ipynb
index cde9a57ad..52bb7e1f7 100644
--- a/website/docs/tutorial/human-in-the-loop.ipynb
+++ b/website/docs/tutorial/human-in-the-loop.ipynb
@@ -149,6 +149,7 @@
],
"source": [
"import os\n",
+ "\n",
"from autogen import ConversableAgent\n",
"\n",
"agent_with_number = ConversableAgent(\n",
diff --git a/website/docs/tutorial/introduction.ipynb b/website/docs/tutorial/introduction.ipynb
index c244a0b04..88df66b72 100644
--- a/website/docs/tutorial/introduction.ipynb
+++ b/website/docs/tutorial/introduction.ipynb
@@ -84,6 +84,7 @@
"outputs": [],
"source": [
"import os\n",
+ "\n",
"from autogen import ConversableAgent\n",
"\n",
"agent = ConversableAgent(\n",
diff --git a/website/docs/tutorial/tool-use.ipynb b/website/docs/tutorial/tool-use.ipynb
index 0e78fe742..12d0f5a80 100644
--- a/website/docs/tutorial/tool-use.ipynb
+++ b/website/docs/tutorial/tool-use.ipynb
@@ -95,6 +95,7 @@
"outputs": [],
"source": [
"import os\n",
+ "\n",
"from autogen import ConversableAgent\n",
"\n",
"# Let's first define the assistant agent that suggests tool calls.\n",
diff --git a/website/process_notebooks.py b/website/process_notebooks.py
index 04b5da699..5e25f5e69 100755
--- a/website/process_notebooks.py
+++ b/website/process_notebooks.py
@@ -1,22 +1,24 @@
#!/usr/bin/env python
from __future__ import annotations
-import signal
-import sys
-from pathlib import Path
-import subprocess
+
import argparse
-import shutil
+import concurrent.futures
import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
import tempfile
import threading
import time
import typing
-import concurrent.futures
-import os
-from typing import Dict, Optional, Tuple, Union
from dataclasses import dataclass
from multiprocessing import current_process
+from pathlib import Path
+from typing import Dict, Optional, Tuple, Union
+
from termcolor import colored
try: