Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:AMAP ML SkillClaw forward chat

From Leeroopedia
Knowledge Sources
Domains Networking, Fault_Tolerance
Last Updated 2026-10-22 00:00 GMT

Overview

Concrete tool for forwarding chat-completion requests to upstream LLM endpoints with bounded failover across primary and fallback endpoints, provided by the SkillClaw client package.

Description

The forward_chat async function sends a prepared chat-completion request body to the primary LLM endpoint, and if that fails with retryable HTTP errors (408, 429, 500, 502, 503, 504), falls over to up to 3 preconfigured fallback endpoints. A shared time budget bounds all attempts together. The function handles compatibility retries (removing unsupported `temperature` parameter, switching to stream mode) and respects `Retry-After` headers for rate-limited responses.

Usage

Import and use when you need to:

  • Forward LLM requests with automatic failover to backup endpoints
  • Understand the retry and compatibility logic of the SkillClaw proxy
  • Configure fallback LLM endpoints for high availability

Code Reference

Source Location

  • Repository: SkillClaw
  • File: `skillclaw/chat_upstream.py:L102-167`

Signature

async def forward_chat(
    config: SkillClawConfig,
    body: dict,
    *,
    timeout: float,
    collect_stream: Callable,
    stream: bool = False,
) -> dict:
    """Forward a chat-completion request with bounded failover.

    Tries primary endpoint first, then up to 3 fallbacks.
    A shared time budget (timeout) bounds all endpoint attempts.
    """

def chat_endpoints(config, requested_model: str) -> list[dict]:
    """Build the ordered list of endpoint dicts (primary + fallbacks).

    Returns [{"api_base", "model_id", "api_key", "provider"}, ...].
    """

def prepare_chat_request(
    config, body: dict, endpoint: dict, *, stream: bool = False
) -> tuple[str, dict, dict]:
    """Prepare URL, payload, and headers for one endpoint attempt.

    Returns (url, payload, headers).
    """

def validate_fallbacks(value) -> list[dict]:
    """Validate and normalize the llm.fallbacks config field.

    Ensures: list of <=3 entries, valid HTTP(S) URLs, each with model_id.
    """

Import

from skillclaw.chat_upstream import forward_chat, chat_endpoints, prepare_chat_request, validate_fallbacks

I/O Contract

Inputs

Name Type Required Description
config SkillClawConfig Yes Config with llm_api_base, llm_api_key, llm_model_id, llm_fallbacks
body dict Yes Chat completion request body (model, messages, tools)
timeout float Yes Total time budget for all endpoint attempts (seconds)
collect_stream Callable Yes Stream collector function for streaming responses
stream bool No Whether to use streaming (default False)

Outputs

Name Type Description
forward_chat returns dict OpenAI-compatible chat completion JSON response
On failure HTTPException 502 (upstream failed) or 504 (timeout exceeded)

Usage Examples

Basic Forwarding

import asyncio
from skillclaw.chat_upstream import forward_chat

# config has llm_api_base, llm_api_key, llm_model_id
body = {
    "model": "gpt-4o",
    "messages": [
        {"role": "system", "content": "You are helpful."},
        {"role": "user", "content": "Hello!"},
    ],
}

async def collect_stream(response, model):
    # Non-streaming: just return the JSON
    return response

result = await forward_chat(
    config=cfg,
    body=body,
    timeout=120.0,
    collect_stream=collect_stream,
)
print(result["choices"][0]["message"]["content"])

With Fallback Endpoints

# Config with fallbacks (max 3):
# llm_fallbacks = [
#     {"api_base": "https://backup1.example.com/v1", "model_id": "gpt-4o", "api_key": "key1"},
#     {"api_base": "https://backup2.example.com/v1", "model_id": "gpt-4o", "api_key": "key2"},
# ]
# forward_chat will try primary first, then fallbacks on 5xx/429 errors

Related Pages

Implements Principle

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment