配置 LLM 与模型(3/6)

High-level architecture of the provider-agnostic language model interface

The LLM system provides a unified interface to language model providers through LiteLLM. It handles model configuration, request orchestration, retry logic, telemetry, and cost tracking across all providers.

Source: openhands-sdk/openhands/sdk/llm/

Core Responsibilities

The LLM system has five primary responsibilities:

  1. Provider Abstraction - Uniform interface to OpenAI, Anthropic, Google, and 100+ providers
  2. Request Pipeline - Dual API support: Chat Completions (completion()) and Responses API (responses())
  3. Configuration Management - Load from environment, JSON, or programmatic configuration
  4. Telemetry & Cost - Track usage, latency, and costs across providers
  5. Enhanced Reasoning - Support for OpenAI Responses API with encrypted thinking and reasoning summaries

Architecture

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 25, "rankSpacing": 70}} }%%
flowchart TB
    subgraph Configuration["Configuration Sources"]
        Env["Environment Variables<br><i>LLM_MODEL, LLM_API_KEY</i>"]
        JSON["JSON Files<br><i>config/llm.json</i>"]
        Code["Programmatic<br><i>LLM(...)</i>"]
    end

    subgraph Core["Core LLM"]
        Model["LLM Model<br><i>Pydantic configuration</i>"]
        Pipeline["Request Pipeline<br><i>Retry, timeout, telemetry</i>"]
    end

    subgraph Backend["LiteLLM Backend"]
        Providers["100+ Providers<br><i>OpenAI, Anthropic, etc.</i>"]
    end

    subgraph Output["Telemetry"]
        Usage["Token Usage"]
        Cost["Cost Tracking"]
        Latency["Latency Metrics"]
    end

    Env --> Model
    JSON --> Model
    Code --> Model

    Model --> Pipeline
    Pipeline --> Providers

    Pipeline --> Usage
    Pipeline --> Cost
    Pipeline --> Latency

    classDef primary fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    classDef secondary fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px
    classDef tertiary fill:#fff4df,stroke:#b7791f,stroke-width:2px

    class Model primary
    class Pipeline secondary
    class LiteLLM tertiary

Key Components

Component Purpose Design
LLM Configuration model Pydantic model with provider settings
completion() Chat Completions API Handles retries, timeouts, streaming
responses() Responses API Enhanced reasoning with encrypted thinking
LiteLLM Provider adapter Unified API for 100+ providers
Configuration Loaders Config hydration load_from_env(), load_from_json()
Telemetry Usage tracking Token counts, costs, latency

Provider Boundaries

Private adapters normalize provider data before the core LLM pipeline consumes it. Stream events use typed contracts; message conversion accepts typed provider objects, generic LiteLLM objects, and dictionaries. It preserves tool-call IDs, Responses item IDs, and reasoning metadata used to replay conversation history.

When custom_tokenizer is configured, the SDK attempts to load a chat-template tokenizer through the optional Transformers package. Token counts include the chat template and tool schemas when supported. Missing Transformers, tokenizer loading failures, or unsupported template results fall back to LiteLLM token counting. Transformers is not required to import or use the SDK.

See LLM Streaming for callback and completion behavior.

Configuration

See LLM source for complete list of supported fields.

Programmatic Configuration

Create LLM instances directly in code:

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30}} }%%
flowchart LR
    Code["Python Code"]
    LLM["LLM(model=...)"]
    Agent["Agent"]

    Code --> LLM
    LLM --> Agent

    style LLM fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px

Example:

from pydantic import SecretStr
from openhands.sdk import LLM

llm = LLM(
    model="anthropic/claude-sonnet-4.1",
    api_key=SecretStr("sk-ant-123"),
    temperature=0.1,
    timeout=120,
)

Environment Variable Configuration

Load from environment using naming convention:

