from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.novita.ai/openai",
# Get the Novita AI API Key from: https://novita.ai/settings/key-management.
api_key="<YOUR Novita AI API Key>",
)
model = "deepseek/deepseek_v3"
# Example function to simulate fetching weather data.
def get_weather(location):
"""Retrieves the current weather for a given location."""
print("Calling get_weather function with location: ", location)
# In a real application, you would call an external weather API here.
# This is a simplified example returning hardcoded data.
return json.dumps({"location": location, "temperature": "60 degrees Fahrenheit"})
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather of an location, the user shoud supply a location first",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"]
},
}
},
]
messages = [
{
"role": "user",
"content": "What is the weather in San Francisco?"
}
]
# Let's send the request and print the response.
response = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
)
# Please check if the response contains tool calls if in production.
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's 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"))
# Append 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, now with the function result
answer_response = client.chat.completions.create(
model=model,
messages=messages,
# Note: Do not include tools parameter here
)
print(answer_response.choices[0].message)