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

# Function Calling

> Permita que os modelos de chat da Venice chamem as ferramentas da sua aplicação com function calling compatível com OpenAI e a API de chat completions.

Function calling permite que um modelo escolha chamadas de ferramentas estruturadas que sua aplicação pode executar. O próprio modelo não executa a função. Ele retorna o nome da função e os argumentos, seu código executa a função e você envia o resultado de volta ao modelo.

Use function calling quando o modelo precisar de dados em tempo real, ações da aplicação, consultas a bancos de dados ou cálculos determinísticos.

## Definição Básica de Ferramenta

Defina ferramentas com o array `tools` compatível com OpenAI:

<CodeGroup>
  ```python Python theme={"system"}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["VENICE_API_KEY"],
      base_url="https://api.venice.ai/api/v1",
  )

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get the current weather in a location",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "City and state, such as San Francisco, CA",
                      }
                  },
                  "required": ["location"],
              },
          },
      }
  ]

  response = client.chat.completions.create(
      model="zai-org-glm-5",
      messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
      tools=tools,
  )

  print(response.choices[0].message.tool_calls)
  ```

  ```javascript Node.js theme={"system"}
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: process.env.VENICE_API_KEY,
    baseURL: "https://api.venice.ai/api/v1",
  });

  const tools = [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the current weather in a location",
        parameters: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "City and state, such as San Francisco, CA",
            },
          },
          required: ["location"],
        },
      },
    },
  ];

  const response = await client.chat.completions.create({
    model: "zai-org-glm-5",
    messages: [{ role: "user", content: "What is the weather in San Francisco?" }],
    tools,
  });

  console.log(response.choices[0].message.tool_calls);
  ```

  ```bash cURL theme={"system"}
  curl https://api.venice.ai/api/v1/chat/completions \
    -H "Authorization: Bearer $VENICE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "zai-org-glm-5",
      "messages": [
        {"role": "user", "content": "What is the weather in San Francisco?"}
      ],
      "tools": [
        {
          "type": "function",
          "function": {
            "name": "get_weather",
            "description": "Get the current weather in a location",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "City and state, such as San Francisco, CA"
                }
              },
              "required": ["location"]
            }
          }
        }
      ]
    }'
  ```
</CodeGroup>

## Executar a Ferramenta

Quando o modelo escolhe uma ferramenta, inspecione `message.tool_calls`, faça o parse dos argumentos, execute a função da sua aplicação e envie o resultado de volta como uma mensagem `tool`.

```python Python theme={"system"}
import json

message = response.choices[0].message
tool_call = message.tool_calls[0]
arguments = json.loads(tool_call.function.arguments)

weather = get_weather(arguments["location"])

follow_up = client.chat.completions.create(
    model="zai-org-glm-5",
    messages=[
        {"role": "user", "content": "What is the weather in San Francisco?"},
        message.model_dump(),
        {
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(weather),
        },
    ],
    tools=tools,
)

print(follow_up.choices[0].message.content)
```

## Escolha um Modelo

O suporte a function calling é específico de cada modelo. Use a página [Modelos de Texto](/models/text) ou a [API de Modelos](/api-reference/endpoint/models/list) para encontrar modelos com `supportsFunctionCalling`.

<Warning>
  Trate os argumentos das ferramentas como entrada não confiável. Valide os argumentos antes de usá-los em consultas a bancos de dados, comandos shell, pagamentos ou outras operações com efeitos colaterais.
</Warning>

## Dicas de Design

* Mantenha nomes e descrições de ferramentas curtos e literais.
* Use JSON Schema para facilitar a produção de argumentos válidos pelo modelo.
* Prefira ferramentas específicas com entradas claras a uma única ferramenta ampla com muitos comportamentos opcionais.
* Retorne resultados concisos das ferramentas para que a resposta final tenha contexto suficiente sem desperdiçar tokens.

## Recursos Relacionados

* [API de Chat Completions](/api-reference/endpoint/chat/completions)
* [Modelos de Texto](/models/text)
* [Guia de Respostas Estruturadas](/guides/features/structured-responses)
* [Integração com LangChain](/guides/integrations/langchain#function-calling-with-agents)