Environment Variable Pattern:

  • Prefix: All variables start with LLM_
  • Mapping: LLM_FIELD → field (lowercased)
  • Types: Auto-cast to int, float, bool, JSON, or SecretStr

Common Variables:

export LLM_MODEL="anthropic/claude-sonnet-4.1"
export LLM_API_KEY="sk-ant-123"
export LLM_USAGE_ID="primary"
export LLM_TIMEOUT="120"
export LLM_NUM_RETRIES="5"

JSON Configuration

Serialize and load from JSON files:

Example:

# Save
llm.model_dump_json(exclude_none=True, indent=2)

# Load
llm = LLM.load_from_json("config/llm.json")

Security: Secrets are redacted in serialized JSON (combine with environment variables for sensitive data). If you need to include secrets in JSON, use llm.model_dump_json(exclude_none=True, context={"expose_secrets": True}).

Request Pipeline

Completion Flow

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30, "rankSpacing": 20}} }%%
flowchart TB
    Request["completion() or responses() call"]
    Validate["Validate Config"]

    Attempt["LiteLLM Request"]
    Success{"Success?"}

    Retry{"Retries<br>remaining?"}
    Wait["Exponential Backoff"]

    Telemetry["Record Telemetry"]
    Response["Return Response"]
    Error["Raise Error"]

    Request --> Validate
    Validate --> Attempt
    Attempt --> Success

    Success -->|Yes| Telemetry
    Success -->|No| Retry

    Retry -->|Yes| Wait
    Retry -->|No| Error

    Wait --> Attempt
    Telemetry --> Response

    style Attempt fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style Retry fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px
    style Telemetry fill:#fff4df,stroke:#b7791f,stroke-width:2px

Pipeline Stages:

  1. Validation: Check required fields (model, messages)
  2. Request: Call LiteLLM with provider-specific formatting
  3. Retry Logic: Exponential backoff on failures (configurable)
  4. Telemetry: Record tokens, cost, latency
  5. Response: Return completion or raise error

Responses API Support

In addition to the standard chat completion API, the LLM system supports OpenAI's Responses API as an alternative invocation path for models that benefit from this newer interface (e.g., GPT-5-Codex only supports Responses API). The Responses API provides enhanced reasoning capabilities with encrypted thinking and detailed reasoning summaries.

Architecture

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30, "rankSpacing": 40}} }%%
flowchart TB
    Check{"Model supports<br>Responses API?"}

    subgraph Standard["Standard Path"]
        ChatFormat["Format as<br>Chat Messages"]
        ChatCall["litellm.completion()"]
    end

    subgraph ResponsesPath["Responses Path"]
        RespFormat["Format as<br>instructions + input[]"]
        RespCall["litellm.responses()"]
    end

    ChatResponse["ModelResponse"]
    RespResponse["ResponsesAPIResponse"]

    Parse["Parse to Message"]
    Return["LLMResponse"]

    Check -->|No| ChatFormat
    Check -->|Yes| RespFormat

    ChatFormat --> ChatCall
    RespFormat --> RespCall

    ChatCall --> ChatResponse
    RespCall --> RespResponse

    ChatResponse --> Parse
    RespResponse --> Parse

    Parse --> Return

    style RespFormat fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style RespCall fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px

Supported Models

Models that automatically use the Responses API path:

Pattern Examples Documentation
gpt-5* gpt-5, gpt-5-mini, gpt-5-codex OpenAI GPT-5 family

Detection: The SDK automatically detects if a model supports the Responses API using pattern matching in model_features.py.

Provider Integration

LiteLLM Abstraction

Software Agent SDK uses LiteLLM for provider abstraction:

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30}} }%%
flowchart TB
    SDK["Software Agent SDK"]
    LiteLLM["LiteLLM"]

    subgraph Providers["100+ Providers"]
        OpenAI["OpenAI"]
        Anthropic["Anthropic"]
        Google["Google"]
        Azure["Azure"]
        Others["..."]
    end

    SDK --> LiteLLM
    LiteLLM --> OpenAI
    LiteLLM --> Anthropic
    LiteLLM --> Google
    LiteLLM --> Azure
    LiteLLM --> Others

    style LiteLLM fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style SDK fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px

