ag2 0.4.1__py3-none-any.whl → 0.5.0__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 (160) hide show
  1. {ag2-0.4.1.dist-info → ag2-0.5.0.dist-info}/METADATA +5 -146
  2. ag2-0.5.0.dist-info/RECORD +6 -0
  3. ag2-0.5.0.dist-info/top_level.txt +1 -0
  4. ag2-0.4.1.dist-info/RECORD +0 -158
  5. ag2-0.4.1.dist-info/top_level.txt +0 -1
  6. autogen/__init__.py +0 -17
  7. autogen/_pydantic.py +0 -116
  8. autogen/agentchat/__init__.py +0 -42
  9. autogen/agentchat/agent.py +0 -142
  10. autogen/agentchat/assistant_agent.py +0 -85
  11. autogen/agentchat/chat.py +0 -306
  12. autogen/agentchat/contrib/__init__.py +0 -0
  13. autogen/agentchat/contrib/agent_builder.py +0 -788
  14. autogen/agentchat/contrib/agent_eval/agent_eval.py +0 -107
  15. autogen/agentchat/contrib/agent_eval/criterion.py +0 -47
  16. autogen/agentchat/contrib/agent_eval/critic_agent.py +0 -47
  17. autogen/agentchat/contrib/agent_eval/quantifier_agent.py +0 -42
  18. autogen/agentchat/contrib/agent_eval/subcritic_agent.py +0 -48
  19. autogen/agentchat/contrib/agent_eval/task.py +0 -43
  20. autogen/agentchat/contrib/agent_optimizer.py +0 -450
  21. autogen/agentchat/contrib/capabilities/__init__.py +0 -0
  22. autogen/agentchat/contrib/capabilities/agent_capability.py +0 -21
  23. autogen/agentchat/contrib/capabilities/generate_images.py +0 -297
  24. autogen/agentchat/contrib/capabilities/teachability.py +0 -406
  25. autogen/agentchat/contrib/capabilities/text_compressors.py +0 -72
  26. autogen/agentchat/contrib/capabilities/transform_messages.py +0 -92
  27. autogen/agentchat/contrib/capabilities/transforms.py +0 -565
  28. autogen/agentchat/contrib/capabilities/transforms_util.py +0 -120
  29. autogen/agentchat/contrib/capabilities/vision_capability.py +0 -217
  30. autogen/agentchat/contrib/captainagent/tools/__init__.py +0 -0
  31. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_correlation.py +0 -41
  32. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_skewness_and_kurtosis.py +0 -29
  33. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_iqr.py +0 -29
  34. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_zscore.py +0 -29
  35. autogen/agentchat/contrib/captainagent/tools/data_analysis/explore_csv.py +0 -22
  36. autogen/agentchat/contrib/captainagent/tools/data_analysis/shapiro_wilk_test.py +0 -31
  37. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_download.py +0 -26
  38. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_search.py +0 -55
  39. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_image.py +0 -54
  40. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_text.py +0 -39
  41. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_wikipedia_text.py +0 -22
  42. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_youtube_caption.py +0 -35
  43. autogen/agentchat/contrib/captainagent/tools/information_retrieval/image_qa.py +0 -61
  44. autogen/agentchat/contrib/captainagent/tools/information_retrieval/optical_character_recognition.py +0 -62
  45. autogen/agentchat/contrib/captainagent/tools/information_retrieval/perform_web_search.py +0 -48
  46. autogen/agentchat/contrib/captainagent/tools/information_retrieval/scrape_wikipedia_tables.py +0 -34
  47. autogen/agentchat/contrib/captainagent/tools/information_retrieval/transcribe_audio_file.py +0 -22
  48. autogen/agentchat/contrib/captainagent/tools/information_retrieval/youtube_download.py +0 -36
  49. autogen/agentchat/contrib/captainagent/tools/math/calculate_circle_area_from_diameter.py +0 -22
  50. autogen/agentchat/contrib/captainagent/tools/math/calculate_day_of_the_week.py +0 -19
  51. autogen/agentchat/contrib/captainagent/tools/math/calculate_fraction_sum.py +0 -29
  52. autogen/agentchat/contrib/captainagent/tools/math/calculate_matrix_power.py +0 -32
  53. autogen/agentchat/contrib/captainagent/tools/math/calculate_reflected_point.py +0 -17
  54. autogen/agentchat/contrib/captainagent/tools/math/complex_numbers_product.py +0 -26
  55. autogen/agentchat/contrib/captainagent/tools/math/compute_currency_conversion.py +0 -24
  56. autogen/agentchat/contrib/captainagent/tools/math/count_distinct_permutations.py +0 -28
  57. autogen/agentchat/contrib/captainagent/tools/math/evaluate_expression.py +0 -29
  58. autogen/agentchat/contrib/captainagent/tools/math/find_continuity_point.py +0 -35
  59. autogen/agentchat/contrib/captainagent/tools/math/fraction_to_mixed_numbers.py +0 -40
  60. autogen/agentchat/contrib/captainagent/tools/math/modular_inverse_sum.py +0 -23
  61. autogen/agentchat/contrib/captainagent/tools/math/simplify_mixed_numbers.py +0 -37
  62. autogen/agentchat/contrib/captainagent/tools/math/sum_of_digit_factorials.py +0 -16
  63. autogen/agentchat/contrib/captainagent/tools/math/sum_of_primes_below.py +0 -16
  64. autogen/agentchat/contrib/captainagent/tools/requirements.txt +0 -10
  65. autogen/agentchat/contrib/captainagent/tools/tool_description.tsv +0 -34
  66. autogen/agentchat/contrib/captainagent.py +0 -490
  67. autogen/agentchat/contrib/gpt_assistant_agent.py +0 -545
  68. autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
  69. autogen/agentchat/contrib/graph_rag/document.py +0 -30
  70. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +0 -111
  71. autogen/agentchat/contrib/graph_rag/falkor_graph_rag_capability.py +0 -81
  72. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +0 -56
  73. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +0 -64
  74. autogen/agentchat/contrib/img_utils.py +0 -390
  75. autogen/agentchat/contrib/llamaindex_conversable_agent.py +0 -123
  76. autogen/agentchat/contrib/llava_agent.py +0 -176
  77. autogen/agentchat/contrib/math_user_proxy_agent.py +0 -471
  78. autogen/agentchat/contrib/multimodal_conversable_agent.py +0 -128
  79. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +0 -325
  80. autogen/agentchat/contrib/retrieve_assistant_agent.py +0 -56
  81. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +0 -705
  82. autogen/agentchat/contrib/society_of_mind_agent.py +0 -203
  83. autogen/agentchat/contrib/swarm_agent.py +0 -463
  84. autogen/agentchat/contrib/text_analyzer_agent.py +0 -76
  85. autogen/agentchat/contrib/tool_retriever.py +0 -120
  86. autogen/agentchat/contrib/vectordb/__init__.py +0 -0
  87. autogen/agentchat/contrib/vectordb/base.py +0 -243
  88. autogen/agentchat/contrib/vectordb/chromadb.py +0 -326
  89. autogen/agentchat/contrib/vectordb/mongodb.py +0 -559
  90. autogen/agentchat/contrib/vectordb/pgvectordb.py +0 -958
  91. autogen/agentchat/contrib/vectordb/qdrant.py +0 -334
  92. autogen/agentchat/contrib/vectordb/utils.py +0 -126
  93. autogen/agentchat/contrib/web_surfer.py +0 -305
  94. autogen/agentchat/conversable_agent.py +0 -2908
  95. autogen/agentchat/groupchat.py +0 -1668
  96. autogen/agentchat/user_proxy_agent.py +0 -109
  97. autogen/agentchat/utils.py +0 -207
  98. autogen/browser_utils.py +0 -291
  99. autogen/cache/__init__.py +0 -10
  100. autogen/cache/abstract_cache_base.py +0 -78
  101. autogen/cache/cache.py +0 -182
  102. autogen/cache/cache_factory.py +0 -85
  103. autogen/cache/cosmos_db_cache.py +0 -150
  104. autogen/cache/disk_cache.py +0 -109
  105. autogen/cache/in_memory_cache.py +0 -61
  106. autogen/cache/redis_cache.py +0 -128
  107. autogen/code_utils.py +0 -745
  108. autogen/coding/__init__.py +0 -22
  109. autogen/coding/base.py +0 -113
  110. autogen/coding/docker_commandline_code_executor.py +0 -262
  111. autogen/coding/factory.py +0 -45
  112. autogen/coding/func_with_reqs.py +0 -203
  113. autogen/coding/jupyter/__init__.py +0 -22
  114. autogen/coding/jupyter/base.py +0 -32
  115. autogen/coding/jupyter/docker_jupyter_server.py +0 -164
  116. autogen/coding/jupyter/embedded_ipython_code_executor.py +0 -182
  117. autogen/coding/jupyter/jupyter_client.py +0 -224
  118. autogen/coding/jupyter/jupyter_code_executor.py +0 -161
  119. autogen/coding/jupyter/local_jupyter_server.py +0 -168
  120. autogen/coding/local_commandline_code_executor.py +0 -410
  121. autogen/coding/markdown_code_extractor.py +0 -44
  122. autogen/coding/utils.py +0 -57
  123. autogen/exception_utils.py +0 -46
  124. autogen/extensions/__init__.py +0 -0
  125. autogen/formatting_utils.py +0 -76
  126. autogen/function_utils.py +0 -362
  127. autogen/graph_utils.py +0 -148
  128. autogen/io/__init__.py +0 -15
  129. autogen/io/base.py +0 -105
  130. autogen/io/console.py +0 -43
  131. autogen/io/websockets.py +0 -213
  132. autogen/logger/__init__.py +0 -11
  133. autogen/logger/base_logger.py +0 -140
  134. autogen/logger/file_logger.py +0 -287
  135. autogen/logger/logger_factory.py +0 -29
  136. autogen/logger/logger_utils.py +0 -42
  137. autogen/logger/sqlite_logger.py +0 -459
  138. autogen/math_utils.py +0 -356
  139. autogen/oai/__init__.py +0 -33
  140. autogen/oai/anthropic.py +0 -428
  141. autogen/oai/bedrock.py +0 -606
  142. autogen/oai/cerebras.py +0 -270
  143. autogen/oai/client.py +0 -1148
  144. autogen/oai/client_utils.py +0 -167
  145. autogen/oai/cohere.py +0 -453
  146. autogen/oai/completion.py +0 -1216
  147. autogen/oai/gemini.py +0 -469
  148. autogen/oai/groq.py +0 -281
  149. autogen/oai/mistral.py +0 -279
  150. autogen/oai/ollama.py +0 -582
  151. autogen/oai/openai_utils.py +0 -811
  152. autogen/oai/together.py +0 -343
  153. autogen/retrieve_utils.py +0 -487
  154. autogen/runtime_logging.py +0 -163
  155. autogen/token_count_utils.py +0 -259
  156. autogen/types.py +0 -20
  157. autogen/version.py +0 -7
  158. {ag2-0.4.1.dist-info → ag2-0.5.0.dist-info}/LICENSE +0 -0
  159. {ag2-0.4.1.dist-info → ag2-0.5.0.dist-info}/NOTICE.md +0 -0
  160. {ag2-0.4.1.dist-info → ag2-0.5.0.dist-info}/WHEEL +0 -0
