-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathapis.py
193 lines (172 loc) · 6.21 KB
/
apis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
from pydantic import BaseModel
from typing import List, Dict, Any, Union, Optional
from cerebrum.utils.communication import Query, send_request, Response, aios_kernel_url
class ToolQuery(Query):
"""
Query class for tool operations.
This class represents a request to execute one or more tool operations.
Tools can be anything from simple calculators to complex data processors.
Attributes:
query_class: Identifier for tool queries, always set to "tool"
tool_calls: List of tool call specifications, each containing:
- name: Tool identifier (e.g., "calculator/basic", "text_processor/summarize")
- parameters: Dictionary of parameters specific to the tool
Examples:
```python
# Calculator tool example
query = ToolQuery(
tool_calls=[{
"name": "calculator/basic",
"parameters": {
"operation": "add",
"numbers": [1, 2, 3]
}
}]
)
# Text processing tool example
query = ToolQuery(
tool_calls=[{
"name": "text/summarizer",
"parameters": {
"text": "Long text to summarize...",
"max_length": 100
}
}]
)
```
"""
query_class: str = "tool"
tool_calls: List[Dict[str, Union[str, Any]]]
class Config:
arbitrary_types_allowed = True
class ToolResponse(Response):
"""
Response class for tool operations.
This class represents the result of executing one or more tool operations.
It includes both successful results and error information if the operation failed.
Attributes:
response_class: Identifier for tool responses, always set to "tool"
response_message: Tool execution result, can be string or structured data
finished: Whether execution completed successfully
error: Error message if any
status_code: HTTP status code indicating the result status
Examples:
```python
# Successful calculator response
response = ToolResponse(
response_message="6", # Result of 1 + 2 + 3
finished=True,
status_code=200
)
# Successful text processing response
response = ToolResponse(
response_message={
"summary": "Shortened text...",
"length": 95,
"compression_ratio": 0.75
},
finished=True,
status_code=200
)
# Error response
response = ToolResponse(
response_message="Invalid operation requested",
finished=True,
error="UnsupportedOperationError",
status_code=400
)
# Partial success with multiple tools
response = ToolResponse(
response_message=[
{"status": "success", "data": "..."},
{"status": "error", "message": "Processing failed"}
],
finished=True,
status_code=207 # Multi-Status
)
```
"""
response_class: str = "tool"
response_message: Optional[str] = None
finished: bool = False
error: Optional[str] = None
status_code: int = 200
def call_tool(
agent_name: str,
tool_calls: List[Dict[str, Any]],
base_url: str = aios_kernel_url
) -> ToolResponse:
"""
Execute one or more tool calls.
This function allows agents to use various tools by specifying the tool name
and parameters. Multiple tools can be called in sequence, and their results
can be combined or processed further.
Args:
agent_name: Name of the agent making the tool call
tool_calls: List of tool call specifications, each containing:
- name: Tool identifier
- parameters: Tool-specific parameters
base_url: API base URL for the tool service
Returns:
ToolResponse containing the results or error information
Examples:
```python
# Basic calculator example
response = call_tool(
"agent1",
[{
"name": "calculator/basic",
"parameters": {
"operation": "multiply",
"numbers": [3, 4]
}
}]
)
if response.finished:
print(f"Result: {response.response_message}") # "12"
# Text analysis example
response = call_tool(
"agent1",
[{
"name": "text/analyzer",
"parameters": {
"text": "Sample text for analysis",
"metrics": ["sentiment", "keywords"]
}
}]
)
if response.finished:
analysis = response.response_message
print(f"Sentiment: {analysis['sentiment']}")
print(f"Keywords: {', '.join(analysis['keywords'])}")
# Multi-tool workflow example
response = call_tool(
"agent1",
[
{
"name": "data/fetch",
"parameters": {"source": "database", "query": "SELECT * FROM users"}
},
{
"name": "data/transform",
"parameters": {"format": "csv", "fields": ["id", "name", "email"]}
},
{
"name": "file/save",
"parameters": {"path": "output/users.csv"}
}
]
)
if response.finished:
print("Data processing workflow completed successfully")
else:
print(f"Workflow failed: {response.error}")
```
Notes:
- Tools must be registered and available in the system
- Some tools may require specific permissions
- Complex workflows may take longer to execute
- Error handling should account for partial successes in multi-tool calls
"""
query = ToolQuery(tool_calls=tool_calls)
return send_request(agent_name, query, base_url)