Benefits:

  • 100+ Providers: OpenAI, Anthropic, Google, Azure, AWS Bedrock, local models, etc.
  • Unified API: Same interface regardless of provider
  • Format Translation: Provider-specific request/response formatting
  • Error Handling: Normalized error codes and messages

LLM Providers

Provider integrations remain shared between the Software Agent SDK and the OpenHands Application. The pages linked below live under the OpenHands app section but apply verbatim to SDK applications because both layers wrap the same openhands.sdk.llm.LLM interface.

Provider / scenario Documentation
OpenHands hosted models /openhands/usage/llms/openhands-llms
OpenAI /openhands/usage/llms/openai-llms
Azure OpenAI /openhands/usage/llms/azure-llms
Google Gemini / Vertex /openhands/usage/llms/google-llms
Groq /openhands/usage/llms/groq
OpenRouter /openhands/usage/llms/openrouter
Moonshot /openhands/usage/llms/moonshot
LiteLLM proxy /openhands/usage/llms/litellm-proxy
Local LLMs (Ollama, SGLang, vLLM, LM Studio) /openhands/usage/llms/local-llms
Saved SDK LLM profiles LLM Profile Store

When you follow any of those guides while building with the SDK, create an LLM object using the documented parameters (for example, API keys, base URLs, or custom headers) and pass it into your agent or registry. The OpenHands UI surfacing is simply a convenience layer on top of the same configuration model.

Telemetry and Cost Tracking

Telemetry Collection

LLM requests automatically collect metrics:

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30}} }%%
flowchart LR
    Request["LLM Request"]

    subgraph Metrics
        Tokens["Token Counts<br><i>Input/Output</i>"]
        Cost["Cost<br><i>USD</i>"]
        Latency["Latency<br><i>ms</i>"]
    end

    Events["Event Log"]

    Request --> Tokens
    Request --> Cost
    Request --> Latency

    Tokens --> Events
    Cost --> Events
    Latency --> Events

    style Metrics fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style Events fill:#fff4df,stroke:#b7791f,stroke-width:2px

Tracked Metrics:

  • Token Usage: Input tokens, output tokens, total
  • Cost: Per-request cost using configured rates
  • Latency: Request duration in milliseconds
  • Errors: Failure types and retry counts

Cost Configuration

Configure per-token costs for custom models:

llm = LLM(
    model="custom/my-model",
    input_cost_per_token=0.00001,   # $0.01 per 1K tokens
    output_cost_per_token=0.00003,  # $0.03 per 1K tokens
)

Built-in Costs: LiteLLM includes costs for major providers (updated regularly, link)

Custom Costs: Override for:

  • Internal models
  • Custom pricing agreements
  • Cost estimation for budgeting

Component Relationships

How LLM Integrates

%%{init: {"theme": "default", "flowchart": {"nodeSpacing": 30}} }%%
flowchart LR
    LLM["LLM"]
    Agent["Agent"]
    Conversation["Conversation"]
    Events["Events"]
    Security["Security Analyzer"]
    Condenser["Context Condenser"]

    Agent -->|Uses| LLM
    LLM -->|Records| Events
    Security -.->|Optional| LLM
    Condenser -.->|Optional| LLM
    Conversation -->|Provides context| Agent

    style LLM fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px
    style Agent fill:#e8f3ff,stroke:#2b6cb0,stroke-width:2px
    style Events fill:#fff4df,stroke:#b7791f,stroke-width:2px

