49 lines
2.0 KiB
Python
49 lines
2.0 KiB
Python
"""Test DeepSeek tool calling with follow-up"""
|
|
import json, urllib.request
|
|
|
|
def chat(messages, tools=None):
|
|
payload = {"model": "deepseek-v4-flash", "messages": messages, "max_tokens": 200}
|
|
if tools:
|
|
payload["tools"] = tools
|
|
payload["tool_choice"] = "auto"
|
|
req = urllib.request.Request(
|
|
'https://api.deepseek.com/chat/completions',
|
|
data=json.dumps(payload).encode(),
|
|
headers={'Content-Type': 'application/json',
|
|
'Authorization': 'Bearer sk-360ef76d59674d6b8bc2eb160327dd39'},
|
|
method='POST'
|
|
)
|
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
return json.loads(resp.read())
|
|
|
|
tools = [{"type": "function", "function": {
|
|
"name": "get_weather", "description": "Get weather",
|
|
"parameters": {"type": "object", "properties": {"loc": {"type": "string"}}, "required": ["loc"]}
|
|
}}]
|
|
|
|
# Call 1: LLM returns tool_call
|
|
msgs = [{"role": "user", "content": "Get weather for Beijing"}]
|
|
resp1 = chat(msgs, tools)
|
|
msg1 = resp1["choices"][0]["message"]
|
|
print(f'Call 1: tool_calls={bool(msg1.get("tool_calls"))}')
|
|
if msg1.get("tool_calls"):
|
|
tc = msg1["tool_calls"][0]
|
|
print(f' tool={tc["function"]["name"]} args={tc["function"]["arguments"]}')
|
|
|
|
# Call 2: Send tool result back (test different formats)
|
|
print('\nTest 1: with "name" field:')
|
|
msgs2 = msgs + [msg1, {"role": "tool", "tool_call_id": tc["id"], "name": tc["function"]["name"], "content": '{"temp": 22}'}]
|
|
try:
|
|
resp2 = chat(msgs2)
|
|
print(f' OK: {resp2["choices"][0]["message"]["content"][:100]}')
|
|
except urllib.error.HTTPError as e:
|
|
print(f' 400: {e.read().decode()[:200]}')
|
|
|
|
print('\nTest 2: without "name" field:')
|
|
msgs3 = msgs + [msg1, {"role": "tool", "tool_call_id": tc["id"], "content": '{"temp": 22}'}]
|
|
try:
|
|
resp3 = chat(msgs3)
|
|
print(f' OK: {resp3["choices"][0]["message"]["content"][:100]}')
|
|
except urllib.error.HTTPError as e:
|
|
print(f' 400: {e.read().decode()[:200]}')
|