aient 1.1.91__tar.gz → 1.1.92__tar.gz

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.
Files changed (58) hide show
  1. {aient-1.1.91 → aient-1.1.92}/PKG-INFO +1 -1
  2. aient-1.1.92/aient/architext/architext/core.py +436 -0
  3. aient-1.1.92/aient/architext/test/openai_client.py +146 -0
  4. aient-1.1.92/aient/architext/test/test.py +927 -0
  5. aient-1.1.92/aient/architext/test/test_save_load.py +93 -0
  6. {aient-1.1.91 → aient-1.1.92}/aient/models/chatgpt.py +31 -104
  7. {aient-1.1.91 → aient-1.1.92}/aient.egg-info/PKG-INFO +1 -1
  8. {aient-1.1.91 → aient-1.1.92}/aient.egg-info/SOURCES.txt +3 -1
  9. {aient-1.1.91 → aient-1.1.92}/pyproject.toml +1 -1
  10. aient-1.1.91/aient/architext/architext/core.py +0 -237
  11. aient-1.1.91/aient/architext/test.py +0 -226
  12. {aient-1.1.91 → aient-1.1.92}/LICENSE +0 -0
  13. {aient-1.1.91 → aient-1.1.92}/README.md +0 -0
  14. {aient-1.1.91 → aient-1.1.92}/aient/__init__.py +0 -0
  15. {aient-1.1.91 → aient-1.1.92}/aient/architext/architext/__init__.py +0 -0
  16. {aient-1.1.91 → aient-1.1.92}/aient/core/__init__.py +0 -0
  17. {aient-1.1.91 → aient-1.1.92}/aient/core/log_config.py +0 -0
  18. {aient-1.1.91 → aient-1.1.92}/aient/core/models.py +0 -0
  19. {aient-1.1.91 → aient-1.1.92}/aient/core/request.py +0 -0
  20. {aient-1.1.91 → aient-1.1.92}/aient/core/response.py +0 -0
  21. {aient-1.1.91 → aient-1.1.92}/aient/core/test/test_base_api.py +0 -0
  22. {aient-1.1.91 → aient-1.1.92}/aient/core/test/test_geminimask.py +0 -0
  23. {aient-1.1.91 → aient-1.1.92}/aient/core/test/test_image.py +0 -0
  24. {aient-1.1.91 → aient-1.1.92}/aient/core/test/test_payload.py +0 -0
  25. {aient-1.1.91 → aient-1.1.92}/aient/core/utils.py +0 -0
  26. {aient-1.1.91 → aient-1.1.92}/aient/models/__init__.py +0 -0
  27. {aient-1.1.91 → aient-1.1.92}/aient/models/audio.py +0 -0
  28. {aient-1.1.91 → aient-1.1.92}/aient/models/base.py +0 -0
  29. {aient-1.1.91 → aient-1.1.92}/aient/plugins/__init__.py +0 -0
  30. {aient-1.1.91 → aient-1.1.92}/aient/plugins/arXiv.py +0 -0
  31. {aient-1.1.91 → aient-1.1.92}/aient/plugins/config.py +0 -0
  32. {aient-1.1.91 → aient-1.1.92}/aient/plugins/excute_command.py +0 -0
  33. {aient-1.1.91 → aient-1.1.92}/aient/plugins/get_time.py +0 -0
  34. {aient-1.1.91 → aient-1.1.92}/aient/plugins/image.py +0 -0
  35. {aient-1.1.91 → aient-1.1.92}/aient/plugins/list_directory.py +0 -0
  36. {aient-1.1.91 → aient-1.1.92}/aient/plugins/read_file.py +0 -0
  37. {aient-1.1.91 → aient-1.1.92}/aient/plugins/read_image.py +0 -0
  38. {aient-1.1.91 → aient-1.1.92}/aient/plugins/readonly.py +0 -0
  39. {aient-1.1.91 → aient-1.1.92}/aient/plugins/registry.py +0 -0
  40. {aient-1.1.91 → aient-1.1.92}/aient/plugins/run_python.py +0 -0
  41. {aient-1.1.91 → aient-1.1.92}/aient/plugins/websearch.py +0 -0
  42. {aient-1.1.91 → aient-1.1.92}/aient/plugins/write_file.py +0 -0
  43. {aient-1.1.91 → aient-1.1.92}/aient/utils/__init__.py +0 -0
  44. {aient-1.1.91 → aient-1.1.92}/aient/utils/prompt.py +0 -0
  45. {aient-1.1.91 → aient-1.1.92}/aient/utils/scripts.py +0 -0
  46. {aient-1.1.91 → aient-1.1.92}/aient.egg-info/dependency_links.txt +0 -0
  47. {aient-1.1.91 → aient-1.1.92}/aient.egg-info/requires.txt +0 -0
  48. {aient-1.1.91 → aient-1.1.92}/aient.egg-info/top_level.txt +0 -0
  49. {aient-1.1.91 → aient-1.1.92}/setup.cfg +0 -0
  50. {aient-1.1.91 → aient-1.1.92}/test/test_Web_crawler.py +0 -0
  51. {aient-1.1.91 → aient-1.1.92}/test/test_ddg_search.py +0 -0
  52. {aient-1.1.91 → aient-1.1.92}/test/test_google_search.py +0 -0
  53. {aient-1.1.91 → aient-1.1.92}/test/test_ollama.py +0 -0
  54. {aient-1.1.91 → aient-1.1.92}/test/test_plugin.py +0 -0
  55. {aient-1.1.91 → aient-1.1.92}/test/test_search.py +0 -0
  56. {aient-1.1.91 → aient-1.1.92}/test/test_url.py +0 -0
  57. {aient-1.1.91 → aient-1.1.92}/test/test_whisper.py +0 -0
  58. {aient-1.1.91 → aient-1.1.92}/test/test_yjh.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aient
