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

# Ejecutar con el SDK de Python

> Invoca un agente desde Python con el paquete fetch-hive-sdk

# Ejecutar con el SDK de Python

Usa el paquete oficial `fetch-hive-sdk` cuando quieras enviar un mensaje a un agente desde Python. El SDK envuelve el endpoint público [`POST /v1/agent/invoke`](../api-reference/agents/invoke), maneja la autenticación, admite streaming y entradas multimodales, y expone variantes sincrónicas y `asyncio`.

## Instalación

```bash theme={null}
pip install fetch-hive-sdk
```

El SDK requiere Python 3.9+ y usa `httpx` por debajo.

## Autenticación

Establece la variable de entorno `FETCH_HIVE_API_KEY` con la clave de API de tu espacio de trabajo (el SDK la lee automáticamente):

```bash theme={null}
export FETCH_HIVE_API_KEY=fhk_...
```

```python theme={null}
from fetch_hive_sdk import FetchHive

client = FetchHive()
```

O pasa la clave explícitamente:

```python theme={null}
client = FetchHive(api_key="fhk_...")
```

Consulta [Claves de API](../workspace/api-keys) para saber cómo crear y rotar claves.

## Ejemplo básico

Envía un mensaje a un agente y lee la respuesta final:

```python theme={null}
from fetch_hive_sdk import FetchHive

client = FetchHive()

reply = client.invoke_agent(
    agent="AGENT_UUID",
    message="Summarize the latest AI infrastructure trends",
)

print(reply["response"])
```

