ag2 0.3.2b2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ag2 might be problematic. Click here for more details.

Files changed (112) hide show
  1. ag2-0.3.2b2.dist-info/LICENSE +201 -0
  2. ag2-0.3.2b2.dist-info/METADATA +490 -0
  3. ag2-0.3.2b2.dist-info/NOTICE.md +19 -0
  4. ag2-0.3.2b2.dist-info/RECORD +112 -0
  5. ag2-0.3.2b2.dist-info/WHEEL +5 -0
  6. ag2-0.3.2b2.dist-info/top_level.txt +1 -0
  7. autogen/__init__.py +17 -0
  8. autogen/_pydantic.py +116 -0
  9. autogen/agentchat/__init__.py +26 -0
  10. autogen/agentchat/agent.py +142 -0
  11. autogen/agentchat/assistant_agent.py +85 -0
  12. autogen/agentchat/chat.py +306 -0
  13. autogen/agentchat/contrib/__init__.py +0 -0
  14. autogen/agentchat/contrib/agent_builder.py +785 -0
  15. autogen/agentchat/contrib/agent_optimizer.py +450 -0
  16. autogen/agentchat/contrib/capabilities/__init__.py +0 -0
  17. autogen/agentchat/contrib/capabilities/agent_capability.py +21 -0
  18. autogen/agentchat/contrib/capabilities/generate_images.py +297 -0
  19. autogen/agentchat/contrib/capabilities/teachability.py +406 -0
  20. autogen/agentchat/contrib/capabilities/text_compressors.py +72 -0
  21. autogen/agentchat/contrib/capabilities/transform_messages.py +92 -0
  22. autogen/agentchat/contrib/capabilities/transforms.py +565 -0
  23. autogen/agentchat/contrib/capabilities/transforms_util.py +120 -0
  24. autogen/agentchat/contrib/capabilities/vision_capability.py +217 -0
  25. autogen/agentchat/contrib/gpt_assistant_agent.py +545 -0
  26. autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
  27. autogen/agentchat/contrib/graph_rag/document.py +24 -0
  28. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +76 -0
  29. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +50 -0
  30. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +56 -0
  31. autogen/agentchat/contrib/img_utils.py +390 -0
  32. autogen/agentchat/contrib/llamaindex_conversable_agent.py +114 -0
  33. autogen/agentchat/contrib/llava_agent.py +176 -0
  34. autogen/agentchat/contrib/math_user_proxy_agent.py +471 -0
  35. autogen/agentchat/contrib/multimodal_conversable_agent.py +128 -0
  36. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +325 -0
  37. autogen/agentchat/contrib/retrieve_assistant_agent.py +56 -0
  38. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +701 -0
  39. autogen/agentchat/contrib/society_of_mind_agent.py +203 -0
  40. autogen/agentchat/contrib/text_analyzer_agent.py +76 -0
  41. autogen/agentchat/contrib/vectordb/__init__.py +0 -0
  42. autogen/agentchat/contrib/vectordb/base.py +243 -0
  43. autogen/agentchat/contrib/vectordb/chromadb.py +326 -0
  44. autogen/agentchat/contrib/vectordb/mongodb.py +559 -0
  45. autogen/agentchat/contrib/vectordb/pgvectordb.py +958 -0
  46. autogen/agentchat/contrib/vectordb/qdrant.py +334 -0
  47. autogen/agentchat/contrib/vectordb/utils.py +126 -0
  48. autogen/agentchat/contrib/web_surfer.py +305 -0
  49. autogen/agentchat/conversable_agent.py +2904 -0
  50. autogen/agentchat/groupchat.py +1666 -0
  51. autogen/agentchat/user_proxy_agent.py +109 -0
  52. autogen/agentchat/utils.py +207 -0
  53. autogen/browser_utils.py +291 -0
  54. autogen/cache/__init__.py +10 -0
  55. autogen/cache/abstract_cache_base.py +78 -0
  56. autogen/cache/cache.py +182 -0
  57. autogen/cache/cache_factory.py +85 -0
  58. autogen/cache/cosmos_db_cache.py +150 -0
  59. autogen/cache/disk_cache.py +109 -0
  60. autogen/cache/in_memory_cache.py +61 -0
  61. autogen/cache/redis_cache.py +128 -0
  62. autogen/code_utils.py +745 -0
  63. autogen/coding/__init__.py +22 -0
  64. autogen/coding/base.py +113 -0
  65. autogen/coding/docker_commandline_code_executor.py +262 -0
  66. autogen/coding/factory.py +45 -0
  67. autogen/coding/func_with_reqs.py +203 -0
  68. autogen/coding/jupyter/__init__.py +22 -0
  69. autogen/coding/jupyter/base.py +32 -0
  70. autogen/coding/jupyter/docker_jupyter_server.py +164 -0
  71. autogen/coding/jupyter/embedded_ipython_code_executor.py +182 -0
  72. autogen/coding/jupyter/jupyter_client.py +224 -0
  73. autogen/coding/jupyter/jupyter_code_executor.py +161 -0
  74. autogen/coding/jupyter/local_jupyter_server.py +168 -0
  75. autogen/coding/local_commandline_code_executor.py +410 -0
  76. autogen/coding/markdown_code_extractor.py +44 -0
  77. autogen/coding/utils.py +57 -0
  78. autogen/exception_utils.py +46 -0
  79. autogen/extensions/__init__.py +0 -0
  80. autogen/formatting_utils.py +76 -0
  81. autogen/function_utils.py +362 -0
  82. autogen/graph_utils.py +148 -0
  83. autogen/io/__init__.py +15 -0
  84. autogen/io/base.py +105 -0
  85. autogen/io/console.py +43 -0
  86. autogen/io/websockets.py +213 -0
  87. autogen/logger/__init__.py +11 -0
  88. autogen/logger/base_logger.py +140 -0
  89. autogen/logger/file_logger.py +287 -0
  90. autogen/logger/logger_factory.py +29 -0
  91. autogen/logger/logger_utils.py +42 -0
  92. autogen/logger/sqlite_logger.py +459 -0
  93. autogen/math_utils.py +356 -0
  94. autogen/oai/__init__.py +33 -0
  95. autogen/oai/anthropic.py +428 -0
  96. autogen/oai/bedrock.py +600 -0
  97. autogen/oai/cerebras.py +264 -0
  98. autogen/oai/client.py +1148 -0
  99. autogen/oai/client_utils.py +167 -0
  100. autogen/oai/cohere.py +453 -0
  101. autogen/oai/completion.py +1216 -0
  102. autogen/oai/gemini.py +469 -0
  103. autogen/oai/groq.py +281 -0
  104. autogen/oai/mistral.py +279 -0
  105. autogen/oai/ollama.py +576 -0
  106. autogen/oai/openai_utils.py +810 -0
  107. autogen/oai/together.py +343 -0
  108. autogen/retrieve_utils.py +487 -0
  109. autogen/runtime_logging.py +163 -0
  110. autogen/token_count_utils.py +257 -0
  111. autogen/types.py +20 -0
  112. autogen/version.py +7 -0
