beswarm 0.2.81__py3-none-any.whl → 0.2.83__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.
@@ -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
+ """