Consulta el [formato de respuesta sin streaming](../api-reference/agents/invoke#response).

## Referencia del método

| Argumento   | Tipo                                             | Requerido | Descripción                                                                                                                                              |
| ----------- | ------------------------------------------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `agent`     | `str`                                            | Sí        | El ID del agente                                                                                                                                         |
| `message`   | `str`                                            | Sí        | El mensaje que quieres enviar                                                                                                                            |
| `thread_id` | `str`                                            | No        | Una cadena arbitraria que identifica un hilo de conversación persistente. Fetch Hive crea el hilo en el primer uso y lo reanuda en llamadas posteriores. |
| `messages`  | `list[dict]`                                     | No        | Historial de conversación administrado por el llamador. Cada elemento: `{"role": "user" \| "assistant" \| "system", "content": str}`.                    |
| `user`      | `str`                                            | No        | Identificador opaco del llamador expuesto en [Seguimiento de usuarios](../user-tracking/overview)                                                        |
| `metadata`  | `dict[str, str \| int \| float \| bool \| None]` | No        | Metadatos planos definidos por el llamador para auditoría y filtrado de registros. Consulta [Metadatos de invocación](../user-tracking/invoke-metadata)  |

El SDK inyecta `streaming: false` para `invoke_agent`. Para hacer streaming, usa `invoke_agent_stream` (abajo).

## Manejo de la respuesta

```python theme={null}
reply = client.invoke_agent(agent="AGENT_UUID", message="Hello")

print(reply["response"])      # final text
print(reply["model"])         # model identifier
print(reply["usage"])         # token usage breakdown
print(reply["request_id"])    # use this to look up the run in Logs
print(reply.get("tool_calls"))  # tool invocations made during the run
```

## Streaming

Usa `invoke_agent_stream` para recibir Server-Sent Events a medida que llegan. El método devuelve un generador que produce diccionarios de eventos analizados:

```python theme={null}
for chunk in client.invoke_agent_stream(
    agent="AGENT_UUID",
    message="Summarize the latest AI infrastructure trends",
    thread_id="user-456-support-session",
):
    if chunk.get("type") == "response":
        print(chunk.get("response", ""), end="", flush=True)
    elif chunk.get("type") == "tool":
        print(f"\n[Calling tool: {chunk.get('tool')}]")
    elif chunk.get("type") == "usage":
        print("\n\nUsage:", chunk["usage"])
```

El stream genera los mismos tipos de eventos documentados en [Invocar Agente → Respuesta](../api-reference/agents/invoke#response): `summary` (cuando se dispara el resumen automático), `reasoning`, `response`, `tool`, un evento final `usage`, o un evento `error` si el proveedor falla a mitad del stream.

### Streaming asíncrono

Para aplicaciones con `asyncio`, usa `ainvoke_agent_stream`. Tiene los mismos argumentos pero devuelve un iterador asíncrono:

```python theme={null}
import asyncio
from fetch_hive_sdk import FetchHive

async def main():
    client = FetchHive()
    async for chunk in client.ainvoke_agent_stream(
        agent="AGENT_UUID",
        message="Hello",
        thread_id="user-456-support-session",
    ):
        if chunk.get("type") == "response":
            print(chunk.get("response", ""), end="", flush=True)

asyncio.run(main())
```

## Conversaciones de múltiples turnos

### Hilos persistentes

Pasa cualquier cadena como `thread_id` y Fetch Hive creará el hilo en la primera llamada y lo reanudará en llamadas posteriores con el mismo valor:

```python theme={null}
client.invoke_agent(
    agent="AGENT_UUID",
    message="What are the main AI infrastructure trends right now?",
    thread_id="user-456-support-session",
)

client.invoke_agent(
    agent="AGENT_UUID",
    message="Which of those trends have the most enterprise adoption?",
    thread_id="user-456-support-session",
)
```

### Historial sin estado

Administra el estado tú mismo pasando los turnos previos en `messages`. Fetch Hive usa el historial proporcionado como contexto pero no lo persiste:

```python theme={null}
client.invoke_agent(
    agent="AGENT_UUID",
    message="Which of those trends have the most enterprise adoption?",
    messages=[
        {"role": "user", "content": "What are the main AI infrastructure trends right now?"},
        {"role": "assistant", "content": "Teams are focusing on evals, tool routing, and observability."},
    ],
)
```

## Entradas multimodales

Adjunta imágenes al mensaje actual con `attachments`:

```python theme={null}
result = client.invoke_agent(
    agent="vision-agent",
    message="Describe this image",
    attachments=["https://example.com/photo.jpg"],
)
print(result["response"])
```

Las URLs deben comenzar con `https://`.

## Configuración

| Opción     | Valor predeterminado                     | Descripción                                  |
| ---------- | ---------------------------------------- | -------------------------------------------- |
| `api_key`  | variable de entorno `FETCH_HIVE_API_KEY` | Token Bearer del panel                       |
| `base_url` | `https://api.fetchhive.com/v1`           | Sobrescribe la URL base de la API            |
| `timeout`  | `120`                                    | Tiempo de espera de la solicitud en segundos |

```python theme={null}
client = FetchHive(
    api_key="fhk_...",
    base_url="https://api.fetchhive.com/v1",
    timeout=120,
)
```

## Errores

Las respuestas no 2xx lanzan un `httpx.HTTPStatusError` con el código de estado y el cuerpo de la respuesta:

```python theme={null}
import httpx

try:
    reply = client.invoke_agent(agent="AGENT_UUID", message="Hello")
except httpx.HTTPStatusError as exc:
    print("Fetch Hive returned", exc.response.status_code, exc.response.text)
```

Consulta [Errores y límites de tasa](../api-reference/errors-and-rate-limits) para conocer el significado de los códigos de estado.

## Enlaces

* [Paquete en PyPI](https://pypi.org/project/fetch-hive-sdk/)
* [Código fuente en GitHub](https://github.com/Fetch-Hive/python-sdk)

## Próximos pasos

* [Ejecutar con API](./run-with-api) - El mismo flujo con cURL
* [Ejecutar con el SDK de Node.js](./run-with-nodejs-sdk)
* [Ejecutar con el SDK de Ruby](./run-with-ruby-sdk)
* [Ejecutar con el SDK de PHP](./run-with-php-sdk)
* [Invocar Agente](../api-reference/agents/invoke) - Referencia completa del endpoint
