from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.myrouter.ai/openai",
api_key="<Your API Key>",
)
model = "deepseek/deepseek-v3"
# Example function to simulate fetching weather data.
def get_weather(location):
"""Get the current weather for a specified location"""
print("Calling get_weather function, location: ", location)
# In a real application, you would call an external weather API here.
# This is a simplified example that returns hardcoded data.
return json.dumps({"location": location, "temperature": "20 Celsius"})
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a location. The user must first provide the location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City information, e.g.: Shanghai",
}
},
"required": ["location"]
},
}
},
]
messages = [
{
"role": "user",
"content": "What's the weather like in Shanghai?"
}
]
# Send the request and print the response
response = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
)
# In production, check if the response contains tool calls
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.model_dump())
# Ensure tool_call is defined from the previous step
if tool_call:
# Extend conversation history with the assistant tool call message
messages.append(response.choices[0].message)
function_name = tool_call.function.name
if function_name == "get_weather":
function_args = json.loads(tool_call.function.arguments)
# Execute the function and get the response
function_response = get_weather(
location=function_args.get("location"))
# Add the function response to the messages
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"content": function_response,
}
)
# Get the final response from the model with function results
answer_response = client.chat.completions.create(
model=model,
messages=messages,
# Note: do not include the tools parameter here
)
print(answer_response.choices[0].message)