Relationship Characteristics:

  • Agent → LLM: Agent uses LLM for reasoning and tool calls
  • LLM → Events: LLM requests/responses recorded as events
  • Security → LLM: Optional security analyzer can use separate LLM
  • Condenser → LLM: Optional context condenser can use separate LLM
  • Configuration: LLM configured independently, passed to agent
  • Telemetry: LLM metrics flow through event system to UI/logging

See Also


Let the agent pick the best saved LLM profile for the task at hand with the built-in route_task_to_model tool.

A ready-to-run example is available here!

The built-in route_task_to_model tool (ClassifyAndSwitchLLMTool) lets an agent switch models mid-conversation based on what the current task looks like. When the agent calls the tool, a lightweight classifier LLM inspects the recent conversation, picks the most suitable saved LLM profile, and switches the conversation to that profile before the agent continues. Conversation history and combined usage metrics are preserved across the switch.

This differs from Model Routing, where a Router decides per request based on fixed rules. Here the decision is made by an LLM, and the agent decides when to ask for it.

How It Works

  1. Save the candidate LLM profiles. The tool switches profiles by name, so every model it can choose must exist in the LLMProfileStore, or be supplied inline (see below).
  2. Define a meta-profile. A MetaProfile names the classifier profile and describes how to map a task to a target profile.
  3. Enable the tool on the agent. Set enable_classify_and_switch_llm_tool=True on OpenHandsAgentSettings and point active_meta_profile (or meta_profile) at the routing configuration.
  4. Let the agent call it. The agent starts on its configured LLM and switches only when it invokes route_task_to_model.

Meta-Profile Shapes

A MetaProfile supports two mutually exclusive routing modes.

Structured classes

Provide a fixed set of task categories. The classifier is shown the categories and returns the number of the best match; the tool switches to that class's model, which is a saved profile name.

from openhands.sdk.llm.meta_profile_store import MetaProfile, MetaProfileClass

structured_meta = MetaProfile(
    classifier_model="example-router-classifier",
    classes=[
        MetaProfileClass(
            description="Simple lookups, small edits, formatting",
            model="example-router-cheap",
        ),
        MetaProfileClass(
            description="Multi-file reasoning, debugging, architecture",
            model="example-router-strong",
        ),
    ],
)

Direct prompt

Provide a free-form prompt_template instead of classes. The template must contain {{ instance_text }} (the recent conversation) and may contain {{ model_table }} (the model_table text). The classifier is expected to return JSON with a model field naming a saved profile:

{"model": "example-router-strong", "reason": "multi-file debugging"}

The returned name is matched case-insensitively against saved profile names, and the canonical profile name is used for the switch.

direct_meta = MetaProfile(
    classifier_model="example-router-classifier",
    prompt_template=(
        "Pick the best model for the task below.\n\n"
        "{{ model_table }}\n\n"
        "Task:\n{{ instance_text }}\n\n"
        'Return ONLY JSON: {"model": "<exact profile name>", "reason": "<short>"}'
    ),
    model_table=(
        "- example-router-cheap: fast and cheap, good for simple tasks\n"
        "- example-router-strong: slower and stronger, good for hard tasks"
    ),
)

Where Meta-Profiles Come From

Meta-profiles are stored by name in ~/.openhands/meta-profiles and managed with MetaProfileStore. The tool resolves its configuration lazily, at invocation time, in this order:

  1. If active_meta_profile is set, the store is authoritative and the meta-profile is loaded by name.
  2. If the store cannot resolve that name, or no name is set, the inline meta_profile from the agent settings is used. Cloud runtimes rely on this because their ephemeral filesystem has no meta-profile store.
  3. If neither applies, the alphabetically first meta-profile in the store is used.

Target and classifier profiles are likewise loaded from the LLMProfileStore, or from the meta_profile_llms map on the settings when supplied inline.

If the classifier returns no usable answer, or names a profile that does not exist, the tool returns an error observation instead of silently routing to a default model. The agent sees the failure and can retry.

Enabling the Tool

Wire everything through OpenHandsAgentSettings:

