-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathclient_tool_calling.py
More file actions
291 lines (247 loc) · 10 KB
/
client_tool_calling.py
File metadata and controls
291 lines (247 loc) · 10 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""Client example for testing tool calling with m serve.
This script demonstrates how to interact with an m serve server
that supports tool calling using the OpenAI-compatible API.
Usage:
1. Start the server:
uv run m serve docs/examples/m_serve/m_serve_example_tool_calling.py
2. Run this client:
uv run python docs/examples/m_serve/client_tool_calling.py
"""
import json
import requests
# Server configuration
BASE_URL = "http://localhost:8080"
ENDPOINT = f"{BASE_URL}/v1/chat/completions"
# Define tools in OpenAI format
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a given location",
"parameters": {
"RootModel": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature units",
},
},
"required": ["location"],
}
},
},
},
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Get the current stock price for a given ticker symbol",
"parameters": {
"RootModel": {
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL, GOOGL",
}
},
"required": ["symbol"],
}
},
},
},
]
def make_request(
messages: list[dict], tools: list[dict] | None = None, tool_name: str | None = None
) -> dict:
"""Make a request to the m serve API.
Args:
messages: List of message dictionaries
tools: Optional list of tool definitions
tool_name: Optional tool name to request explicitly
Returns:
Response dictionary from the API
"""
payload = {
"model": "gpt-3.5-turbo", # Model name (not used by m serve)
"messages": messages,
"temperature": 0.7,
}
if tools:
payload["tools"] = tools
if tool_name is not None:
# m serve forwards tool_choice to compatible backends, but the
# downstream provider/model may ignore it or treat it as a weak
# preference rather than a guarantee. Use an explicit function
# selection in this client so the example demonstrates the API
# contract even when the model would otherwise decline to call tools.
payload["tool_choice"] = {
"type": "function",
"function": {"name": tool_name},
}
else:
payload["tool_choice"] = "auto"
response = requests.post(ENDPOINT, json=payload, timeout=30)
if response.status_code >= 400:
try:
error_payload = response.json()
except ValueError:
error_payload = {"error": {"message": response.text}}
error_message = error_payload.get("error", {}).get("message", response.text)
raise requests.HTTPError(
f"{response.status_code} Server Error: {error_message}", response=response
)
return response.json()
def _run_local_tool(tool_name: str, args: dict) -> str:
"""Simulate local execution of the example tools."""
if tool_name == "get_weather":
units = args.get("units") or "celsius"
unit_suffix = "C" if units == "celsius" else "F"
return f"The weather in {args['location']} is sunny and 22°{unit_suffix}"
if tool_name == "get_stock_price":
mock_prices = {
"AAPL": "$175.43",
"GOOGL": "$142.87",
"MSFT": "$378.91",
"TSLA": "$242.15",
}
symbol = args["symbol"].upper()
return f"The current price of {symbol} is {mock_prices.get(symbol, '$100.00')}"
return "Tool result"
def main():
"""Run example tool calling interactions."""
print("=" * 60)
print("Tool Calling Example with m serve")
print("=" * 60)
# Example 1: Request that should trigger weather tool
print("\n1. Weather Query")
print("-" * 60)
messages = [{"role": "user", "content": "What's the weather like in Tokyo?"}]
print(f"User: {messages[0]['content']}")
response = make_request(messages, tools=tools, tool_name="get_weather")
choice = response["choices"][0]
print(f"\nFinish Reason: {choice['finish_reason']}")
if choice.get("message", {}).get("tool_calls"):
print("\nTool Calls:")
for tool_call in choice["message"]["tool_calls"]:
func = tool_call["function"]
args = json.loads(func["arguments"])
print(f" - {func['name']}({json.dumps(args)})")
elif choice.get("message", {}).get("content"):
print(f"Assistant: {choice['message']['content']}")
else:
print("Assistant returned no content and no tool calls.")
# Example 2: Request that should trigger stock price tool
print("\n\n2. Stock Price Query")
print("-" * 60)
messages = [{"role": "user", "content": "What's the current stock price of AAPL?"}]
print(f"User: {messages[0]['content']}")
response = make_request(messages, tools=tools, tool_name="get_stock_price")
choice = response["choices"][0]
print(f"\nFinish Reason: {choice['finish_reason']}")
if choice.get("message", {}).get("tool_calls"):
print("\nTool Calls:")
for tool_call in choice["message"]["tool_calls"]:
func = tool_call["function"]
args = json.loads(func["arguments"])
print(f" - {func['name']}({json.dumps(args)})")
elif choice.get("message", {}).get("content"):
print(f"Assistant: {choice['message']['content']}")
else:
print("Assistant returned no content and no tool calls.")
# Example 3: Request without tools (normal chat)
print("\n\n3. Normal Chat (No Tools)")
print("-" * 60)
messages = [{"role": "user", "content": "Hello! How are you?"}]
print(f"User: {messages[0]['content']}")
response = make_request(messages, tools=None)
choice = response["choices"][0]
print(f"\nFinish Reason: {choice['finish_reason']}")
print(f"Assistant: {choice['message']['content']}")
# Example 4: Multi-turn conversation with tool use
print("\n\n4. Multi-turn Conversation")
print("-" * 60)
messages = [{"role": "user", "content": "What's the weather in Paris?"}]
print(f"User: {messages[0]['content']}")
response = make_request(messages, tools=tools, tool_name="get_weather")
choice = response["choices"][0]
assistant_message = choice["message"]
if assistant_message.get("tool_calls"):
print("\nAssistant requested tool calls:")
# Add assistant message once before processing tool calls
messages.append(
{
"role": "assistant",
"content": assistant_message.get("content"),
"tool_calls": assistant_message["tool_calls"],
}
)
tool_results: list[str] = []
# Process each tool call and add tool responses
for tool_call in assistant_message["tool_calls"]:
func = tool_call["function"]
args = json.loads(func["arguments"])
print(f" - {func['name']}({json.dumps(args)})")
tool_result = _run_local_tool(func["name"], args)
tool_results.append(tool_result)
print(f" Result: {tool_result}")
# Add tool response to conversation
messages.append(
{
"role": "tool",
"tool_call_id": tool_call["id"],
"content": tool_result,
}
)
# Get final response after tool execution.
# Ask for a concise answer that explicitly uses the tool result so the
# example output includes the actual weather/price instead of only a
# conversational acknowledgement.
messages.append(
{
"role": "user",
"content": (
f"Original question: {messages[0]['content']}\n"
f"Tool result: {'; '.join(tool_results)}\n"
"Answer the original question directly using only that tool "
"result. Do not mention unrelated topics or other tools."
),
}
)
print("\nGetting final response after tool execution...")
response = make_request(messages, tools=None)
choice = response["choices"][0]
if choice.get("message", {}).get("content"):
print(f"Assistant: {choice['message']['content']}")
else:
print("Assistant returned no content after tool execution.")
elif assistant_message.get("content"):
print(f"Assistant: {assistant_message['content']}")
else:
print("Assistant returned no content and no tool calls.")
print("\n" + "=" * 60)
print("Examples completed!")
print("=" * 60)
if __name__ == "__main__":
try:
main()
except requests.exceptions.ConnectionError:
print("Error: Could not connect to server.")
print("Make sure the server is running:")
print(" uv run m serve docs/examples/m_serve/m_serve_example_tool_calling.py")
except requests.exceptions.HTTPError as e:
print(f"Error: {e}")
if e.response is not None:
try:
print("Server response:", json.dumps(e.response.json(), indent=2))
except ValueError:
print("Server response:", e.response.text)
except Exception as e:
print(f"Error: {e}")