3
- Version: 1.1.91
3
+ Version: 1.1.92
4
4
  Summary: Aient: The Awakening of Agent.
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -0,0 +1,436 @@
1
+ import pickle
2
+ import base64
3
+ import asyncio
4
+ import logging
5
+ import hashlib
6
+ import mimetypes
7
+ from dataclasses import dataclass
8
+ from abc import ABC, abstractmethod
9
+ from typing import List, Dict, Any, Optional, Union
10
+
11
+ # 1. 核心数据结构: ContentBlock
12
+ @dataclass
13
+ class ContentBlock:
14
+ name: str
15
+ content: str
16
+
17
+ # 2. 上下文提供者 (带缓存)
18
+ class ContextProvider(ABC):
19
+ def __init__(self, name: str):
20
+ self.name = name; self._cached_content: Optional[str] = None; self._is_stale: bool = True
21
+ def mark_stale(self): self._is_stale = True
22
+ async def refresh(self):
23
+ if self._is_stale:
24
+ self._cached_content = await self.render()
25
+ self._is_stale = False
26
+ @abstractmethod
27
+ async def render(self) -> Optional[str]: raise NotImplementedError
28
+ @abstractmethod
29
+ def update(self, *args, **kwargs): raise NotImplementedError
30
+ def get_content_block(self) -> Optional[ContentBlock]:
31
+ if self._cached_content is not None: return ContentBlock(self.name, self._cached_content)
32
+ return None
33
+
34
+ class Texts(ContextProvider):
35
+ def __init__(self, text: str, name: Optional[str] = None):
36
+ self._text = text
37
+ if name is None:
38
+ h = hashlib.sha1(self._text.encode()).hexdigest()
39
+ _name = f"text_{h[:8]}"
40
+ else:
41
+ _name = name
42
+ super().__init__(_name)
43
+
44
+ def update(self, text: str):
45
+ self._text = text
46
+ self.mark_stale()
47
+
48
+ async def render(self) -> str: return self._text
49
+
50
+ class Tools(ContextProvider):
51
+ def __init__(self, tools_json: List[Dict]): super().__init__("tools"); self._tools_json = tools_json
52
+ def update(self, tools_json: List[Dict]):
53
+ self._tools_json = tools_json
54
+ self.mark_stale()
55
+ async def render(self) -> str: return f"<tools>{str(self._tools_json)}</tools>"
56
+
57
+ class Files(ContextProvider):
58
+ def __init__(self, *paths: Union[str, List[str]]):
59
+ super().__init__("files")
60
+ self._files: Dict[str, str] = {}
61
+
62
+ file_paths: List[str] = []
63
+ if paths:
64
+ # Handle the case where the first argument is a list of paths, e.g., Files(['a', 'b'])
65
+ if len(paths) == 1 and isinstance(paths[0], list):
66
+ file_paths.extend(paths[0])
67
+ # Handle the case where arguments are individual string paths, e.g., Files('a', 'b')
68
+ else:
69
+ file_paths.extend(paths)
70
+
71
+ if file_paths:
72
+ for path in file_paths:
73
+ try:
74
+ with open(path, 'r', encoding='utf-8') as f:
75
+ self._files[path] = f.read()
76
+ except FileNotFoundError:
77
+ logging.warning(f"File not found during initialization: {path}. Skipping.")
78
+ except Exception as e:
79
+ logging.error(f"Error reading file {path} during initialization: {e}")
80
+
81
+ async def refresh(self):
82
+ """
83
+ Overrides the default refresh behavior. It synchronizes the content of
84
+ all tracked files with the file system. If a file is not found, its
85
+ content is updated to reflect the error.
86
+ """
87
+ is_changed = False
88
+ for path in list(self._files.keys()):
89
+ try:
90
+ with open(path, 'r', encoding='utf-8') as f:
91
+ new_content = f.read()
92
+ if self._files.get(path) != new_content:
93
+ self._files[path] = new_content
94
+ is_changed = True
95
+ except FileNotFoundError:
96
+ error_msg = f"[Error: File not found at path '{path}']"
97
+ if self._files.get(path) != error_msg:
98
+ self._files[path] = error_msg
99
+ is_changed = True
100
+ except Exception as e:
101
+ error_msg = f"[Error: Could not read file at path '{path}': {e}]"
102
+ if self._files.get(path) != error_msg:
103
+ self._files[path] = error_msg
104
+ is_changed = True
105
+
106
+ if is_changed:
107
+ self.mark_stale()
108
+
109
+ await super().refresh()
110
+
111
+ def update(self, path: str, content: Optional[str] = None):
112
+ """
113
+ Updates a single file. If content is provided, it updates the file in
114
+ memory. If content is None, it reads the file from disk.
115
+ """
116
+ if content is not None:
117
+ self._files[path] = content
118
+ else:
119
+ try:
120
+ with open(path, 'r', encoding='utf-8') as f:
121
+ self._files[path] = f.read()
122
+ except FileNotFoundError:
123
+ logging.error(f"File not found for update: {path}.")
124
+ self._files[path] = f"[Error: File not found at path '{path}']"
125
+ except Exception as e:
126
+ logging.error(f"Error reading file for update {path}: {e}.")
127
+ self._files[path] = f"[Error: Could not read file at path '{path}': {e}]"
128
+ self.mark_stale()
129
+ async def render(self) -> str:
130
+ if not self._files: return None
131
+ return "<latest_file_content>" + "\n".join([f"<file><file_path>{p}</file_path><file_content>{c}</file_content></file>" for p, c in self._files.items()]) + "\n</latest_file_content>"
132
+
133
+ class Images(ContextProvider):
134
+ def __init__(self, url: str, name: Optional[str] = None):
135
+ super().__init__(name or url)
136
+ self.url = url
137
+ def update(self, url: str):
138
+ self.url = url
139
+ self.mark_stale()
140
+ async def render(self) -> Optional[str]:
141
+ if self.url.startswith("data:"):
142
+ return self.url
143
+ try:
144
+ with open(self.url, "rb") as image_file:
145
+ encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
146
+ mime_type, _ = mimetypes.guess_type(self.url)
147
+ if not mime_type: mime_type = "application/octet-stream" # Fallback
148
+ return f"data:{mime_type};base64,{encoded_string}"
149
+ except FileNotFoundError:
150
+ logging.warning(f"Image file not found: {self.url}. Skipping.")
151
+ return None # Or handle error appropriately
152
+
153
+ # 3. 消息类 (已合并 MessageContent)
154
+ class Message(ABC):
155
+ def __init__(self, role: str, *initial_items: Union[ContextProvider, str, list]):
156
+ self.role = role
157
+ processed_items = []
158
+ for item in initial_items:
159
+ if isinstance(item, str):
160
+ processed_items.append(Texts(text=item))
161
+ elif isinstance(item, Message):
162
+ processed_items.extend(item.providers())
163
+ elif isinstance(item, ContextProvider):
164
+ processed_items.append(item)
165
+ elif isinstance(item, list):
166
+ for sub_item in item:
167
+ if not isinstance(sub_item, dict) or 'type' not in sub_item:
168
+ raise ValueError("List items must be dicts with a 'type' key.")
169
+
170
+ item_type = sub_item['type']
171
+ if item_type == 'text':
172
+ processed_items.append(Texts(text=sub_item.get('text', '')))
173
+ elif item_type == 'image_url':
174
+ image_url = sub_item.get('image_url', {}).get('url')
175
+ if image_url:
176
+ processed_items.append(Images(url=image_url))
177
+ else:
178
+ raise ValueError(f"Unsupported item type in list: {item_type}")
179
+ else:
180
+ raise TypeError(f"Unsupported item type: {type(item)}. Must be str, ContextProvider, or list.")
181
+ self._items: List[ContextProvider] = processed_items
182
+ self._parent_messages: Optional['Messages'] = None
183
+
184
+ def _render_content(self) -> str:
185
+ blocks = [item.get_content_block() for item in self._items]
186
+ return "\n\n".join(b.content for b in blocks if b and b.content)
187
+
188
+ def pop(self, name: str) -> Optional[ContextProvider]:
189
+ popped_item = None
190
+ for i, item in enumerate(self._items):
191
+ if hasattr(item, 'name') and item.name == name:
192
+ popped_item = self._items.pop(i)
193
+ break
194
+ if popped_item and self._parent_messages:
195
+ self._parent_messages._notify_provider_removed(popped_item)
196
+ return popped_item
197
+
198
+ def insert(self, index: int, item: ContextProvider):
199
+ self._items.insert(index, item)
200
+ if self._parent_messages:
201
+ self._parent_messages._notify_provider_added(item, self)
202
+
203
+ def append(self, item: ContextProvider):
204
+ self._items.append(item)
205
+ if self._parent_messages:
206
+ self._parent_messages._notify_provider_added(item, self)
207
+
208
+ def providers(self) -> List[ContextProvider]: return self._items
209
+
210
+ def __add__(self, other):
211
+ if isinstance(other, str):
212
+ new_items = self._items + [Texts(text=other)]
213
+ return type(self)(*new_items)
214
+ if isinstance(other, Message):
215
+ new_items = self._items + other.providers()
216
+ return type(self)(*new_items)
217
+ return NotImplemented
218
+
219
+ def __radd__(self, other):
220
+ if isinstance(other, str):
221
+ new_items = [Texts(text=other)] + self._items
222
+ return type(self)(*new_items)
223
+ if isinstance(other, Message):
224
+ new_items = other.providers() + self._items
225
+ return type(self)(*new_items)
226
+ return NotImplemented
227
+
228
+ def __getitem__(self, key: str) -> Any:
229
+ """
230
+ 使得 Message 对象支持字典风格的访问 (e.g., message['content'])。
231
+ """
232
+ if key == 'role':
233
+ return self.role
234
+ elif key == 'content':
235
+ # 直接调用 to_dict 并提取 'content',确保逻辑一致
236
+ rendered_dict = self.to_dict()
237
+ return rendered_dict.get('content') if rendered_dict else None
238
+ # 对于 tool_calls 等特殊属性,也通过 to_dict 获取
239
+ elif hasattr(self, key):
240
+ rendered_dict = self.to_dict()
241
+ if rendered_dict and key in rendered_dict:
242
+ return rendered_dict[key]
243
+
244
+ # 如果在对象本身或其 to_dict() 中都找不到,则引发 KeyError
245
+ if hasattr(self, key):
246
+ return getattr(self, key)
247
+ raise KeyError(f"'{key}'")
248
+
249
+ def __repr__(self): return f"Message(role='{self.role}', items={[i.name for i in self._items]})"
250
+ def __bool__(self) -> bool:
251
+ return bool(self._items)
252
+ def get(self, key: str, default: Any = None) -> Any:
253
+ """提供类似字典的 .get() 方法来访问属性。"""
254
+ return getattr(self, key, default)
255
+ def to_dict(self) -> Optional[Dict[str, Any]]:
256
+ is_multimodal = any(isinstance(p, Images) for p in self._items)
257
+
258
+ if not is_multimodal:
259
+ rendered_content = self._render_content()
260
+ if not rendered_content: return None
261
+ return {"role": self.role, "content": rendered_content}
262
+ else:
263
+ content_list = []
264
+ for item in self._items:
265
+ block = item.get_content_block()
266
+ if not block or not block.content: continue
267
+ if isinstance(item, Images):
268
+ content_list.append({"type": "image_url", "image_url": {"url": block.content}})
269
+ else:
270
+ content_list.append({"type": "text", "text": block.content})
271
+ if not content_list: return None
272
+ return {"role": self.role, "content": content_list}
273
+
274
+ class SystemMessage(Message):
275
+ def __init__(self, *items): super().__init__("system", *items)
276
+ class UserMessage(Message):
277
+ def __init__(self, *items): super().__init__("user", *items)
278
+ class AssistantMessage(Message):
279
+ def __init__(self, *items): super().__init__("assistant", *items)
280
+
281
+ class RoleMessage:
282
+ """A factory class that creates a specific message type based on the role."""
283
+ def __new__(cls, role: str, *items):
284
+ if role == 'system':
285
+ return SystemMessage(*items)
286
+ elif role == 'user':
287
+ return UserMessage(*items)
288
+ elif role == 'assistant':
289
+ return AssistantMessage(*items)
290
+ else:
291
+ raise ValueError(f"Invalid role: {role}. Must be 'system', 'user', or 'assistant'.")
292
+
293
+ class ToolCalls(Message):
294
+ """Represents an assistant message that requests tool calls."""
295
+ def __init__(self, tool_calls: List[Any]):
296
+ super().__init__("assistant")
297
+ self.tool_calls = tool_calls
298
+
299
+ def to_dict(self) -> Dict[str, Any]:
300
+ # Duck-typing serialization for OpenAI's tool_call objects
301
+ serialized_calls = []
302
+ for tc in self.tool_calls:
303
+ try:
304
+ # Attempt to serialize based on openai-python > 1.0 tool_call structure
305
+ func = tc.function
306
+ serialized_calls.append({
307
+ "id": tc.id,
308
+ "type": tc.type,
309
+ "function": { "name": func.name, "arguments": func.arguments }
310
+ })
311
+ except AttributeError:
312
+ if isinstance(tc, dict):
313
+ serialized_calls.append(tc) # Assume it's already a serializable dict
314
+ else:
315
+ raise TypeError(f"Unsupported tool_call type: {type(tc)}. It should be an OpenAI tool_call object or a dict.")
316
+
317
+ return {
318
+ "role": self.role,
319
+ "tool_calls": serialized_calls,
320
+ "content": None
321
+ }
322
+
323
+ class ToolResults(Message):
324
+ """Represents a tool message with the result of a single tool call."""
325
+ def __init__(self, tool_call_id: str, content: str):
326
+ super().__init__("tool")
327
+ self.tool_call_id = tool_call_id
328
+ self.content = content
329
+
330
+ def to_dict(self) -> Dict[str, Any]:
331
+ return {
332
+ "role": self.role,
333
+ "tool_call_id": self.tool_call_id,
334
+ "content": self.content
335
+ }
336
+
337
+ # 4. 顶层容器: Messages
338
+ class Messages:
339
+ def __init__(self, *initial_messages: Message):
340
+ from typing import Tuple
341
+ self._messages: List[Message] = []
342
+ self._providers_index: Dict[str, Tuple[ContextProvider, Message]] = {}
343
+ if initial_messages:
344
+ for msg in initial_messages:
345
+ self.append(msg)
346
+
347
+ def _notify_provider_added(self, provider: ContextProvider, message: Message):
348
+ if provider.name not in self._providers_index:
349
+ self._providers_index[provider.name] = (provider, message)
350
+
351
+ def _notify_provider_removed(self, provider: ContextProvider):
352
+ if provider.name in self._providers_index:
353
+ del self._providers_index[provider.name]
354
+
355
+ def provider(self, name: str) -> Optional[ContextProvider]:
356
+ indexed = self._providers_index.get(name)
357
+ return indexed[0] if indexed else None
358
+
359
+ def pop(self, key: Optional[Union[str, int]] = None) -> Union[Optional[ContextProvider], Optional[Message]]:
360
+ # If no key is provided, pop the last message.
361
+ if key is None:
362
+ key = len(self._messages) - 1
363
+
364
+ if isinstance(key, str):
365
+ indexed = self._providers_index.get(key)
366
+ if not indexed:
367
+ return None
368
+ _provider, parent_message = indexed
369
+ return parent_message.pop(key)
370
+ elif isinstance(key, int):
371
+ try:
372
+ if key < 0: # Handle negative indices like -1
373
+ key += len(self._messages)
374
+ if not (0 <= key < len(self._messages)):
375
+ return None
376
+ popped_message = self._messages.pop(key)
377
+ popped_message._parent_messages = None
378
+ for provider in popped_message.providers():
379
+ self._notify_provider_removed(provider)
380
+ return popped_message
381
+ except IndexError:
382
+ return None
383
+
384
+ return None
385
+
386
+ async def refresh(self):
387
+ tasks = [provider.refresh() for provider, _ in self._providers_index.values()]
388
+ await asyncio.gather(*tasks)
389
+
390
+ def render(self) -> List[Dict[str, Any]]:
391
+ results = [msg.to_dict() for msg in self._messages]
392
+ return [res for res in results if res]
393
+
394
+ async def render_latest(self) -> List[Dict[str, Any]]:
395
+ await self.refresh()
396
+ return self.render()
397
+
398
+ def append(self, message: Message):
399
+ if self._messages and self._messages[-1].role == message.role:
400
+ last_message = self._messages[-1]
401
+ for provider in message.providers():
402
+ last_message.append(provider)
403
+ else:
404
+ message._parent_messages = self
405
+ self._messages.append(message)
406
+ for p in message.providers():
407
+ self._notify_provider_added(p, message)
408
+
409
+ def save(self, file_path: str):
410
+ """
411
+ Saves the entire Messages object to a file using pickle.
412
+ Warning: Deserializing data with pickle from an untrusted source is insecure.
413
+ """
414
+ with open(file_path, 'wb') as f:
415
+ pickle.dump(self, f)
416
+
417
+ @classmethod
418
+ def load(cls, file_path: str) -> Optional['Messages']:
419
+ """
420
+ Loads a Messages object from a file using pickle.
421
+ Returns the loaded object, or None if the file is not found or an error occurs.
422
+ Warning: Only load files from a trusted source.
423
+ """
424
+ try:
425
+ with open(file_path, 'rb') as f:
426
+ return pickle.load(f)
427
+ except FileNotFoundError:
428
+ logging.warning(f"File not found at {file_path}, returning empty Messages.")
429
+ return cls()
430
+ except (pickle.UnpicklingError, EOFError) as e:
431
+ logging.error(f"Could not deserialize file {file_path}: {e}")
432
+ return cls()
433
+
434
+ def __getitem__(self, index: int) -> Message: return self._messages[index]
435
+ def __len__(self) -> int: return len(self._messages)
436
+ def __iter__(self): return iter(self._messages)
@@ -0,0 +1,146 @@
1
+ import os
2
+ import json
3
+ import asyncio
4
+ from openai import AsyncOpenAI
5
+
6
+ # 从我们设计的 architext 库中导入消息类
7
+ from architext.core import (
8
+ Messages,
9
+ SystemMessage,
10
+ UserMessage,
11
+ AssistantMessage,
12
+ ToolCalls,
13
+ ToolResults,
14
+ Texts,
15
+ )
16
+
17
+ def _add_tool(a: int, b: int) -> int:
18
+ """(工具函数) 计算两个整数的和。"""
19
+ print(f"Executing tool: add(a={a}, b={b})")
20
+ return a + b
21
+
22
+ async def main():
23
+ """
24
+ 一个简化的、函数式的流程,用于处理单个包含工具调用的用户查询。
25
+ """
26
+ print("Starting simplified Tool Use demonstration...")
27
+
28
+ # --- 1. 初始化 ---
29
+ # 确保环境变量已设置
30
+ if not os.getenv("API_KEY"):
31
+ print("\nERROR: API_KEY environment variable not set.")
32
+ return
33
+
34
+ client = AsyncOpenAI(base_url=os.getenv("BASE_URL"), api_key=os.getenv("API_KEY"))
35
+ model = os.getenv("MODEL", "gpt-4o-mini")
36
+
37
+ # 定义工具
38
+ tool_executors = { "add": _add_tool }
39
+ tools_definition = [{
40
+ "type": "function", "function": {
41
+ "name": "add", "description": "Calculate the sum of two integers.",
42
+ "parameters": {
43
+ "type": "object",
44
+ "properties": {
45
+ "a": {"type": "integer", "description": "The first integer."},
46
+ "b": {"type": "integer", "description": "The second integer."},
47
+ }, "required": ["a", "b"],
48
+ },
49
+ },
50
+ }]
51
+
52
+ # --- 2. 处理查询 ---
53
+ # 初始消息
54
+ messages = Messages(
55
+ SystemMessage(Texts("system_prompt", "You are a helpful assistant. You must use the provided tools to answer questions.")),
56
+ UserMessage(Texts("user_question", "What is the sum of 5 and 10?"))
57
+ )
58
+
59
+ # 第一次 API 调用
60
+ print("\n--- [Step 1] Calling OpenAI with tools...")
61
+ response = await client.chat.completions.create(
62
+ model=model,
63
+ messages=await messages.render_latest(),
64
+ tools=tools_definition,
65
+ tool_choice="auto",
66
+ )
67
+ response_message = response.choices[0].message
68
+
69
+ # 检查是否需要工具调用
70
+ if not response_message.tool_calls:
71
+ final_content = response_message.content or ""
72
+ messages.append(AssistantMessage(Texts("assistant_response", final_content)))
73
+ else:
74
+ # 执行工具调用
75
+ print("--- [Step 2] Assistant requested tool calls. Executing them...")
76
+ messages.append(ToolCalls(response_message.tool_calls))
77
+
78
+ for tool_call in response_message.tool_calls:
79
+ if tool_call.function is None: continue
80
+
81
+ executor = tool_executors.get(tool_call.function.name)
82
+ if not executor: continue
83
+
84
+ try:
85
+ args = json.loads(tool_call.function.arguments)
86
+ result = executor(**args)
87
+ messages.append(ToolResults(tool_call_id=tool_call.id, content=str(result)))
88
+ print(f" - Executed '{tool_call.function.name}'. Result: {result}")
89
+ except (json.JSONDecodeError, TypeError) as e:
90
+ print(f" - Error processing tool call '{tool_call.function.name}': {e}")
91
+
92
+ # 第二次 API 调用
93
+ print("--- [Step 3] Calling OpenAI with tool results for final answer...")
94
+ final_response = await client.chat.completions.create(
95
+ model=model,
96
+ messages=await messages.render_latest(),
97
+ )
98
+ final_content = final_response.choices[0].message.content or ""
99
+ messages.append(AssistantMessage(Texts("final_response", final_content)))
100
+
101
+ # --- 3. 显示结果 ---
102
+ print("\n--- Final request body sent to OpenAI: ---")
103
+ print(json.dumps(await messages.render_latest(), indent=2, ensure_ascii=False))
104
+
105
+ print("\n--- Final Assistant Answer ---")
106
+ print(final_content)
107
+ print("\nDemonstration finished.")
108
+
109
+ if __name__ == "__main__":
110
+ asyncio.run(main())
111
+
112
+ """
113
+ [
114
+ {
115
+ "role": "system",
116
+ "content": "You are a helpful assistant. You must use the provided tools to answer questions."
117
+ },
118
+ {
119
+ "role": "user",
120
+ "content": "What is the sum of 5 and 10?"
121
+ },
122
+ {
123
+ "role": "assistant",
124
+ "tool_calls": [
125
+ {
126
+ "id": "call_rddWXkDikIxllRgbPrR6XjtMVSBPv",
127
+ "type": "function",
128
+ "function": {
129
+ "name": "add",
130
+ "arguments": "{\"b\": 10, \"a\": 5}"
131
+ }
132
+ }
133
+ ],
134
+ "content": null
135
+ },
136
+ {
137
+ "role": "tool",
138
+ "tool_call_id": "call_rddWXkDikIxllRgbPrR6XjtMVSBPv",
139
+ "content": "15"
140
+ },
141
+ {
142
+ "role": "assistant",
143
+ "content": "The sum of 5 and 10 is 15."
144
+ }
145
+ ]
146
+ """