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

# Integração com o LlamaIndex Agents

> Conecte o LlamaIndex Agents ao AI Gateway do Toqan Router para ter observabilidade completa, confiabilidade integrada e acesso a mais de 500 LLMs de mais de 30 provedores.

> [card] [AI Gateway](#ai-gateway)
>
> Roteie suas chamadas de LLM pelo AI Gateway alterando apenas a base URL. Sem dependência de fornecedor: use sempre o melhor modelo pelo menor custo para o seu caso de uso.

## AI Gateway

### Visão geral

O LlamaIndex Agents é um framework agêntico construído sobre o LlamaIndex que permite que LLMs raciocinem, usem ferramentas e executem fluxos de trabalho com múltiplas etapas. Ao conectar o LlamaIndex Agents ao AI Gateway do Toqan Router, você obtém agentes prontos para produção com recursos de nível empresarial sem alterar seu código existente.

### Principais benefícios

O AI Gateway do Toqan Router aprimora seus LlamaIndex Agents com:

> [card] Observabilidade completa
>
> Acompanhe cada etapa de agente, uso de ferramenta e trace de raciocínio com análises detalhadas

> [card] Confiabilidade integrada
>
> Fallbacks automáticos, novas tentativas e balanceamento de carga para resiliência em produção

> [card] Otimização de custos
>
> Acompanhamento de custos em tempo real e gestão de gastos em todas as suas operações de IA

> [card] Acesso a múltiplos provedores
>
> Acesse mais de 500 LLMs e mais de 30 provedores por meio de uma integração única e unificada

### Pré-requisitos

Antes de integrar o LlamaIndex Agents ao Toqan Router, certifique-se de ter:

* Uma conta no Toqan Router e uma chave de API
* Python 3.8 ou superior
* O LlamaIndex instalado no seu projeto

> [!NOTE]
>
> Para configurar sua chave de API, consulte Chaves de API e endpoints.

### Instalação

Instale o LlamaIndex e as dependências necessárias:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
pip install llama-index llama-index-llms-openai-like
```

### Configuração

Configure o LlamaIndex Agents para usar o AI Gateway do Toqan Router com a classe `OpenAILike`:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from llama_index.llms.openai_like import OpenAILike
import os

# Configure OpenAI-compatible LLM with Toqan Router AI Gateway
llm = OpenAILike(
    model="openai/gpt-5.6-sol",
    api_key=os.getenv("TOQAN_API_KEY"),
    api_base="https://router.toqan.ai/eu/v3/router",
    is_chat_model=True,
)
```

> **api\_base**: `https://router.toqan.ai/eu/v3/router`

### Exemplo básico de agente

Veja um exemplo completo usando `ReActAgent` com uma ferramenta simples:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import asyncio
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.tools import FunctionTool
from llama_index.llms.openai_like import OpenAILike
import os

# Configure LLM with Toqan Router AI Gateway
llm = OpenAILike(
    model="openai/gpt-5.6-sol",
    api_key=os.getenv("TOQAN_API_KEY"),
    api_base="https://router.toqan.ai/eu/v3/router",
    is_chat_model=True,
)

# Define a tool
def get_weather(location: str) -> str:
    """Get the current weather for a location."""
    return f"The weather in {location} is sunny and 72°F"

# Create agent
agent = ReActAgent(
    tools=[FunctionTool.from_defaults(get_weather)],
    llm=llm,
)

async def main():
    response = await agent.run("What's the weather in San Francisco?")
    print(response)

asyncio.run(main())
```

### Agente com várias ferramentas

Crie agentes com várias ferramentas para raciocínio complexo:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import asyncio
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.tools import FunctionTool
from llama_index.llms.openai_like import OpenAILike
import os

llm = OpenAILike(
    model="openai/gpt-5.6-sol",
    api_key=os.getenv("TOQAN_API_KEY"),
    api_base="https://router.toqan.ai/eu/v3/router",
    is_chat_model=True,
)

def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b

def multiply(a: int, b: int) -> int:
    """Multiply two integers."""
    return a * b

def get_company_info(company: str) -> str:
    """Get basic information about a company."""
    companies = {
        "openai": "OpenAI is an AI research company founded in 2015.",
        "anthropic": "Anthropic is an AI safety company founded in 2021.",
    }
    return companies.get(company.lower(), f"No information found for {company}")

agent = ReActAgent(
    tools=[
        FunctionTool.from_defaults(add),
        FunctionTool.from_defaults(multiply),
        FunctionTool.from_defaults(get_company_info),
    ],
    llm=llm,
    system_prompt="You are a helpful assistant with access to math and company information tools.",
)

async def main():
    response = await agent.run("What is 15 * 4, and tell me about Anthropic?")
    print(response)

asyncio.run(main())
```

### Seleção de modelo

Com o Toqan Router, você pode usar qualquer modelo compatível de mais de 30 provedores:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import asyncio
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.tools import FunctionTool
from llama_index.llms.openai_like import OpenAILike
import os

def get_time(timezone: str) -> str:
    """Get the current time in a timezone."""
    return f"The current time in {timezone} is 14:30"

# Use Claude
claude_llm = OpenAILike(
    model="anthropic/claude-sonnet-5",
    api_key=os.getenv("TOQAN_API_KEY"),
    api_base="https://router.toqan.ai/eu/v3/router",
    is_chat_model=True,
)

# Use Gemini
gemini_llm = OpenAILike(
    model="google/gemini-2.5-pro",
    api_key=os.getenv("TOQAN_API_KEY"),
    api_base="https://router.toqan.ai/eu/v3/router",
    is_chat_model=True,
)

agent = ReActAgent(
    tools=[FunctionTool.from_defaults(get_time)],
    llm=claude_llm,
)

async def main():
    response = await agent.run("What time is it in Tokyo?")
    print(response)

asyncio.run(main())
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.