from openhands.sdk import Conversation, OpenHandsAgentSettings
from openhands.sdk.llm.llm_profile_store import LLMProfileStore
from openhands.tools.preset.default import register_default_tools

profile_store = LLMProfileStore()
register_default_tools(enable_browser=False)

settings = OpenHandsAgentSettings(
    llm=profile_store.load("example-router-default"),
    enable_classify_and_switch_llm_tool=True,
    active_meta_profile="structured",
    meta_profile=structured_meta,
)
agent = settings.create_agent()
conversation = Conversation(agent=agent, workspace=".")

create_agent() defaults the agent's toolset to terminal, file_editor, and task_tracker by name. Their implementations live in openhands-tools and are registered only when imported, so call register_default_tools() (or import the tool modules you need) before creating the agent. Passing tools=[] instead builds a bare agent that has only the built-in tools plus route_task_to_model.

Ready-to-run Example

This example is available on GitHub: examples/01_standalone_sdk/59_route_task_to_model.py

Save a set of profiles, define a structured meta-profile, enable the tool, and ask the agent to route the task:

"""Route each task to the best LLM with the built-in route_task_to_model tool.

The agent starts on a default profile. When it calls the ``route_task_to_model``
tool (a.k.a. ``ClassifyAndSwitchLLMTool``), a lightweight classifier LLM inspects
the recent conversation, picks the most suitable saved LLM profile for the task,
and switches the conversation to that profile before the agent continues.

This example shows the two meta-profile shapes the tool supports:

1. **Structured classes** — a fixed set of ``{description, model}`` rows; the
   classifier returns a class index.
2. **Direct prompt** — a ``prompt_template`` rendered with ``{{ instance_text }}``
   and ``{{ model_table }}``; the classifier returns the model name directly.

Both modes require the target models to exist as saved LLM profiles (the tool
switches to them by name) or to be supplied inline via ``meta_profile_llms``.

Usage:
    LLM_API_KEY=... LLM_BASE_URL=https://llm-proxy.app.all-hands.dev \
        uv run python examples/01_standalone_sdk/59_route_task_to_model.py
"""

import os

from pydantic import SecretStr

from openhands.sdk import LLM, Conversation, OpenHandsAgentSettings
from openhands.sdk.llm.llm_profile_store import LLMProfileStore
from openhands.sdk.llm.meta_profile_store import MetaProfile, MetaProfileClass
from openhands.tools.preset.default import register_default_tools

DEFAULT_BASE_URL = "https://llm-proxy.app.all-hands.dev"

# Saved profile names. The route_task_to_model tool switches the conversation
# to one of these by name, so each must exist in the LLMProfileStore below.
DEFAULT_PROFILE = "example-router-default"
CHEAP_PROFILE = "example-router-cheap"
STRONG_PROFILE = "example-router-strong"
CLASSIFIER_PROFILE = "example-router-classifier"

CHEAP_MODEL = "openai/gpt-5.5"
STRONG_MODEL = "openai/prod/claude-sonnet-4-5-20250929"

api_key = os.getenv("LLM_API_KEY")
assert api_key is not None, "LLM_API_KEY environment variable is not set."
base_url = os.getenv("LLM_BASE_URL", DEFAULT_BASE_URL)

# ── 1. Save the LLM profiles the router will choose between ──────────────
profile_store = LLMProfileStore()
for name, model, usage_id in [
    (DEFAULT_PROFILE, CHEAP_MODEL, "router-default"),
    (CHEAP_PROFILE, CHEAP_MODEL, "router-cheap"),
    (STRONG_PROFILE, STRONG_MODEL, "router-strong"),
    (CLASSIFIER_PROFILE, CHEAP_MODEL, "router-classifier"),
]:
    profile_store.save(
        name,
        LLM(
            model=model,
            api_key=SecretStr(api_key),
            base_url=base_url,
            usage_id=usage_id,
        ),
        include_secrets=True,
    )

