> ## Documentation Index
> Fetch the complete documentation index at: https://friendli.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool Calling with Model APIs

> Implement tool calling with Friendli Model APIs. Tutorial covers defining tools, handling function calls, and building multi-turn agent loops.

export const RoundedBorderBox = ({children, caption}) => <div className="rounded-border-box">
    {children}
    {caption && <p className="text-sm text-gray-700 dark:text-gray-400">{caption}</p>}
  </div>;

## Goals

* Use tool calling to build your own AI agent with [**Friendli Model APIs**](https://friendli.ai/product/model-apis)
* Check out the examples below to see how you can interact with state-of-the-art language models while letting them search the web, run Python code, etc.
* Feel free to make your own custom tools!

## Getting Started

1. Head to [**Friendli Suite**](https://friendli.ai/suite), and create an account.
2. Grab a [Personal API Key](https://friendli.ai/suite/~/setting/keys) to use Friendli Model APIs within an agent.

## Step 1. Playground UI

Experience tool calling on the Playground!

<RoundedBorderBox>
  <img alt="Sidebar" src="https://mintcdn.com/friendliai/SRK7vx0X1v_2rjkU/static/images/guides/model-apis/sidebar.png?fit=max&auto=format&n=SRK7vx0X1v_2rjkU&q=85&s=f9cccd5c42639d08d83ca72600e4d410" width="936" height="612" data-path="static/images/guides/model-apis/sidebar.png" />
</RoundedBorderBox>

<br />

<RoundedBorderBox>
  <img alt="Web Search Tool" src="https://mintcdn.com/friendliai/SRK7vx0X1v_2rjkU/static/images/guides/model-apis/web-search-example.png?fit=max&auto=format&n=SRK7vx0X1v_2rjkU&q=85&s=b9354bf8dcade95251d93518b1ffd545" width="2924" height="1476" data-path="static/images/guides/model-apis/web-search-example.png" />
</RoundedBorderBox>

1. On your left sidebar, click the 'Model APIs' option to access the playground page.
2. You will see models that can be used as Model APIs. Select the one you want and click the endpoint.
3. Click the 'Tools' button, select the Search tool, and enter a query to see the response. 😀

## Step 2. Tool Calling

Search interesting information using the `web:search` tool.
This time, let's try it by writing Python code.

1. Add your input as a `user` role message.
2. Add the `web:search` tool to the tools option.

```python theme={null}
# pip install friendli

import os
from friendli import SyncFriendli

with SyncFriendli(
    token=os.getenv("API_KEY", ""),
) as friendli:
    res = friendli.serverless.tool_assisted_chat.complete(
        model="zai-org/GLM-5.2",
        messages=[
            {
                "role": "user",
                "content": "Find information on the popular movies currently showing in theaters and provide their ratings.",
            },
        ],
        tools=[{"type": "web:search"}],
        max_tokens=200,
    )

    print(res)
```

## Step 3. Multiple Tool Calling

Use multiple tools at once to calculate "How long it will take you to buy a house in the San Francisco Bay Area based on your annual salary". Here are the available built-in tools.

* `math:calculator` (tool for calculating arithmetic operations)
* `web:search` (tool for retrieving data through the web search)
* `code:python-interpreter` (tool for writing and executing python code)

### Example Answer Sheet

```text theme={null}
Prompt: My annual salary is $ 100k. How long it will take to buy a house in San Francisco Bay Area? (`web:search` & `math:calculator` used)

Answer: Based on the web search results, the median price of an existing single-family home in the Bay Area is around $1.25 million.
Using a calculator to calculate how long it would take to buy a house in the San Francisco Bay Area with an annual salary of $100,000, we get:
$1,200,000 (house price) / $100,000 (annual salary) = 12 years
So, it would take approximately 12 years to buy a house in the San Francisco Bay Area with an annual salary of $100,000,
assuming you save your entire salary each year and don't consider other factors like interest rates, taxes, and living expenses.
```

## Step 4. Build a Custom Tool

Build your own creative tool. We will show you how to make a custom tool that retrieves temperature information. (Completed code snippet is provided at the bottom)

1. **Define a function for using as a custom tool**

```python theme={null}
def get_temperature(location: str) -> int:
    """Mock function that returns the city temperature"""
    if "new york" in location.lower():
        return 45
    if "san francisco" in location.lower():
        return 72
    return 30
```

2. **Send a function calling inference request**

   1. Add your input as a `user` role message.
   2. The information about the custom function (e.g., `get_temperature`) goes into the tools option. JSON schema describes the function's parameters.
   3. The response includes the `arguments` field, which are values extracted from the user's input that can be used as parameters of the custom function.

   ```python theme={null}
   # pip install friendli

   import os
   from friendli import SyncFriendli

   token = os.environ.get("API_KEY") or "YOUR_API_KEY"
   client= SyncFriendli(token=token)
   user_prompt = "I live in New York. What should I wear for today's weather?"

   messages = [
       {
           "role": "user",
           "content": user_prompt,
       },
   ]

   tools=[
       {
           "type": "function",
           "function": {
               "name": "get_temperature",
               "description": "Get the temperature information in a given location.",
               "parameters": {
                   "type": "object",
                   "properties": {
                       "location": {
                           "type": "string",
                           "description": "The name of current location e.g., New York",
                       },
                   },
               },
           },
       },
   ]

   chat = client.serverless.chat.complete(
       model="zai-org/GLM-5.2",
       messages=messages,
       tools=tools,
       temperature=0,
       frequency_penalty=1,
   )

   print(chat)
   ```

3. **Generate the final response using the tool calling results**

   1. Add the `tool_calls` response as an `assistant` role message.
   2. Add the result obtained by calling the `get_temperature` function as a `tool` message to the Chat API again.

   ```python theme={null}
   import json

   func_kwargs = json.loads(chat.choices[0].message.tool_calls[0].function.arguments)
   temperature_info = get_temperature(**func_kwargs)

   messages.append(
       {
           "role": "assistant",
           "tool_calls": [
               tool_call.model_dump()
               for tool_call in chat.choices[0].message.tool_calls
           ]
       }
   )
   messages.append(
       {
           "role": "tool",
           "content": str(temperature_info),
           "tool_call_id": chat.choices[0].message.tool_calls[0].id
       }
   )

   chat_w_info = client.serverless.chat.complete(
       model="zai-org/GLM-5.2",
       tools=tools,
       messages=messages,
   )

   for choice in chat_w_info.choices:
       print(choice.message.content)
   ```

* **Complete Code Snippet**

  ```python theme={null}
  # pip install friendli

  import json
  import os
  from friendli import SyncFriendli

  token = os.environ.get("API_KEY") or "YOUR_API_KEY"
  client = SyncFriendli(token=token)
  user_prompt = "I live in New York. What should I wear for today's weather?"

  messages = [
      {
          "role": "user",
          "content": user_prompt,
      },
  ]

  tools=[
      {
          "type": "function",
          "function": {
              "name": "get_temperature",
              "description": "Get the temperature information in a given location.",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "The name of current location e.g., New York",
                      },
                  },
              },
          },
      },
  ]

  chat = client.serverless.chat.complete(
      model="zai-org/GLM-5.2",
      messages=messages,
      tools=tools,
      temperature=0,
      frequency_penalty=1,
  )

  def get_temperature(location: str) -> int:
      """Mock function that returns the city temperature"""
      if "new york" in location.lower():
          return 45
      if "san francisco" in location.lower():
          return 72
      return 30

  func_kwargs = json.loads(chat.choices[0].message.tool_calls[0].function.arguments)
  temperature_info = get_temperature(**func_kwargs)

  messages.append(
      {
          "role": "assistant",
          "tool_calls": [
              tool_call.model_dump()
              for tool_call in chat.choices[0].message.tool_calls
          ]
      }
  )
  messages.append(
      {
          "role": "tool",
          "content": str(temperature_info),
          "tool_call_id": chat.choices[0].message.tool_calls[0].id
      }
  )

  chat_w_info = client.serverless.chat.complete(
      model="zai-org/GLM-5.2",
      tools=tools,
      messages=messages,
  )

  for choice in chat_w_info.choices:
      print(choice.message.content)
  ```

## Congratulations

Following the above instructions, we've experienced the whole process of defining and using a custom tool to generate an accurate and rich answer from LLM models!

Brainstorm creative ideas for your agent by reading our blog articles!

* [**Building an AI Agent for Google Calendar**](https://friendli.ai/blog/ai-agent-google-calendar){/* - [**Hassle-free LLM Fine-tuning with FriendliAI and Weights & Biases**](https://friendli.ai/blog/llm-fine-tuning-friendliai-wandb) */}
* [**Building AI Agents Using Function Calling with LLMs**](https://friendli.ai/blog/ai-agents-function-calling)
* [**Function Calling: Connecting LLMs with Functions and APIs**](https://friendli.ai/blog/llm-function-calling)
