from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.highwayapi.ai/openai",
api_key="<Your API Key>",
)
model = "deepseek/deepseek-v3"
# Example function used to simulate retrieving weather data.
def get_weather(location):
"""Get the current weather for the specified location"""
print("Calling get_weather function, location: ", location)
# In a real-world application, you need to call an external weather API here.
# This is a simplified example that returns hardcoded data.
return json.dumps({"位置": location, "温度": "20 degrees Celsius"})
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a location; the user must provide the location first",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City information, for example: 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 whether the response contains tool calls
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.model_dump())
# Ensure the tool call has been defined from the previous step
if tool_call:
# Extend the conversation history and add 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, including the function result
answer_response = client.chat.completions.create(
model=model,
messages=messages,
# Note: do not include the tools parameter here
)
print(answer_response.choices[0].message)