Skip to main content

Use Cases

Function Calling enables models to interact with external tools to retrieve real-time information or perform specific actions. This improves data accuracy and expands model capabilities, allowing models to support more dynamic and practical application scenarios instead of simply generating text. Examples of Function Calling use cases include:
  • Dynamic information lookup: Call APIs to retrieve real-time dynamic data from external systems, such as weather, news, and stock quotes. For example, by calling a weather API to get real-time weather information, when a user asks about the current weather, the model can tell the user the weather conditions at that moment instead of providing an outdated forecast.
  • Task automation: Execute specific actions through function calls, allowing users to trigger automated backend operations through conversation. For example, by calling a ticket booking website API to reserve tickets, when a user asks how to buy tickets for an attraction, the model can help the user complete the booking directly instead of merely explaining how to book tickets.

Supported Models

The following models support Function Calling:

How to Use

  1. Define the tool functions that the model should call.
  2. Add the tools parameter to the request to define the functions the model can use.

Example

The following section provides a complete Python code example. It uses querying the current weather for a location as an example to demonstrate how to use Function Calling. For the specific API format of Function Calling, see the Create Chat Completion API.

1. Initialize the Client

You need to initialize the client with your JieKou AI API key.
from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.highwayapi.ai/openai",
    api_key="<Your API Key>",
)

model = "deepseek/deepseek-v3"

2. Define the Function to Call

Define the function that the model should call. The following Python example demonstrates a function for retrieving weather information.
# 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"})

3. Construct an API Request with Tools and the User Message

Create the API call request. This request includes the tools parameter, which defines the function the model can use, as well as the user’s message.
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())
Output:
{'id': '0', 'function': {'arguments': '{"location": "Shanghai"}', 'name': 'get_weather'}, 'type': 'function'}

4. Respond Based on the Function Call Result and Get the Final Answer

Next, handle the function call, execute the get_weather function, and send the result back to the model to generate the final response for the user.
# 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)
Output:
ChatCompletionMessage(content="The current temperature in Shanghai is 20 degrees Celsius. Please note that weather conditions may change at any time, so we recommend checking the latest weather forecast for more accurate information.", refusal=None, role='assistant', function_call=None, tool_calls=None)

Complete Code

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)