@@ -1,811 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- #
5
- # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
- # SPDX-License-Identifier: MIT
7
- import importlib.metadata
8
- import json
9
- import logging
10
- import os
11
- import re
12
- import tempfile
13
- import time
14
- from pathlib import Path
15
- from typing import Any, Dict, List, Optional, Set, Union
16
-
17
- from dotenv import find_dotenv, load_dotenv
18
- from openai import OpenAI
19
- from openai.types.beta.assistant import Assistant
20
- from packaging.version import parse
21
-
22
- NON_CACHE_KEY = [
23
- "api_key",
24
- "base_url",
25
- "api_type",
26
- "api_version",
27
- "azure_ad_token",
28
- "azure_ad_token_provider",
29
- "credentials",
30
- ]
31
- DEFAULT_AZURE_API_VERSION = "2024-02-01"
32
- OAI_PRICE1K = {
33
- # https://openai.com/api/pricing/
34
- # gpt-4o
35
- "gpt-4o": (0.005, 0.015),
36
- "gpt-4o-2024-05-13": (0.005, 0.015),
37
- "gpt-4o-2024-08-06": (0.0025, 0.01),
38
- "gpt-4o-2024-11-20": (0.0025, 0.01),
39
- # gpt-4-turbo
40
- "gpt-4-turbo-2024-04-09": (0.01, 0.03),
41
- # gpt-4
42
- "gpt-4": (0.03, 0.06),
43
- "gpt-4-32k": (0.06, 0.12),
44
- # gpt-4o-mini
45
- "gpt-4o-mini": (0.000150, 0.000600),
46
- "gpt-4o-mini-2024-07-18": (0.000150, 0.000600),
47
- # gpt-3.5 turbo
48
- "gpt-3.5-turbo": (0.0005, 0.0015), # default is 0125
49
- "gpt-3.5-turbo-0125": (0.0005, 0.0015), # 16k
50
- "gpt-3.5-turbo-instruct": (0.0015, 0.002),
51
- # base model
52
- "davinci-002": 0.002,
53
- "babbage-002": 0.0004,
54
- # old model
55
- "gpt-4-0125-preview": (0.01, 0.03),
56
- "gpt-4-1106-preview": (0.01, 0.03),
57
- "gpt-4-1106-vision-preview": (0.01, 0.03), # TODO: support vision pricing of images
58
- "gpt-3.5-turbo-1106": (0.001, 0.002),
59
- "gpt-3.5-turbo-0613": (0.0015, 0.002),
60
- # "gpt-3.5-turbo-16k": (0.003, 0.004),
61
- "gpt-3.5-turbo-16k-0613": (0.003, 0.004),
62
- "gpt-3.5-turbo-0301": (0.0015, 0.002),
63
- "text-ada-001": 0.0004,
64
- "text-babbage-001": 0.0005,
65
- "text-curie-001": 0.002,
66
- "code-cushman-001": 0.024,
67
- "code-davinci-002": 0.1,
68
- "text-davinci-002": 0.02,
69
- "text-davinci-003": 0.02,
70
- "gpt-4-0314": (0.03, 0.06), # deprecate in Sep
71
- "gpt-4-32k-0314": (0.06, 0.12), # deprecate in Sep
72
- "gpt-4-0613": (0.03, 0.06),
73
- "gpt-4-32k-0613": (0.06, 0.12),
74
- "gpt-4-turbo-preview": (0.01, 0.03),
75
- # https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/#pricing
76
- "gpt-35-turbo": (0.0005, 0.0015), # what's the default? using 0125 here.
77
- "gpt-35-turbo-0125": (0.0005, 0.0015),
78
- "gpt-35-turbo-instruct": (0.0015, 0.002),
79
- "gpt-35-turbo-1106": (0.001, 0.002),
80
- "gpt-35-turbo-0613": (0.0015, 0.002),
81
- "gpt-35-turbo-0301": (0.0015, 0.002),
82
- "gpt-35-turbo-16k": (0.003, 0.004),
83
- "gpt-35-turbo-16k-0613": (0.003, 0.004),
84
- }
85
-
86
-
87
- def get_key(config: Dict[str, Any]) -> str:
88
- """Get a unique identifier of a configuration.
89
-
90
- Args:
91
- config (dict or list): A configuration.
92
-
93
- Returns:
94
- tuple: A unique identifier which can be used as a key for a dict.
95
- """
96
- copied = False
97
- for key in NON_CACHE_KEY:
98
- if key in config:
99
- config, copied = config.copy() if not copied else config, True
100
- config.pop(key)
101
- # if isinstance(config, dict):
102
- # return tuple(get_key(x) for x in sorted(config.items()))
103
- # if isinstance(config, list):
104
- # return tuple(get_key(x) for x in config)
105
- # return config
106
- return json.dumps(config, sort_keys=True)
107
-
108
-
109
- def is_valid_api_key(api_key: str) -> bool:
110
- """Determine if input is valid OpenAI API key. As of 2024-09-24 there's no official definition of the key structure
111
- so we will allow anything starting with "sk-" and having at least 48 alphanumeric (plus underscore and dash) characters.
112
- Keys are known to start with "sk-", "sk-proj", "sk-None", and "sk-svcaat"
113
-
114
- Args:
115
- api_key (str): An input string to be validated.
116
-
117
- Returns:
118
- bool: A boolean that indicates if input is valid OpenAI API key.
119
- """
120
- api_key_re = re.compile(r"^sk-[A-Za-z0-9_-]{48,}$")
121
- return bool(re.fullmatch(api_key_re, api_key))
122
-
123
-
124
- def get_config_list(
125
- api_keys: List[str],
126
- base_urls: Optional[List[str]] = None,
127
- api_type: Optional[str] = None,
128
- api_version: Optional[str] = None,
129
- ) -> List[Dict[str, Any]]:
130
- """Get a list of configs for OpenAI API client.
131
-
132
- Args:
133
- api_keys (list): The api keys for openai api calls.
134
- base_urls (list, optional): The api bases for openai api calls. If provided, should match the length of api_keys.
135
- api_type (str, optional): The api type for openai api calls.
136
- api_version (str, optional): The api version for openai api calls.
137
-
138
- Returns:
139
- list: A list of configs for OepnAI API calls.
140
-
141
- Example:
142
- ```python
143
- # Define a list of API keys
144
- api_keys = ['key1', 'key2', 'key3']
145
-
146
- # Optionally, define a list of base URLs corresponding to each API key
147
- base_urls = ['https://api.service1.com', 'https://api.service2.com', 'https://api.service3.com']
148
-
149
- # Optionally, define the API type and version if they are common for all keys
150
- api_type = 'azure'
151
- api_version = '2024-02-01'
152
-
153
- # Call the get_config_list function to get a list of configuration dictionaries
154
- config_list = get_config_list(api_keys, base_urls, api_type, api_version)
155
- ```
156
-
157
- """
158
- if base_urls is not None:
159
- assert len(api_keys) == len(base_urls), "The length of api_keys must match the length of base_urls"
160
- config_list = []
161
- for i, api_key in enumerate(api_keys):
162
- if not api_key.strip():
163
- continue
164
- config = {"api_key": api_key}
165
- if base_urls:
166
- config["base_url"] = base_urls[i]
167
- if api_type:
168
- config["api_type"] = api_type
169
- if api_version:
170
- config["api_version"] = api_version
171
- config_list.append(config)
172
- return config_list
173
-
174
-
175
- def config_list_openai_aoai(
176
- key_file_path: Optional[str] = ".",
177
- openai_api_key_file: Optional[str] = "key_openai.txt",
178
- aoai_api_key_file: Optional[str] = "key_aoai.txt",
179
- openai_api_base_file: Optional[str] = "base_openai.txt",
180
- aoai_api_base_file: Optional[str] = "base_aoai.txt",
181
- exclude: Optional[str] = None,
182
- ) -> List[Dict[str, Any]]:
183
- """Get a list of configs for OpenAI API client (including Azure or local model deployments that support OpenAI's chat completion API).
184
-
185
- This function constructs configurations by reading API keys and base URLs from environment variables or text files.
186
- It supports configurations for both OpenAI and Azure OpenAI services, allowing for the exclusion of one or the other.
187
- When text files are used, the environment variables will be overwritten.
188
- To prevent text files from being used, set the corresponding file name to None.
189
- Or set key_file_path to None to disallow reading from text files.
190
-
191
- Args:
192
- key_file_path (str, optional): The directory path where the API key files are located. Defaults to the current directory.
193
- openai_api_key_file (str, optional): The filename containing the OpenAI API key. Defaults to 'key_openai.txt'.
194
- aoai_api_key_file (str, optional): The filename containing the Azure OpenAI API key. Defaults to 'key_aoai.txt'.
195
- openai_api_base_file (str, optional): The filename containing the OpenAI API base URL. Defaults to 'base_openai.txt'.
196
- aoai_api_base_file (str, optional): The filename containing the Azure OpenAI API base URL. Defaults to 'base_aoai.txt'.
197
- exclude (str, optional): The API type to exclude from the configuration list. Can be 'openai' or 'aoai'. Defaults to None.
198
-
199
- Returns:
200
- List[Dict]: A list of configuration dictionaries. Each dictionary contains keys for 'api_key',
201
- and optionally 'base_url', 'api_type', and 'api_version'.
202
-
203
- Raises:
204
- FileNotFoundError: If the specified key files are not found and the corresponding API key is not set in the environment variables.
205
-
206
- Example:
207
- # To generate configurations excluding Azure OpenAI:
208
- configs = config_list_openai_aoai(exclude='aoai')
209
-
210
- File samples:
211
- - key_aoai.txt
212
-
213
- ```
214
- aoai-12345abcdef67890ghijklmnopqr
215
- aoai-09876zyxwvuts54321fedcba
216
- ```
217
-
218
- - base_aoai.txt
219
-
220
- ```
221
- https://api.azure.com/v1
222
- https://api.azure2.com/v1
223
- ```
224
-
225
- Notes:
226
- - The function checks for API keys and base URLs in the following environment variables: 'OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY',
227
- 'OPENAI_API_BASE' and 'AZURE_OPENAI_API_BASE'. If these are not found, it attempts to read from the specified files in the
228
- 'key_file_path' directory.
229
- - The API version for Azure configurations is set to DEFAULT_AZURE_API_VERSION by default.
230
- - If 'exclude' is set to 'openai', only Azure OpenAI configurations are returned, and vice versa.
231
- - The function assumes that the API keys and base URLs in the environment variables are separated by new lines if there are
232
- multiple entries.
233
- """
234
- if exclude != "openai" and key_file_path is not None:
235
- # skip if key_file_path is None
236
- if openai_api_key_file is not None:
237
- # skip if openai_api_key_file is None
238
- try:
239
- with open(f"{key_file_path}/{openai_api_key_file}") as key_file:
240
- os.environ["OPENAI_API_KEY"] = key_file.read().strip()
241
- except FileNotFoundError:
242
- logging.info(
243
- "OPENAI_API_KEY is not found in os.environ "
244
- "and key_openai.txt is not found in the specified path. You can specify the api_key in the config_list."
245
- )
246
- if openai_api_base_file is not None:
247
- # skip if openai_api_base_file is None
248
- try:
249
- with open(f"{key_file_path}/{openai_api_base_file}") as key_file:
250
- os.environ["OPENAI_API_BASE"] = key_file.read().strip()
251
- except FileNotFoundError:
252
- logging.info(
253
- "OPENAI_API_BASE is not found in os.environ "
254
- "and base_openai.txt is not found in the specified path. You can specify the base_url in the config_list."
255
- )
256
- if exclude != "aoai" and key_file_path is not None:
257
- # skip if key_file_path is None
258
- if aoai_api_key_file is not None:
259
- try:
260
- with open(f"{key_file_path}/{aoai_api_key_file}") as key_file:
261
- os.environ["AZURE_OPENAI_API_KEY"] = key_file.read().strip()
262
- except FileNotFoundError:
263
- logging.info(
264
- "AZURE_OPENAI_API_KEY is not found in os.environ "
265
- "and key_aoai.txt is not found in the specified path. You can specify the api_key in the config_list."
266
- )
267
- if aoai_api_base_file is not None:
268
- try:
269
- with open(f"{key_file_path}/{aoai_api_base_file}") as key_file:
270
- os.environ["AZURE_OPENAI_API_BASE"] = key_file.read().strip()
271
- except FileNotFoundError:
272
- logging.info(
273
- "AZURE_OPENAI_API_BASE is not found in os.environ "
274
- "and base_aoai.txt is not found in the specified path. You can specify the base_url in the config_list."
275
- )
276
- aoai_config = (
277
- get_config_list(
278
- # Assuming Azure OpenAI api keys in os.environ["AZURE_OPENAI_API_KEY"], in separated lines
279
- api_keys=os.environ.get("AZURE_OPENAI_API_KEY", "").split("\n"),
280
- # Assuming Azure OpenAI api bases in os.environ["AZURE_OPENAI_API_BASE"], in separated lines
281
- base_urls=os.environ.get("AZURE_OPENAI_API_BASE", "").split("\n"),
282
- api_type="azure",
283
- api_version=DEFAULT_AZURE_API_VERSION,
284
- )
285
- if exclude != "aoai"
286
- else []
287
- )
288
- # process openai base urls
289
- base_urls_env_var = os.environ.get("OPENAI_API_BASE", None)
290
- base_urls = base_urls_env_var if base_urls_env_var is None else base_urls_env_var.split("\n")
291
- openai_config = (
292
- get_config_list(
293
- # Assuming OpenAI API_KEY in os.environ["OPENAI_API_KEY"]
294
- api_keys=os.environ.get("OPENAI_API_KEY", "").split("\n"),
295
- base_urls=base_urls,
296
- )
297
- if exclude != "openai"
298
- else []
299
- )
300
- config_list = openai_config + aoai_config
301
- return config_list
302
-
303
-
304
- def config_list_from_models(
305
- key_file_path: Optional[str] = ".",
306
- openai_api_key_file: Optional[str] = "key_openai.txt",
307
- aoai_api_key_file: Optional[str] = "key_aoai.txt",
308
- aoai_api_base_file: Optional[str] = "base_aoai.txt",
309
- exclude: Optional[str] = None,
310
- model_list: Optional[List[str]] = None,
311
- ) -> List[Dict[str, Any]]:
312
- """
313
- Get a list of configs for API calls with models specified in the model list.
314
-
315
- This function extends `config_list_openai_aoai` by allowing to clone its' out for each of the models provided.
316
- Each configuration will have a 'model' key with the model name as its value. This is particularly useful when
317
- all endpoints have same set of models.
318
-
319
- Args:
320
- key_file_path (str, optional): The path to the key files.
321
- openai_api_key_file (str, optional): The file name of the OpenAI API key.
322
- aoai_api_key_file (str, optional): The file name of the Azure OpenAI API key.
323
- aoai_api_base_file (str, optional): The file name of the Azure OpenAI API base.
324
- exclude (str, optional): The API type to exclude, "openai" or "aoai".
325
- model_list (list, optional): The list of model names to include in the configs.
326
-
327
- Returns:
328
- list: A list of configs for OpenAI API calls, each including model information.
329
-
330
- Example:
331
- ```python
332
- # Define the path where the API key files are located
333
- key_file_path = '/path/to/key/files'
334
-
335
- # Define the file names for the OpenAI and Azure OpenAI API keys and bases
336
- openai_api_key_file = 'key_openai.txt'
337
- aoai_api_key_file = 'key_aoai.txt'
338
- aoai_api_base_file = 'base_aoai.txt'
339
-
340
- # Define the list of models for which to create configurations
341
- model_list = ['gpt-4', 'gpt-3.5-turbo']
342
-
343
- # Call the function to get a list of configuration dictionaries
344
- config_list = config_list_from_models(
345
- key_file_path=key_file_path,
346
- openai_api_key_file=openai_api_key_file,
347
- aoai_api_key_file=aoai_api_key_file,
348
- aoai_api_base_file=aoai_api_base_file,
349
- model_list=model_list
350
- )
351
-
352
- # The `config_list` will contain configurations for the specified models, for example:
353
- # [
354
- # {'api_key': '...', 'base_url': 'https://api.openai.com', 'model': 'gpt-4'},
355
- # {'api_key': '...', 'base_url': 'https://api.openai.com', 'model': 'gpt-3.5-turbo'}
356
- # ]
357
- ```
358
- """
359
- config_list = config_list_openai_aoai(
360
- key_file_path=key_file_path,
361
- openai_api_key_file=openai_api_key_file,
362
- aoai_api_key_file=aoai_api_key_file,
363
- aoai_api_base_file=aoai_api_base_file,
364
- exclude=exclude,
365
- )
366
- if model_list:
367
- config_list = [{**config, "model": model} for model in model_list for config in config_list]
368
- return config_list
369
-
370
-
371
- def config_list_gpt4_gpt35(
372
- key_file_path: Optional[str] = ".",
373
- openai_api_key_file: Optional[str] = "key_openai.txt",
374
- aoai_api_key_file: Optional[str] = "key_aoai.txt",
375
- aoai_api_base_file: Optional[str] = "base_aoai.txt",
376
- exclude: Optional[str] = None,
377
- ) -> List[Dict[str, Any]]:
378
- """Get a list of configs for 'gpt-4' followed by 'gpt-3.5-turbo' API calls.
379
-
380
- Args:
381
- key_file_path (str, optional): The path to the key files.
382
- openai_api_key_file (str, optional): The file name of the openai api key.
383
- aoai_api_key_file (str, optional): The file name of the azure openai api key.
384
- aoai_api_base_file (str, optional): The file name of the azure openai api base.
385
- exclude (str, optional): The api type to exclude, "openai" or "aoai".
386
-
387
- Returns:
388
- list: A list of configs for openai api calls.
389
- """
390
- return config_list_from_models(
391
- key_file_path,
392
- openai_api_key_file,
393
- aoai_api_key_file,
394
- aoai_api_base_file,
395
- exclude,
396
- model_list=["gpt-4", "gpt-3.5-turbo"],
397
- )
398
-
399
-
400
- def filter_config(
401
- config_list: List[Dict[str, Any]],
402
- filter_dict: Optional[Dict[str, Union[List[Union[str, None]], Set[Union[str, None]]]]],
403
- exclude: bool = False,
404
- ) -> List[Dict[str, Any]]:
405
- """This function filters `config_list` by checking each configuration dictionary against the criteria specified in
406
- `filter_dict`. A configuration dictionary is retained if for every key in `filter_dict`, see example below.
407
-
408
- Args:
409
- config_list (list of dict): A list of configuration dictionaries to be filtered.
410
- filter_dict (dict): A dictionary representing the filter criteria, where each key is a
411
- field name to check within the configuration dictionaries, and the
412
- corresponding value is a list of acceptable values for that field.
413
- If the configuration's field's value is not a list, then a match occurs
414
- when it is found in the list of acceptable values. If the configuration's
415
- field's value is a list, then a match occurs if there is a non-empty
416
- intersection with the acceptable values.
417
- exclude (bool): If False (the default value), configs that match the filter will be included in the returned
418
- list. If True, configs that match the filter will be excluded in the returned list.
419
- Returns:
420
- list of dict: A list of configuration dictionaries that meet all the criteria specified
421
- in `filter_dict`.
422
-
423
- Example:
424
- ```python
425
- # Example configuration list with various models and API types
426
- configs = [
427
- {'model': 'gpt-3.5-turbo'},
428
- {'model': 'gpt-4'},
429
- {'model': 'gpt-3.5-turbo', 'api_type': 'azure'},
430
- {'model': 'gpt-3.5-turbo', 'tags': ['gpt35_turbo', 'gpt-35-turbo']},
431
- ]
432
- # Define filter criteria to select configurations for the 'gpt-3.5-turbo' model
433
- # that are also using the 'azure' API type
434
- filter_criteria = {
435
- 'model': ['gpt-3.5-turbo'], # Only accept configurations for 'gpt-3.5-turbo'
436
- 'api_type': ['azure'] # Only accept configurations for 'azure' API type
437
- }
438
- # Apply the filter to the configuration list
439
- filtered_configs = filter_config(configs, filter_criteria)
440
- # The resulting `filtered_configs` will be:
441
- # [{'model': 'gpt-3.5-turbo', 'api_type': 'azure', ...}]
442
- # Define a filter to select a given tag
443
- filter_criteria = {
444
- 'tags': ['gpt35_turbo'],
445
- }
446
- # Apply the filter to the configuration list
447
- filtered_configs = filter_config(configs, filter_criteria)
448
- # The resulting `filtered_configs` will be:
449
- # [{'model': 'gpt-3.5-turbo', 'tags': ['gpt35_turbo', 'gpt-35-turbo']}]
450
- ```
451
- Note:
452
- - If `filter_dict` is empty or None, no filtering is applied and `config_list` is returned as is.
453
- - If a configuration dictionary in `config_list` does not contain a key specified in `filter_dict`,
454
- it is considered a non-match and is excluded from the result.
455
- - If the list of acceptable values for a key in `filter_dict` includes None, then configuration
456
- dictionaries that do not have that key will also be considered a match.
457
-
458
- """
459
-
460
- if filter_dict:
461
- return [
462
- item
463
- for item in config_list
464
- if all(_satisfies_criteria(item.get(key), values) != exclude for key, values in filter_dict.items())
465
- ]
466
- return config_list
467
-
468
-
469
- def _satisfies_criteria(value: Any, criteria_values: Any) -> bool:
470
- if value is None:
471
- return False
472
-
473
- if isinstance(value, list):
474
- return bool(set(value) & set(criteria_values)) # Non-empty intersection
475
- else:
476
- return value in criteria_values
477
-
478
-
479
- def config_list_from_json(
480
- env_or_file: str,
481
- file_location: Optional[str] = "",
482
- filter_dict: Optional[Dict[str, Union[List[Union[str, None]], Set[Union[str, None]]]]] = None,
483
- ) -> List[Dict[str, Any]]:
484
- """
485
- Retrieves a list of API configurations from a JSON stored in an environment variable or a file.
486
-
487
- This function attempts to parse JSON data from the given `env_or_file` parameter. If `env_or_file` is an
488
- environment variable containing JSON data, it will be used directly. Otherwise, it is assumed to be a filename,
489
- and the function will attempt to read the file from the specified `file_location`.
490
-
491
- The `filter_dict` parameter allows for filtering the configurations based on specified criteria. Each key in the
492
- `filter_dict` corresponds to a field in the configuration dictionaries, and the associated value is a list or set
493
- of acceptable values for that field. If a field is missing in a configuration and `None` is included in the list
494
- of acceptable values for that field, the configuration will still be considered a match.
495
-
496
- Args:
497
- env_or_file (str): The name of the environment variable, the filename, or the environment variable of the filename
498
- that containing the JSON data.
499
- file_location (str, optional): The directory path where the file is located, if `env_or_file` is a filename.
500
- filter_dict (dict, optional): A dictionary specifying the filtering criteria for the configurations, with
501
- keys representing field names and values being lists or sets of acceptable values for those fields.
502
-
503
- Example:
504
- ```python
505
- # Suppose we have an environment variable 'CONFIG_JSON' with the following content:
506
- # '[{"model": "gpt-3.5-turbo", "api_type": "azure"}, {"model": "gpt-4"}]'
507
-
508
- # We can retrieve a filtered list of configurations like this:
509
- filter_criteria = {"model": ["gpt-3.5-turbo"]}
510
- configs = config_list_from_json('CONFIG_JSON', filter_dict=filter_criteria)
511
- # The 'configs' variable will now contain only the configurations that match the filter criteria.
512
- ```
513
-
514
- Returns:
515
- List[Dict]: A list of configuration dictionaries that match the filtering criteria specified in `filter_dict`.
516
-
517
- Raises:
518
- FileNotFoundError: if env_or_file is neither found as an environment variable nor a file
519
- """
520
- env_str = os.environ.get(env_or_file)
521
-
522
- if env_str:
523
- # The environment variable exists. We should use information from it.
524
- if os.path.exists(env_str):
525
- # It is a file location, and we need to load the json from the file.
526
- with open(env_str, "r") as file:
527
- json_str = file.read()
528
- else:
529
- # Else, it should be a JSON string by itself.
530
- json_str = env_str
531
- config_list = json.loads(json_str)
532
- else:
533
- # The environment variable does not exist.
534
- # So, `env_or_file` is a filename. We should use the file location.
535
- if file_location is not None:
536
- config_list_path = os.path.join(file_location, env_or_file)
537
- else:
538
- config_list_path = env_or_file
539
-
540
- with open(config_list_path) as json_file:
541
- config_list = json.load(json_file)
542
- return filter_config(config_list, filter_dict)
543
-
544
-
545
- def get_config(
546
- api_key: Optional[str],
547
- base_url: Optional[str] = None,
548
- api_type: Optional[str] = None,
549
- api_version: Optional[str] = None,
550
- ) -> Dict[str, Any]:
551
- """
552
- Constructs a configuration dictionary for a single model with the provided API configurations.
553
-
554
- Example:
555
- ```python
556
- config = get_config(
557
- api_key="sk-abcdef1234567890",
558
- base_url="https://api.openai.com",
559
- api_version="v1"
560
- )
561
- # The 'config' variable will now contain:
562
- # {
563
- # "api_key": "sk-abcdef1234567890",
564
- # "base_url": "https://api.openai.com",
565
- # "api_version": "v1"
566
- # }
567
- ```
568
-
569
- Args:
570
- api_key (str): The API key for authenticating API requests.
571
- base_url (Optional[str]): The base URL of the API. If not provided, defaults to None.
572
- api_type (Optional[str]): The type of API. If not provided, defaults to None.
573
- api_version (Optional[str]): The version of the API. If not provided, defaults to None.
574
-
575
- Returns:
576
- Dict: A dictionary containing the provided API configurations.
577
- """
578
- config = {"api_key": api_key}
579
- if base_url:
580
- config["base_url"] = os.getenv(base_url, default=base_url)
581
- if api_type:
582
- config["api_type"] = os.getenv(api_type, default=api_type)
583
- if api_version:
584
- config["api_version"] = os.getenv(api_version, default=api_version)
585
- return config
586
-
587
-
588
- def config_list_from_dotenv(
589
- dotenv_file_path: Optional[str] = None,
590
- model_api_key_map: Optional[Dict[str, Any]] = None,
591
- filter_dict: Optional[Dict[str, Union[List[Union[str, None]], Set[Union[str, None]]]]] = None,
592
- ) -> List[Dict[str, Union[str, Set[str]]]]:
593
- """
594
- Load API configurations from a specified .env file or environment variables and construct a list of configurations.
595
-
596
- This function will:
597
- - Load API keys from a provided .env file or from existing environment variables.
598
- - Create a configuration dictionary for each model using the API keys and additional configurations.
599
- - Filter and return the configurations based on provided filters.
600
-
601
- model_api_key_map will default to `{"gpt-4": "OPENAI_API_KEY", "gpt-3.5-turbo": "OPENAI_API_KEY"}` if none
602
-
603
- Args:
604
- dotenv_file_path (str, optional): The path to the .env file. Defaults to None.
605
- model_api_key_map (str/dict, optional): A dictionary mapping models to their API key configurations.
606
- If a string is provided as configuration, it is considered as an environment
607
- variable name storing the API key.
608
- If a dict is provided, it should contain at least 'api_key_env_var' key,
609
- and optionally other API configurations like 'base_url', 'api_type', and 'api_version'.
610
- Defaults to a basic map with 'gpt-4' and 'gpt-3.5-turbo' mapped to 'OPENAI_API_KEY'.
611
- filter_dict (dict, optional): A dictionary containing the models to be loaded.
612
- Containing a 'model' key mapped to a set of model names to be loaded.
613
- Defaults to None, which loads all found configurations.
614
-
615
- Returns:
616
- List[Dict[str, Union[str, Set[str]]]]: A list of configuration dictionaries for each model.
617
-
618
- Raises:
619
- FileNotFoundError: If the specified .env file does not exist.
620
- TypeError: If an unsupported type of configuration is provided in model_api_key_map.
621
- """
622
- if dotenv_file_path:
623
- dotenv_path = Path(dotenv_file_path)
624
- if dotenv_path.exists():
625
- load_dotenv(dotenv_path)
626
- else:
627
- logging.warning(f"The specified .env file {dotenv_path} does not exist.")
628
- else:
629
- dotenv_path_str = find_dotenv()
630
- if not dotenv_path_str:
631
- logging.warning("No .env file found. Loading configurations from environment variables.")
632
- dotenv_path = Path(dotenv_path_str)
633
- load_dotenv(dotenv_path)
634
-
635
- # Ensure the model_api_key_map is not None to prevent TypeErrors during key assignment.
636
- model_api_key_map = model_api_key_map or {}
637
-
638
- # Ensure default models are always considered
639
- default_models = ["gpt-4", "gpt-3.5-turbo"]
640
-
641
- for model in default_models:
642
- # Only assign default API key if the model is not present in the map.
643
- # If model is present but set to invalid/empty, do not overwrite.
644
- if model not in model_api_key_map:
645
- model_api_key_map[model] = "OPENAI_API_KEY"
646
-
647
- env_var = []
648
- # Loop over the models and create configuration dictionaries
649
- for model, config in model_api_key_map.items():
650
- if isinstance(config, str):
651
- api_key_env_var = config
652
- config_dict = get_config(api_key=os.getenv(api_key_env_var))
653
- elif isinstance(config, dict):
654
- api_key = os.getenv(config.get("api_key_env_var", "OPENAI_API_KEY"))
655
- config_without_key_var = {k: v for k, v in config.items() if k != "api_key_env_var"}
656
- config_dict = get_config(api_key=api_key, **config_without_key_var)
657
- else:
658
- logging.warning(f"Unsupported type {type(config)} for model {model} configuration")
659
-
660
- if not config_dict["api_key"] or config_dict["api_key"].strip() == "":
661
- logging.warning(
662
- f"API key not found or empty for model {model}. Please ensure path to .env file is correct."
663
- )
664
- continue # Skip this configuration and continue with the next
665
-
666
- # Add model to the configuration and append to the list
667
- config_dict["model"] = model
668
- env_var.append(config_dict)
669
-
670
- fd, temp_name = tempfile.mkstemp()
671
- try:
672
- with os.fdopen(fd, "w+") as temp:
673
- env_var_str = json.dumps(env_var)
674
- temp.write(env_var_str)
675
- temp.flush()
676
-
677
- # Assuming config_list_from_json is a valid function from your code
678
- config_list = config_list_from_json(env_or_file=temp_name, filter_dict=filter_dict)
679
- finally:
680
- # The file is deleted after using its name (to prevent windows build from breaking)
681
- os.remove(temp_name)
682
-
683
- if len(config_list) == 0:
684
- logging.error("No configurations loaded.")
685
- return []
686
-
687
- logging.info(f"Models available: {[config['model'] for config in config_list]}")
688
- return config_list
689
-
690
-
691
- def retrieve_assistants_by_name(client: OpenAI, name: str) -> List[Assistant]:
692
- """
693
- Return the assistants with the given name from OAI assistant API
694
- """
695
- assistants = client.beta.assistants.list()
696
- candidate_assistants = []
697
- for assistant in assistants.data:
698
- if assistant.name == name:
699
- candidate_assistants.append(assistant)
700
- return candidate_assistants
701
-
702
-
703
- def detect_gpt_assistant_api_version() -> str:
704
- """Detect the openai assistant API version"""
705
- oai_version = importlib.metadata.version("openai")
706
- if parse(oai_version) < parse("1.21"):
707
- return "v1"
708
- else:
709
- return "v2"
710
-
711
-
712
- def create_gpt_vector_store(client: OpenAI, name: str, fild_ids: List[str]) -> Any:
713
- """Create a openai vector store for gpt assistant"""
714
-
715
- try:
716
- vector_store = client.beta.vector_stores.create(name=name)
717
- except Exception as e:
718
- raise AttributeError(f"Failed to create vector store, please install the latest OpenAI python package: {e}")
719
-
720
- # poll the status of the file batch for completion.
721
- batch = client.beta.vector_stores.file_batches.create_and_poll(vector_store_id=vector_store.id, file_ids=fild_ids)
722
-
723
- if batch.status == "in_progress":
724
- time.sleep(1)
725
- logging.debug(f"file batch status: {batch.file_counts}")
726
- batch = client.beta.vector_stores.file_batches.poll(vector_store_id=vector_store.id, batch_id=batch.id)
727
-
728
- if batch.status == "completed":
729
- return vector_store
730
-
731
- raise ValueError(f"Failed to upload files to vector store {vector_store.id}:{batch.status}")
732
-
733
-
734
- def create_gpt_assistant(
735
- client: OpenAI, name: str, instructions: str, model: str, assistant_config: Dict[str, Any]
736
- ) -> Assistant:
737
- """Create a openai gpt assistant"""
738
-
739
- assistant_create_kwargs = {}
740
- gpt_assistant_api_version = detect_gpt_assistant_api_version()
741
- tools = assistant_config.get("tools", [])
742
-
743
- if gpt_assistant_api_version == "v2":
744
- tool_resources = assistant_config.get("tool_resources", {})
745
- file_ids = assistant_config.get("file_ids")
746
- if tool_resources.get("file_search") is not None and file_ids is not None:
747
- raise ValueError(
748
- "Cannot specify both `tool_resources['file_search']` tool and `file_ids` in the assistant config."
749
- )
750
-
751
- # Designed for backwards compatibility for the V1 API
752
- # Instead of V1 AssistantFile, files are attached to Assistants using the tool_resources object.
753
- for tool in tools:
754
- if tool["type"] == "retrieval":
755
- tool["type"] = "file_search"
756
- if file_ids is not None:
757
- # create a vector store for the file search tool
758
- vs = create_gpt_vector_store(client, f"{name}-vectorestore", file_ids)
759
- tool_resources["file_search"] = {
760
- "vector_store_ids": [vs.id],
761
- }
762
- elif tool["type"] == "code_interpreter" and file_ids is not None:
763
- tool_resources["code_interpreter"] = {
764
- "file_ids": file_ids,
765
- }
766
-
767
- assistant_create_kwargs["tools"] = tools
768
- if len(tool_resources) > 0:
769
- assistant_create_kwargs["tool_resources"] = tool_resources
770
- else:
771
- # not support forwards compatibility
772
- if "tool_resources" in assistant_config:
773
- raise ValueError("`tool_resources` argument are not supported in the openai assistant V1 API.")
774
- if any(tool["type"] == "file_search" for tool in tools):
775
- raise ValueError(
776
- "`file_search` tool are not supported in the openai assistant V1 API, please use `retrieval`."
777
- )
778
- assistant_create_kwargs["tools"] = tools
779
- assistant_create_kwargs["file_ids"] = assistant_config.get("file_ids", [])
780
-
781
- logging.info(f"Creating assistant with config: {assistant_create_kwargs}")
782
- return client.beta.assistants.create(name=name, instructions=instructions, model=model, **assistant_create_kwargs)
783
-
784
-
785
- def update_gpt_assistant(client: OpenAI, assistant_id: str, assistant_config: Dict[str, Any]) -> Assistant:
786
- """Update openai gpt assistant"""
787
-
788
- gpt_assistant_api_version = detect_gpt_assistant_api_version()
789
- assistant_update_kwargs = {}
790
-
791
- if assistant_config.get("tools") is not None:
792
- assistant_update_kwargs["tools"] = assistant_config["tools"]
793
-
794
- if assistant_config.get("instructions") is not None:
795
- assistant_update_kwargs["instructions"] = assistant_config["instructions"]
796
-
797
- if gpt_assistant_api_version == "v2":
798
- if assistant_config.get("tool_resources") is not None:
799
- assistant_update_kwargs["tool_resources"] = assistant_config["tool_resources"]
800
- else:
801
- if assistant_config.get("file_ids") is not None:
802
- assistant_update_kwargs["file_ids"] = assistant_config["file_ids"]
803
-
804
- return client.beta.assistants.update(assistant_id=assistant_id, **assistant_update_kwargs)
805
-
806
-
807
- def _satisfies(config_value: Any, acceptable_values: Any) -> bool:
808
- if isinstance(config_value, list):
809
- return bool(set(config_value) & set(acceptable_values)) # Non-empty intersection
810
- else:
811
- return config_value in acceptable_values