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,42 @@
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 datetime
8
+ import inspect
9
+ from typing import Any, Dict, List, Tuple, Union
10
+
11
+ __all__ = ("get_current_ts", "to_dict")
12
+
13
+
14
+ def get_current_ts() -> str:
15
+ return datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")
16
+
17
+
18
+ def to_dict(
19
+ obj: Union[int, float, str, bool, Dict[Any, Any], List[Any], Tuple[Any, ...], Any],
20
+ exclude: Tuple[str, ...] = (),
21
+ no_recursive: Tuple[Any, ...] = (),
22
+ ) -> Any:
23
+ if isinstance(obj, (int, float, str, bool)):
24
+ return obj
25
+ elif callable(obj):
26
+ return inspect.getsource(obj).strip()
27
+ elif isinstance(obj, dict):
28
+ return {
29
+ str(k): to_dict(str(v)) if isinstance(v, no_recursive) else to_dict(v, exclude, no_recursive)
30
+ for k, v in obj.items()
31
+ if k not in exclude
32
+ }
33
+ elif isinstance(obj, (list, tuple)):
34
+ return [to_dict(str(v)) if isinstance(v, no_recursive) else to_dict(v, exclude, no_recursive) for v in obj]
35
+ elif hasattr(obj, "__dict__"):
36
+ return {
37
+ str(k): to_dict(str(v)) if isinstance(v, no_recursive) else to_dict(v, exclude, no_recursive)
38
+ for k, v in vars(obj).items()
39
+ if k not in exclude
40
+ }
41
+ else:
42
+ return obj
@@ -0,0 +1,459 @@
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
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import os
12
+ import sqlite3
13
+ import threading
14
+ import uuid
15
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, TypeVar, Union
16
+
17
+ from openai import AzureOpenAI, OpenAI
18
+ from openai.types.chat import ChatCompletion
19
+
20
+ from autogen.logger.base_logger import BaseLogger
21
+ from autogen.logger.logger_utils import get_current_ts, to_dict
22
+
23
+ from .base_logger import LLMConfig
24
+
25
+ if TYPE_CHECKING:
26
+ from autogen import Agent, ConversableAgent, OpenAIWrapper
27
+ from autogen.oai.anthropic import AnthropicClient
28
+ from autogen.oai.bedrock import BedrockClient
29
+ from autogen.oai.cerebras import CerebrasClient
30
+ from autogen.oai.cohere import CohereClient
31
+ from autogen.oai.gemini import GeminiClient
32
+ from autogen.oai.groq import GroqClient
33
+ from autogen.oai.mistral import MistralAIClient
34
+ from autogen.oai.ollama import OllamaClient
35
+ from autogen.oai.together import TogetherClient
36
+
37
+ logger = logging.getLogger(__name__)
38
+ lock = threading.Lock()
39
+
40
+ __all__ = ("SqliteLogger",)
41
+
42
+ F = TypeVar("F", bound=Callable[..., Any])
43
+
44
+
45
+ def safe_serialize(obj: Any) -> str:
46
+ def default(o: Any) -> str:
47
+ if hasattr(o, "to_json"):
48
+ return str(o.to_json())
49
+ else:
50
+ return f"<<non-serializable: {type(o).__qualname__}>>"
51
+
52
+ return json.dumps(obj, default=default)
53
+
54
+
55
+ class SqliteLogger(BaseLogger):
56
+ schema_version = 1
57
+
58
+ def __init__(self, config: Dict[str, Any]):
59
+ self.config = config
60
+
61
+ try:
62
+ self.dbname = self.config.get("dbname", "logs.db")
63
+ self.con = sqlite3.connect(self.dbname, check_same_thread=False)
64
+ self.cur = self.con.cursor()
65
+ self.session_id = str(uuid.uuid4())
66
+ except sqlite3.Error as e:
67
+ logger.error(f"[SqliteLogger] Failed to connect to database {self.dbname}: {e}")
68
+
69
+ def start(self) -> str:
70
+ try:
71
+ query = """
72
+ CREATE TABLE IF NOT EXISTS chat_completions(
73
+ id INTEGER PRIMARY KEY,
74
+ invocation_id TEXT,
75
+ client_id INTEGER,
76
+ wrapper_id INTEGER,
77
+ session_id TEXT,
78
+ source_name TEXT,
79
+ request TEXT,
80
+ response TEXT,
81
+ is_cached INEGER,
82
+ cost REAL,
83
+ start_time DATETIME DEFAULT CURRENT_TIMESTAMP,
84
+ end_time DATETIME DEFAULT CURRENT_TIMESTAMP)
85
+ """
86
+ self._run_query(query=query)
87
+
88
+ query = """
89
+ CREATE TABLE IF NOT EXISTS agents (
90
+ id INTEGER PRIMARY KEY, -- Key assigned by the database
91
+ agent_id INTEGER, -- result of python id(agent)
92
+ wrapper_id INTEGER, -- result of python id(agent.client)
93
+ session_id TEXT,
94
+ name TEXT, -- agent.name
95
+ class TEXT, -- type or class name of agent
96
+ init_args TEXT, -- JSON serialization of constructor
97
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
98
+ UNIQUE(agent_id, session_id))
99
+ """
100
+ self._run_query(query=query)
101
+
102
+ query = """
103
+ CREATE TABLE IF NOT EXISTS oai_wrappers (
104
+ id INTEGER PRIMARY KEY, -- Key assigned by the database
105
+ wrapper_id INTEGER, -- result of python id(wrapper)
106
+ session_id TEXT,
107
+ init_args TEXT, -- JSON serialization of constructor
108
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
109
+ UNIQUE(wrapper_id, session_id))
110
+ """
111
+ self._run_query(query=query)
112
+
113
+ query = """
114
+ CREATE TABLE IF NOT EXISTS oai_clients (
115
+ id INTEGER PRIMARY KEY, -- Key assigned by the database
116
+ client_id INTEGER, -- result of python id(client)
117
+ wrapper_id INTEGER, -- result of python id(wrapper)
118
+ session_id TEXT,
119
+ class TEXT, -- type or class name of client
120
+ init_args TEXT, -- JSON serialization of constructor
121
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
122
+ UNIQUE(client_id, session_id))
123
+ """
124
+ self._run_query(query=query)
125
+
126
+ query = """
127
+ CREATE TABLE IF NOT EXISTS version (
128
+ id INTEGER PRIMARY KEY CHECK (id = 1), -- id of the logging database
129
+ version_number INTEGER NOT NULL -- version of the logging database
130
+ );
131
+ """
132
+ self._run_query(query=query)
133
+
134
+ query = """
135
+ CREATE TABLE IF NOT EXISTS events (
136
+ event_name TEXT,
137
+ source_id INTEGER,
138
+ source_name TEXT,
139
+ agent_module TEXT DEFAULT NULL,
140
+ agent_class_name TEXT DEFAULT NULL,
141
+ id INTEGER PRIMARY KEY,
142
+ json_state TEXT,
143
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
144
+ );
145
+ """
146
+ self._run_query(query=query)
147
+
148
+ query = """
149
+ CREATE TABLE IF NOT EXISTS function_calls (
150
+ source_id INTEGER,
151
+ source_name TEXT,
152
+ function_name TEXT,
153
+ args TEXT DEFAULT NULL,
154
+ returns TEXT DEFAULT NULL,
155
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
156
+ );
157
+ """
158
+ self._run_query(query=query)
159
+
160
+ current_verion = self._get_current_db_version()
161
+ if current_verion is None:
162
+ self._run_query(
163
+ query="INSERT INTO version (id, version_number) VALUES (1, ?);", args=(SqliteLogger.schema_version,)
164
+ )
165
+ self._apply_migration()
166
+
167
+ except sqlite3.Error as e:
168
+ logger.error(f"[SqliteLogger] start logging error: {e}")
169
+ finally:
170
+ return self.session_id
171
+
172
+ def _get_current_db_version(self) -> Union[None, int]:
173
+ self.cur.execute("SELECT version_number FROM version ORDER BY id DESC LIMIT 1")
174
+ result = self.cur.fetchone()
175
+ return result[0] if result is not None else None
176
+
177
+ # Example migration script name format: 002_update_agents_table.sql
178
+ def _apply_migration(self, migrations_dir: str = "./migrations") -> None:
179
+ current_version = self._get_current_db_version()
180
+ current_version = SqliteLogger.schema_version if current_version is None else current_version
181
+
182
+ if os.path.isdir(migrations_dir):
183
+ migrations = sorted(os.listdir(migrations_dir))
184
+ else:
185
+ logger.info("no migration scripts, skip...")
186
+ return
187
+
188
+ migrations_to_apply = [m for m in migrations if int(m.split("_")[0]) > current_version]
189
+
190
+ for script in migrations_to_apply:
191
+ with open(script, "r") as f:
192
+ migration_sql = f.read()
193
+ self._run_query_script(script=migration_sql)
194
+
195
+ latest_version = int(script.split("_")[0])
196
+ query = "UPDATE version SET version_number = ? WHERE id = 1"
197
+ args = (latest_version,)
198
+ self._run_query(query=query, args=args)
199
+
200
+ def _run_query(self, query: str, args: Tuple[Any, ...] = ()) -> None:
201
+ """
202
+ Executes a given SQL query.
203
+
204
+ Args:
205
+ query (str): The SQL query to execute.
206
+ args (Tuple): The arguments to pass to the SQL query.
207
+ """
208
+ try:
209
+ with lock:
210
+ self.cur.execute(query, args)
211
+ self.con.commit()
212
+ except Exception as e:
213
+ logger.error("[sqlite logger]Error running query with query %s and args %s: %s", query, args, e)
214
+
215
+ def _run_query_script(self, script: str) -> None:
216
+ """
217
+ Executes SQL script.
218
+
219
+ Args:
220
+ script (str): SQL script to execute.
221
+ """
222
+ try:
223
+ with lock:
224
+ self.cur.executescript(script)
225
+ self.con.commit()
226
+ except Exception as e:
227
+ logger.error("[sqlite logger]Error running query script %s: %s", script, e)
228
+
229
+ def log_chat_completion(
230
+ self,
231
+ invocation_id: uuid.UUID,
232
+ client_id: int,
233
+ wrapper_id: int,
234
+ source: Union[str, Agent],
235
+ request: Dict[str, Union[float, str, List[Dict[str, str]]]],
236
+ response: Union[str, ChatCompletion],
237
+ is_cached: int,
238
+ cost: float,
239
+ start_time: str,
240
+ ) -> None:
241
+ if self.con is None:
242
+ return
243
+
244
+ end_time = get_current_ts()
245
+
246
+ if response is None or isinstance(response, str):
247
+ response_messages = json.dumps({"response": response})
248
+ else:
249
+ response_messages = json.dumps(to_dict(response), indent=4)
250
+
251
+ source_name = None
252
+ if isinstance(source, str):
253
+ source_name = source
254
+ else:
255
+ source_name = source.name
256
+
257
+ query = """
258
+ INSERT INTO chat_completions (
259
+ invocation_id, client_id, wrapper_id, session_id, request, response, is_cached, cost, start_time, end_time, source_name
260
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
261
+ """
262
+ args = (
263
+ invocation_id,
264
+ client_id,
265
+ wrapper_id,
266
+ self.session_id,
267
+ json.dumps(request),
268
+ response_messages,
269
+ is_cached,
270
+ cost,
271
+ start_time,
272
+ end_time,
273
+ source_name,
274
+ )
275
+
276
+ self._run_query(query=query, args=args)
277
+
278
+ def log_new_agent(self, agent: ConversableAgent, init_args: Dict[str, Any]) -> None:
279
+ from autogen import Agent
280
+
281
+ if self.con is None:
282
+ return
283
+
284
+ args = to_dict(
285
+ init_args,
286
+ exclude=(
287
+ "self",
288
+ "__class__",
289
+ "api_key",
290
+ "organization",
291
+ "base_url",
292
+ "azure_endpoint",
293
+ "azure_ad_token",
294
+ "azure_ad_token_provider",
295
+ ),
296
+ no_recursive=(Agent,),
297
+ )
298
+
299
+ # We do an upsert since both the superclass and subclass may call this method (in that order)
300
+ query = """
301
+ INSERT INTO agents (agent_id, wrapper_id, session_id, name, class, init_args, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)
302
+ ON CONFLICT (agent_id, session_id) DO UPDATE SET
303
+ wrapper_id = excluded.wrapper_id,
304
+ name = excluded.name,
305
+ class = excluded.class,
306
+ init_args = excluded.init_args,
307
+ timestamp = excluded.timestamp
308
+ """
309
+ args = (
310
+ id(agent),
311
+ agent.client.wrapper_id if hasattr(agent, "client") and agent.client is not None else "",
312
+ self.session_id,
313
+ agent.name if hasattr(agent, "name") and agent.name is not None else "",
314
+ type(agent).__name__,
315
+ json.dumps(args),
316
+ get_current_ts(),
317
+ )
318
+ self._run_query(query=query, args=args)
319
+
320
+ def log_event(self, source: Union[str, Agent], name: str, **kwargs: Dict[str, Any]) -> None:
321
+ from autogen import Agent
322
+
323
+ if self.con is None:
324
+ return
325
+
326
+ json_args = json.dumps(kwargs, default=lambda o: f"<<non-serializable: {type(o).__qualname__}>>")
327
+
328
+ if isinstance(source, Agent):
329
+ query = """
330
+ INSERT INTO events (source_id, source_name, event_name, agent_module, agent_class_name, json_state, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)
331
+ """
332
+ args = (
333
+ id(source),
334
+ source.name if hasattr(source, "name") else source,
335
+ name,
336
+ source.__module__,
337
+ source.__class__.__name__,
338
+ json_args,
339
+ get_current_ts(),
340
+ )
341
+ self._run_query(query=query, args=args)
342
+ else:
343
+ query = """
344
+ INSERT INTO events (source_id, source_name, event_name, json_state, timestamp) VALUES (?, ?, ?, ?, ?)
345
+ """
346
+ args_str_based = (
347
+ id(source),
348
+ source.name if hasattr(source, "name") else source,
349
+ name,
350
+ json_args,
351
+ get_current_ts(),
352
+ )
353
+ self._run_query(query=query, args=args_str_based)
354
+
355
+ def log_new_wrapper(self, wrapper: OpenAIWrapper, init_args: Dict[str, Union[LLMConfig, List[LLMConfig]]]) -> None:
356
+ if self.con is None:
357
+ return
358
+
359
+ args = to_dict(
360
+ init_args,
361
+ exclude=(
362
+ "self",
363
+ "__class__",
364
+ "api_key",
365
+ "organization",
366
+ "base_url",
367
+ "azure_endpoint",
368
+ "azure_ad_token",
369
+ "azure_ad_token_provider",
370
+ ),
371
+ )
372
+
373
+ query = """
374
+ INSERT INTO oai_wrappers (wrapper_id, session_id, init_args, timestamp) VALUES (?, ?, ?, ?)
375
+ ON CONFLICT (wrapper_id, session_id) DO NOTHING;
376
+ """
377
+ args = (
378
+ id(wrapper),
379
+ self.session_id,
380
+ json.dumps(args),
381
+ get_current_ts(),
382
+ )
383
+ self._run_query(query=query, args=args)
384
+
385
+ def log_function_use(self, source: Union[str, Agent], function: F, args: Dict[str, Any], returns: Any) -> None:
386
+
387
+ if self.con is None:
388
+ return
389
+
390
+ query = """
391
+ INSERT INTO function_calls (source_id, source_name, function_name, args, returns, timestamp) VALUES (?, ?, ?, ?, ?, ?)
392
+ """
393
+ query_args: Tuple[Any, ...] = (
394
+ id(source),
395
+ source.name if hasattr(source, "name") else source,
396
+ function.__name__,
397
+ safe_serialize(args),
398
+ safe_serialize(returns),
399
+ get_current_ts(),
400
+ )
401
+ self._run_query(query=query, args=query_args)
402
+
403
+ def log_new_client(
404
+ self,
405
+ client: Union[
406
+ AzureOpenAI,
407
+ OpenAI,
408
+ CerebrasClient,
409
+ GeminiClient,
410
+ AnthropicClient,
411
+ MistralAIClient,
412
+ TogetherClient,
413
+ GroqClient,
414
+ CohereClient,
415
+ OllamaClient,
416
+ BedrockClient,
417
+ ],
418
+ wrapper: OpenAIWrapper,
419
+ init_args: Dict[str, Any],
420
+ ) -> None:
421
+ if self.con is None:
422
+ return
423
+
424
+ args = to_dict(
425
+ init_args,
426
+ exclude=(
427
+ "self",
428
+ "__class__",
429
+ "api_key",
430
+ "organization",
431
+ "base_url",
432
+ "azure_endpoint",
433
+ "azure_ad_token",
434
+ "azure_ad_token_provider",
435
+ ),
436
+ )
437
+
438
+ query = """
439
+ INSERT INTO oai_clients (client_id, wrapper_id, session_id, class, init_args, timestamp) VALUES (?, ?, ?, ?, ?, ?)
440
+ ON CONFLICT (client_id, session_id) DO NOTHING;
441
+ """
442
+ args = (
443
+ id(client),
444
+ id(wrapper),
445
+ self.session_id,
446
+ type(client).__name__,
447
+ json.dumps(args),
448
+ get_current_ts(),
449
+ )
450
+ self._run_query(query=query, args=args)
451
+
452
+ def stop(self) -> None:
453
+ if self.con:
454
+ self.con.close()
455
+
456
+ def get_connection(self) -> Union[None, sqlite3.Connection]:
457
+ if self.con:
458
+ return self.con
459
+ return None