@@ -0,0 +1,161 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/autogen-ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Original portions of this file are derived from https://github.com/microsoft/autogen under the MIT License.
6
+ # SPDX-License-Identifier: MIT
7
+ import base64
8
+ import json
9
+ import os
10
+ import re
11
+ import sys
12
+ import uuid
13
+ from pathlib import Path
14
+ from types import TracebackType
15
+ from typing import Any, ClassVar, List, Optional, Type, Union
16
+
17
+ from autogen.coding.utils import silence_pip
18
+
19
+ if sys.version_info >= (3, 11):
20
+ from typing import Self
21
+ else:
22
+ from typing_extensions import Self
23
+
24
+
25
+ from ...agentchat.agent import LLMAgent
26
+ from ..base import CodeBlock, CodeExecutor, CodeExtractor, IPythonCodeResult
27
+ from ..markdown_code_extractor import MarkdownCodeExtractor
28
+ from .base import JupyterConnectable, JupyterConnectionInfo
29
+ from .jupyter_client import JupyterClient
30
+
31
+
32
+ class JupyterCodeExecutor(CodeExecutor):
33
+ def __init__(
34
+ self,
35
+ jupyter_server: Union[JupyterConnectable, JupyterConnectionInfo],
36
+ kernel_name: str = "python3",
37
+ timeout: int = 60,
38
+ output_dir: Union[Path, str] = Path("."),
39
+ ):
40
+ """(Experimental) A code executor class that executes code statefully using
41
+ a Jupyter server supplied to this class.
42
+
43
+ Each execution is stateful and can access variables created from previous
44
+ executions in the same session.
45
+
46
+ Args:
47
+ jupyter_server (Union[JupyterConnectable, JupyterConnectionInfo]): The Jupyter server to use.
48
+ timeout (int): The timeout for code execution, by default 60.
49
+ kernel_name (str): The kernel name to use. Make sure it is installed.
50
+ By default, it is "python3".
51
+ output_dir (str): The directory to save output files, by default ".".
52
+ """
53
+ if timeout < 1:
54
+ raise ValueError("Timeout must be greater than or equal to 1.")
55
+
56
+ if isinstance(output_dir, str):
57
+ output_dir = Path(output_dir)
58
+
59
+ if not output_dir.exists():
60
+ raise ValueError(f"Output directory {output_dir} does not exist.")
61
+
62
+ if isinstance(jupyter_server, JupyterConnectable):
63
+ self._connection_info = jupyter_server.connection_info
64
+ elif isinstance(jupyter_server, JupyterConnectionInfo):
65
+ self._connection_info = jupyter_server
66
+ else:
67
+ raise ValueError("jupyter_server must be a JupyterConnectable or JupyterConnectionInfo.")
68
+
69
+ self._jupyter_client = JupyterClient(self._connection_info)
70
+ available_kernels = self._jupyter_client.list_kernel_specs()
71
+ if kernel_name not in available_kernels["kernelspecs"]:
72
+ raise ValueError(f"Kernel {kernel_name} is not installed.")
73
+
74
+ self._kernel_id = self._jupyter_client.start_kernel(kernel_name)
75
+ self._kernel_name = kernel_name
76
+ self._jupyter_kernel_client = self._jupyter_client.get_kernel_client(self._kernel_id)
77
+ self._timeout = timeout
78
+ self._output_dir = output_dir
79
+
80
+ @property
81
+ def code_extractor(self) -> CodeExtractor:
82
+ """(Experimental) Export a code extractor that can be used by an agent."""
83
+ return MarkdownCodeExtractor()
84
+
85
+ def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> IPythonCodeResult:
86
+ """(Experimental) Execute a list of code blocks and return the result.
87
+
88
+ This method executes a list of code blocks as cells in the Jupyter kernel.
89
+ See: https://jupyter-client.readthedocs.io/en/stable/messaging.html
90
+ for the message protocol.
91
+
92
+ Args:
93
+ code_blocks (List[CodeBlock]): A list of code blocks to execute.
94
+
95
+ Returns:
96
+ IPythonCodeResult: The result of the code execution.
97
+ """
98
+ self._jupyter_kernel_client.wait_for_ready()
99
+ outputs = []
100
+ output_files = []
101
+ for code_block in code_blocks:
102
+ code = silence_pip(code_block.code, code_block.language)
103
+ result = self._jupyter_kernel_client.execute(code, timeout_seconds=self._timeout)
104
+ if result.is_ok:
105
+ outputs.append(result.output)
106
+ for data in result.data_items:
107
+ if data.mime_type == "image/png":
108
+ path = self._save_image(data.data)
109
+ outputs.append(f"Image data saved to {path}")
110
+ output_files.append(path)
111
+ elif data.mime_type == "text/html":
112
+ path = self._save_html(data.data)
113
+ outputs.append(f"HTML data saved to {path}")
114
+ output_files.append(path)
115
+ else:
116
+ outputs.append(json.dumps(data.data))
117
+ else:
118
+ return IPythonCodeResult(
119
+ exit_code=1,
120
+ output=f"ERROR: {result.output}",
121
+ )
122
+
123
+ return IPythonCodeResult(
124
+ exit_code=0, output="\n".join([str(output) for output in outputs]), output_files=output_files
125
+ )
126
+
127
+ def restart(self) -> None:
128
+ """(Experimental) Restart a new session."""
129
+ self._jupyter_client.restart_kernel(self._kernel_id)
130
+ self._jupyter_kernel_client = self._jupyter_client.get_kernel_client(self._kernel_id)
131
+
132
+ def _save_image(self, image_data_base64: str) -> str:
133
+ """Save image data to a file."""
134
+ image_data = base64.b64decode(image_data_base64)
135
+ # Randomly generate a filename.
136
+ filename = f"{uuid.uuid4().hex}.png"
137
+ path = os.path.join(self._output_dir, filename)
138
+ with open(path, "wb") as f:
139
+ f.write(image_data)
140
+ return os.path.abspath(path)
141
+
142
+ def _save_html(self, html_data: str) -> str:
143
+ """Save html data to a file."""
144
+ # Randomly generate a filename.
145
+ filename = f"{uuid.uuid4().hex}.html"
146
+ path = os.path.join(self._output_dir, filename)
147
+ with open(path, "w") as f:
148
+ f.write(html_data)
149
+ return os.path.abspath(path)
150
+
151
+ def stop(self) -> None:
152
+ """Stop the kernel."""
153
+ self._jupyter_client.delete_kernel(self._kernel_id)
154
+
155
+ def __enter__(self) -> Self:
156
+ return self
157
+
158
+ def __exit__(
159
+ self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]
160
+ ) -> None:
161
+ self.stop()
@@ -0,0 +1,168 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/autogen-ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Original portions of this file are derived from https://github.com/microsoft/autogen under the MIT License.
6
+ # SPDX-License-Identifier: MIT
7
+ from __future__ import annotations
8
+
9
+ import atexit
10
+ import json
11
+ import secrets
12
+ import signal
13
+ import socket
14
+ import subprocess
15
+ import sys
16
+ from types import TracebackType
17
+ from typing import Optional, Type, Union, cast
18
+
19
+ if sys.version_info >= (3, 11):
20
+ from typing import Self
21
+ else:
22
+ from typing_extensions import Self
23
+
24
+ from .base import JupyterConnectable, JupyterConnectionInfo
25
+ from .jupyter_client import JupyterClient
26
+
27
+
28
+ class LocalJupyterServer(JupyterConnectable):
29
+ class GenerateToken:
30
+ pass
31
+
32
+ def __init__(
33
+ self,
34
+ ip: str = "127.0.0.1",
35
+ port: Optional[int] = None,
36
+ token: Union[str, GenerateToken] = GenerateToken(),
37
+ log_file: str = "jupyter_gateway.log",
38
+ log_level: str = "INFO",
39
+ log_max_bytes: int = 1048576,
40
+ log_backup_count: int = 3,
41
+ ):
42
+ """Runs a Jupyter Kernel Gateway server locally.
43
+
44
+ Args:
45
+ ip (str, optional): IP address to bind to. Defaults to "127.0.0.1".
46
+ port (Optional[int], optional): Port to use, if None it automatically selects a port. Defaults to None.
47
+ token (Union[str, GenerateToken], optional): Token to use for Jupyter server. By default will generate a token. Using None will use no token for authentication. Defaults to GenerateToken().
48
+ log_file (str, optional): File for Jupyter Kernel Gateway logs. Defaults to "jupyter_gateway.log".
49
+ log_level (str, optional): Level for Jupyter Kernel Gateway logs. Defaults to "INFO".
50
+ log_max_bytes (int, optional): Max logfile size. Defaults to 1048576.
51
+ log_backup_count (int, optional): Number of backups for rotating log. Defaults to 3.
52
+ """
53
+ # Remove as soon as https://github.com/jupyter-server/kernel_gateway/issues/398 is fixed
54
+ if sys.platform == "win32":
55
+ raise ValueError("LocalJupyterServer is not supported on Windows due to kernelgateway bug.")
56
+
57
+ # Check Jupyter gateway server is installed
58
+ try:
59
+ subprocess.run(
60
+ [sys.executable, "-m", "jupyter", "kernelgateway", "--version"],
61
+ check=True,
62
+ stdout=subprocess.PIPE,
63
+ stderr=subprocess.PIPE,
64
+ text=True,
65
+ )
66
+ except subprocess.CalledProcessError:
67
+ raise ValueError(
68
+ "Jupyter gateway server is not installed. Please install it with `pip install jupyter_kernel_gateway`."
69
+ )
70
+
71
+ self.ip = ip
72
+
73
+ if isinstance(token, LocalJupyterServer.GenerateToken):
74
+ token = secrets.token_hex(32)
75
+
76
+ self.token = token
77
+ logging_config = {
78
+ "handlers": {
79
+ "file": {
80
+ "class": "logging.handlers.RotatingFileHandler",
81
+ "level": log_level,
82
+ "maxBytes": log_max_bytes,
83
+ "backupCount": log_backup_count,
84
+ "filename": log_file,
85
+ }
86
+ },
87
+ "loggers": {"KernelGatewayApp": {"level": log_level, "handlers": ["file", "console"]}},
88
+ }
89
+
90
+ # Run Jupyter gateway server with detached subprocess
91
+ args = [
92
+ sys.executable,
93
+ "-m",
94
+ "jupyter",
95
+ "kernelgateway",
96
+ "--KernelGatewayApp.ip",
97
+ ip,
98
+ "--KernelGatewayApp.auth_token",
99
+ token,
100
+ "--JupyterApp.answer_yes",
101
+ "true",
102
+ "--JupyterApp.logging_config",
103
+ json.dumps(logging_config),
104
+ "--JupyterWebsocketPersonality.list_kernels",
105
+ "true",
106
+ ]
107
+ if port is not None:
108
+ args.extend(["--KernelGatewayApp.port", str(port)])
109
+ args.extend(["--KernelGatewayApp.port_retries", "0"])
110
+ self._subprocess = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
111
+
112
+ # Satisfy mypy, we know this is not None because we passed PIPE
113
+ assert self._subprocess.stderr is not None
114
+ # Read stderr until we see "is available at" or the process has exited with an error
115
+ stderr = ""
116
+ while True:
117
+ result = self._subprocess.poll()
118
+ if result is not None:
119
+ stderr += self._subprocess.stderr.read()
120
+ raise ValueError(f"Jupyter gateway server failed to start with exit code: {result}. stderr:\n{stderr}")
121
+ line = self._subprocess.stderr.readline()
122
+ stderr += line
123
+
124
+ if "ERROR:" in line:
125
+ error_info = line.split("ERROR:")[1]
126
+ raise ValueError(f"Jupyter gateway server failed to start. {error_info}")
127
+
128
+ if "is available at" in line:
129
+ # We need to extract what port it settled on
130
+ # Example output:
131
+ # Jupyter Kernel Gateway 3.0.0 is available at http://127.0.0.1:8890
132
+ if port is None:
133
+ port = int(line.split(":")[-1])
134
+ self.port = port
135
+
136
+ break
137
+
138
+ # Poll the subprocess to check if it is still running
139
+ result = self._subprocess.poll()
140
+ if result is not None:
141
+ raise ValueError(
142
+ f"Jupyter gateway server failed to start. Please check the logs ({log_file}) for more information."
143
+ )
144
+
145
+ atexit.register(self.stop)
146
+
147
+ def stop(self) -> None:
148
+ if self._subprocess.poll() is None:
149
+ if sys.platform == "win32":
150
+ self._subprocess.send_signal(signal.CTRL_C_EVENT)
151
+ else:
152
+ self._subprocess.send_signal(signal.SIGINT)
153
+ self._subprocess.wait()
154
+
155
+ @property
156
+ def connection_info(self) -> JupyterConnectionInfo:
157
+ return JupyterConnectionInfo(host=self.ip, use_https=False, port=self.port, token=self.token)
158
+
159
+ def get_client(self) -> JupyterClient:
160
+ return JupyterClient(self.connection_info)
161
+
162
+ def __enter__(self) -> Self:
163
+ return self
164
+
165
+ def __exit__(
166
+ self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]
167
+ ) -> None:
168
+ self.stop()