try:
    # ── 2. Define a meta-profile: structured classes ──────────────────────
    # The classifier returns a 1-based class index; ``model`` is the saved
    # profile name to switch to. ``classifier_model`` is itself a saved
    # profile name used to run the classification call.
    structured_meta = MetaProfile(
        classifier_model=CLASSIFIER_PROFILE,
        classes=[
            MetaProfileClass(
                description="Simple lookups, small edits, formatting",
                model=CHEAP_PROFILE,
            ),
            MetaProfileClass(
                description="Multi-file reasoning, debugging, architecture",
                model=STRONG_PROFILE,
            ),
        ],
    )

    # ── 3. Build the agent via OpenHandsAgentSettings ─────────────────────
    # ``create_agent()`` defaults to the standard exec tools (terminal,
    # file_editor, task_tracker) by name; their implementations live in
    # ``openhands-tools`` and must be registered before the agent initializes.
    register_default_tools(enable_browser=False)

    # Enabling the tool + setting the active meta-profile name is all it takes
    # to wire route_task_to_model into the agent. The agent starts on the
    # default profile and switches only when it calls the tool.
    settings = OpenHandsAgentSettings(
        llm=profile_store.load(DEFAULT_PROFILE),
        enable_classify_and_switch_llm_tool=True,
        active_meta_profile="structured",
        meta_profile=structured_meta,
    )
    agent = settings.create_agent()

    conversation = Conversation(agent=agent, workspace=os.getcwd())
    print(f"Starting model: {conversation.agent.llm.model}")

    conversation.send_message(
        "Call the route_task_to_model tool now. After it returns, answer in one "
        "short sentence naming the model the tool switched to."
    )
    conversation.run()

    print(f"Active model after routing: {conversation.agent.llm.model}")

    for usage_id, metrics in conversation.state.stats.usage_to_metrics.items():
        print(f"  [{usage_id}] cost=${metrics.accumulated_cost:.6f}")
    combined = conversation.state.stats.get_combined_metrics()
    print(f"Total cost: ${combined.accumulated_cost:.6f}")
    print(f"EXAMPLE_COST: {combined.accumulated_cost}")

    # ── 4. (Info) Direct-prompt meta-profile shape ────────────────────────
    # Instead of fixed classes, you give the classifier a free-form prompt
    # template and a model table. The classifier returns the model name
    # directly as JSON ``{"model": "<name>", "reason": "..."}``. This is the
    # shape used by the Pareto prompt meta-profiles.
    direct_meta = MetaProfile(
        classifier_model=CLASSIFIER_PROFILE,
        prompt_template=(
            "Pick the best model for the task below.\n\n"
            "{{ model_table }}\n\n"
            "Task:\n{{ instance_text }}\n\n"
            'Return ONLY JSON: {"model": "<exact profile name>", "reason": "<short>"}'
        ),
        model_table=(
            f"- {CHEAP_PROFILE}: fast and cheap, good for simple tasks\n"
            f"- {STRONG_PROFILE}: slower and stronger, good for hard tasks"
        ),
    )
    print()
    print("Direct-prompt meta-profile (not executed here):")
    print(direct_meta.model_dump_json(indent=2))

finally:
    for name in [
        DEFAULT_PROFILE,
        CHEAP_PROFILE,
        STRONG_PROFILE,
        CLASSIFIER_PROFILE,
    ]:
        profile_store.delete(name)

You can run the example code as-is.

The model name should follow the LiteLLM convention: provider/model_name (e.g., anthropic/claude-sonnet-4-5-20250929, openai/gpt-4o). The LLM_API_KEY should be the API key for your chosen provider.

ChatGPT Plus/Pro subscribers: You can use LLM.subscription_login() to authenticate with your ChatGPT account and access Codex models without consuming API credits. See the LLM Subscriptions guide for details.

Next Steps