Skip to main content

saytoken-agent-sdk

SDK Python para conectar una aplicación externa a un agente de SayToken a través del Canal API. Requiere Python 3.9 o superior.

Requiere que el Canal API esté activo en el agente (Modificar agente > Canal API) y tener a mano:

  • api_channel_key
  • api_channel_secret (se muestra una sola vez; si lo perdés, rotalo en el mismo panel)

Instalación

pip install saytoken-agent-sdk

Modo 1: polling (sin servidor propio)

Ideal para scripts, jobs o backends que no exponen un endpoint HTTPS público. ask(...) envía el mensaje y hace polling hasta que el agente responde o se agota el timeout.

from saytoken_agent_sdk import SayTokenAgentClient

client = SayTokenAgentClient(
    base_url="https://TU_DOMINIO",
    api_channel_key="ack_live_...",
    api_channel_secret="acs_live_...",
)

reply = client.ask(
    message="Hola, necesito ayuda con mi pedido.",
    external_user_id="cliente_123",
    conversation_id="ticket_456",
)

print(reply.status)   # "completed" | "failed"
print(reply.reply)    # texto de respuesta del agente

Usá siempre el mismo conversation_id para mantener el hilo: si cambia, el agente pierde el contexto previo. Cada mensaje admite hasta 8000 caracteres.

Para reintentar sin duplicar el mensaje ni su consumo, pasá tu propio external_event_id y repetí la llamada con ese mismo valor. Si no lo pasás, el SDK genera uno nuevo en cada llamada:

reply = client.ask(
    message="Hola, necesito ayuda con mi pedido.",
    external_user_id="cliente_123",
    conversation_id="ticket_456",
    external_event_id="pedido_789_mensaje_1",
)

Durante el polling, ask(...) reintenta los errores 429, 5xx y fallos de red con espera creciente hasta agotar timeout. Las consultas de estado admiten 120 por minuto por IP y canal; si hacés muchas ask(...) en paralelo, subí poll_interval. Si el agente tiene carga, subí timeout.

Si preferís controlar el envío y la consulta por separado:

inbound_message_id = client.send_message(
    message="Hola",
    external_user_id="cliente_123",
)

reply = client.get_status(inbound_message_id)

get_status usa el endpoint GET /api/agent-api/{api_channel_key}/messages/{inbound_message_id}, autenticado con la misma firma HMAC del canal (no requiere login de usuario SayToken).

Modo 2: callback (tiempo real, requiere HTTPS público)

Si tu app ya expone un servidor HTTPS, configurá Callback URL en el panel del agente y usá parse_callback para validar la firma y parsear el evento que SayToken te envía cuando el agente termina de responder:

from saytoken_agent_sdk import parse_callback, InvalidCallbackSignature

@app.post("/saytoken/callback")
def saytoken_callback():
    raw_body = request.get_data()
    try:
        event = parse_callback(
            raw_body,
            request.headers.get("X-SayToken-Timestamp", ""),
            request.headers.get("X-SayToken-Signature", ""),
            callback_secret="tu_callback_secret_opcional",
        )
    except InvalidCallbackSignature:
        return jsonify({"error": "invalid signature"}), 401

    print(event.status, event.reply)
    return jsonify({"ok": True}), 200

Con callback_secret, parse_callback rechaza firmas inválidas y callbacks con más de 5 minutos de antigüedad (ajustable con tolerance_seconds), así que tu servidor debe tener la hora sincronizada. Sin callback_secret no se valida nada: cualquiera que conozca tu URL podría enviarte eventos falsos. Tu endpoint debe responder 2xx; si no, SayToken reintenta hasta completar 5 intentos.

Seguridad

api_channel_secret da permiso para enviar mensajes al agente y leer sus respuestas. Guardalo solo en tu backend (variables de entorno / secret manager) — nunca lo incluyas en una app distribuida al usuario final (móvil, frontend, extensión).

Manejo de errores

  • SayTokenAuthError — firma HMAC inválida o secreto incorrecto.
  • SayTokenAPIError — cualquier otro error HTTP (status_code, detail). Si ocurre durante el polling de ask(...), incluye inbound_message_id.
  • SayTokenTimeoutError — ask(...) no obtuvo completed/failed dentro del timeout; el mensaje puede seguir procesándose. Consultalo luego con get_status(exc.inbound_message_id), sin volver a enviarlo.
Código Causa probable
401 api_channel_secret incorrecto o reloj desfasado más de 5 minutos.
403 Agente no publicado o IP fuera de Allowed IPs.
404 api_channel_key incorrecta, canal apagado o mensaje inexistente.
413 El mensaje supera los 8000 caracteres.
422 Faltan message o external_user_id.
429 Demasiadas solicitudes o límite diario del canal agotado.

Licencia

MIT. Ver el archivo LICENSE.

Metadata

Release files for saytoken-agent-sdk 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for saytoken-agent-sdk 0.2.0
File Size Uploaded Provenance Actions
saytoken_agent_sdk-0.2.0.tar.gz 9.8 kB Without provenance Details for saytoken_agent_sdk-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for saytoken-agent-sdk 0.2.0
File Interpreter ABI Platform Actions
saytoken_agent_sdk-0.2.0-py3-none-any.whl Python 3 none any Details for saytoken_agent_sdk-0.2.0-py3-none-any.whl

Total release size: 18.1 kB

Release files / saytoken_agent_sdk-0.2.0.tar.gz

Download URL saytoken_agent_sdk-0.2.0.tar.gz
Size 9.8 kB
Tags Source
SHA-256 checksum
How to use checksums
799ae1d3b022dbc8c088d01a256f0104cf1f7e240ce172e2a20ad92d1d508928
BLAKE2b-256 checksum
How to use checksums
da6f6589d4af4d58db6194746a7c1224696ee5a7ee66eaa79a24ee29b2653310
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.0

Release files / saytoken_agent_sdk-0.2.0-py3-none-any.whl

Download URL saytoken_agent_sdk-0.2.0-py3-none-any.whl
Size 8.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
74c5bdcb1f3ddac1765c0bd95261ed4e8eba9d1d01bd330c88cb166bc706076f
BLAKE2b-256 checksum
How to use checksums
6a382e753ec8c554cc30d791f95ba48aa1e3f32b33cdcf159e374a48e1caa2d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.0

Security for saytoken-agent-sdk 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page