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

# Model

The model interprets input, selects tools, and generates responses. Agents read global model settings from environment variables or `config.yaml` by default. Use `Agent` parameters to give individual agents their own models, endpoints, and credentials

## Set the model for a single agent

Complete [installation](https://docs.veadk.xyz/productions/veadk/preview/en/get-started/installation.md), then select one platform configuration below. Enable the model in the corresponding account, or replace its name with an accessible model or inference endpoint

> [tab] Volcengine
>
> ```bash lines theme={null}
> export CLOUD_PROVIDER="volcengine"
> export MODEL_AGENT_NAME="doubao-seed-2-1-pro-260628"
> export MODEL_AGENT_API_BASE="https://ark.cn-beijing.volces.com/api/v3/"
> export MODEL_AGENT_API_KEY="<model-api-key>"
> ```

> [tab] BytePlus
>
> ```bash lines theme={null}
> export CLOUD_PROVIDER="byteplus"
> export MODEL_AGENT_NAME="seed-2-0-lite-260228"
> export MODEL_AGENT_API_BASE="https://ark.ap-southeast.bytepluses.com/api/v3"
> export MODEL_AGENT_API_KEY="<model-api-key>"
> ```

Run this script from the same terminal:

```python main.py lines theme={null}
import asyncio
import os
from veadk import Agent, Runner

agent = Agent(
    name="assistant",
    model_name=os.environ["MODEL_AGENT_NAME"],
    model_provider="openai",
    model_api_base=os.environ["MODEL_AGENT_API_BASE"],
    model_api_key=os.environ["MODEL_AGENT_API_KEY"],
)

async def main():
    print(await Runner(agent=agent).run(
        messages="Explain what an AI agent does in one paragraph.",
        session_id="model-demo",
    ))

if __name__ == "__main__":
    asyncio.run(main())
```

Run `python main.py` to print a response. If all agents share the settings above, `Agent(name="assistant")` is sufficient

### Model parameters and global settings

Explicit constructor arguments override their corresponding global settings. Unspecified fields retain global values. VeADK searches for `config.yaml` from the current directory upward, and existing environment variables take precedence over matching file settings. See [quickstart](https://docs.veadk.xyz/productions/veadk/preview/en/get-started/quickstart.md) for YAML configuration

| Parameter | Type | Default | Environment variable or behavior |
| :- | :- | :- | :- |
| `model_name` | `str \| list[str]` | Platform default model | `MODEL_AGENT_NAME`; lists define fallbacks |
| `model_provider` | `str` | `"openai"` | `MODEL_AGENT_PROVIDER`; LiteLLM provider identifier, with `openai` used for OpenAI-compatible Ark endpoints |
| `model_api_base` | `str` | Platform default endpoint | `MODEL_AGENT_API_BASE` |
| `model_api_key` | `str` | `""`, resolved at initialization | `MODEL_AGENT_API_KEY` |
| `model_api_key_name` | `str` | `""` | `MODEL_AGENT_API_KEY_NAME`; looks up an Ark key by name |
| `model_fallbacks` | `list[str \| ModelFallbackEndpoint]` | `[]` | Additional fallback models or endpoints; matching dictionaries are also accepted |
| `model_extra_config` | `dict` | `{}` | Additional model request settings; supported fields depend on the API |
| `enable_responses` | `bool` | `False` | Enables the Ark Responses API |
| `enable_responses_cache` | `bool` | `True` | Controls caching in Responses mode |
| `query_routing` | `bool \| dict \| QueryRoutingConfig` | `None` | Query routing between cheap and strong models. `None` auto-loads the `query_routing` block from `config.yaml`; `False` disables it. See [Query routing](#query-routing). |

Without global overrides, Volcengine uses `doubao-seed-2-1-pro-260628` at `https://ark.cn-beijing.volces.com/api/v3/`. With `CLOUD_PROVIDER=byteplus`, the defaults are `seed-2-0-lite-260228` and `https://ark.ap-southeast.bytepluses.com/api/v3`. Check existing `MODEL_AGENT_*` variables when switching platforms so settings from the previous platform are not retained

### Resolve an API key by name

Key precedence is: nonempty `model_api_key`, `MODEL_AGENT_API_KEY`, a lookup using `model_api_key_name` or `MODEL_AGENT_API_KEY_NAME`, then the account's default key lookup

```bash lines theme={null}
export MODEL_AGENT_API_KEY_NAME="production-key"
```

Name-based lookup requires account credentials permitted to read Ark API keys. The name is not the secret value. An existing key value takes precedence over lookup. This feature is available from VeADK 1.0.2

### Rate-limit retries

With the default `adk` runtime, Responses disabled, and no custom `model`, VeADK retries an HTTP 429 once if no model response has been emitted. A valid numeric `Retry-After` controls the delay, capped at 2 seconds; missing or invalid values use 0.5 seconds. This retry layer does not replay a request after output has started

## Configure fallback models

Set `BACKUP_MODEL_NAME` in addition to the earlier settings, then replace the `agent` definition with:

```python lines theme={null}
agent = Agent(
    name="assistant",
    model_name=[os.environ["MODEL_AGENT_NAME"], os.environ["BACKUP_MODEL_NAME"]],
)
```

The first entry is primary; subsequent entries are fallback candidates sharing the provider, endpoint, and credentials. You can also append same-provider candidates with `model_fallbacks=["backup-model-name"]`. When both are configured, candidates from `model_name` precede those from `model_fallbacks`

Same-provider name fallbacks are available for the default model API and Responses API. Every candidate must support the request's tools, input modalities, and output format. Fallbacks handle request failures; low-quality answers do not automatically trigger a switch

## Configure cross-provider fallback models

Use `ModelFallbackEndpoint` when a backup has a different provider, endpoint, or credentials. In addition to the primary settings, set `BACKUP_MODEL_NAME`, `BACKUP_MODEL_PROVIDER`, `BACKUP_MODEL_API_BASE`, and `BACKUP_MODEL_API_KEY` to the backup service's actual values

```python fallback.py lines theme={null}
import asyncio
import os
from veadk import Agent, ModelFallbackEndpoint, Runner

agent = Agent(
    name="assistant",
    model_fallbacks=[
        ModelFallbackEndpoint(
            model_name=os.environ["BACKUP_MODEL_NAME"],
            model_provider=os.environ["BACKUP_MODEL_PROVIDER"],
            model_api_base=os.environ["BACKUP_MODEL_API_BASE"],
            model_api_key_env="BACKUP_MODEL_API_KEY",
        ),
    ],
)

async def main():
    print(await Runner(agent=agent).run(
        messages="Explain model fallback briefly.", session_id="fallback-demo"
    ))

if __name__ == "__main__":
    asyncio.run(main())
```

### `ModelFallbackEndpoint` parameters

| Parameter | Type | Default | Description |
| :- | :- | :- | :- |
| `model_name` | `str` | Required | Model name; uses the primary provider when neither a prefix nor provider is supplied |
| `model_provider` | `str \| None` | `None` | Backup provider; a different provider does not inherit primary credentials or endpoint |
| `model_api_base` | `str \| None` | `None` | Backup endpoint; when omitted across providers, LiteLLM uses a provider default if available |
| `model_api_key` | `str \| None` | `None` | Backup key value; takes precedence over `model_api_key_env` |
| `model_api_key_env` | `str \| None` | `None` | Environment variable containing the key, read when creating the agent; if missing, LiteLLM tries provider-default credentials |
| `model_extra_config` | `dict` | `{}` | Backup request settings; explicitly supplied `extra_headers` and `extra_body` dictionaries merge by key with their primary counterparts, with backup values winning; nested objects are not recursively merged |

Dictionaries can replace endpoint objects. Supported aliases are `model`, `provider`, `api_base` or `base_url`, `api_key`, `api_key_env`, and `extra_config`. Explicitly specify the provider, endpoint, and credentials across providers to avoid inheriting unsuitable settings

### Fallback limitations

* `enable_responses=True` accepts only same-provider string fallbacks; endpoint objects or dictionaries fail at initialization
* `codex` and `piagent` ignore fallback chains; use `adk` when fallbacks are required. See [runtime](https://docs.veadk.xyz/productions/veadk/preview/en/components/agent/runtime.md#switch-the-execution-backend)
* With a custom `model` object in the default runtime, `model_fallbacks` is ignored; configure fallbacks on that object instead

## Query routing

SystemOne selects a model once at the start of each user turn, using the effective history, instructions, tool declarations and candidate capabilities. The selection remains fixed through tool loops, nested AgentTool calls and sub-agent transfers. The next user turn is classified again. Routing is disabled unless explicitly configured; an unconfigured project retains its original execution behavior.

> [!WARNING]
>
> Query routing is only supported by the `adk` runtime. When routing is enabled, `model_name` list fallbacks and `model_fallbacks` must be removed; the two cannot be used together.

### Configuration

Add the block to `config.yaml` in the project root:

```yaml title="config.yaml" theme={null}
decision:
  model: doubao-seed-2-1-lite-260915

query_routing:
  simple_models:
    - doubao-seed-2-1-lite-260915
  # strong_model: kimi-k3-1-pro-261024  # optional; defaults to the Agent's model_name
  mode: shadow  # observe first; set enforce to execute routing
  decision_timeout: 2.0
  questions:
    - question: Does the answer need up-to-date, real-time information?
      threshold: 0.2
```

The Agent discovers `config.yaml` in the current working directory and its parents at startup, so no extra code is needed:

```python title="agent.py" theme={null}
agent = Agent(model_name="kimi-k3-1-pro-261024")
```

You can also pass a mapping directly with `Agent(query_routing={...})`, or disable routing explicitly with `query_routing=False`.

### Parameters

| Field | Type | Default | Description |
| :- | :- | :- | :- |
| `simple_models` | `list[str \| dict]` | required | Low-cost models, at least one. The first model that supports the current request is selected in list order. A string is shorthand for a mapping with only `name`. |
| `strong_model` | `str` | Agent's `model_name` | Strong model name. When it differs from the Agent's primary model, it is built separately with the same connection settings. |
| `mode` | `"enforce" \| "shadow"` | `"shadow"` | `shadow` only records routing decisions and always uses the strong model, so you can observe results before switching. |
| `decision_timeout` | `float` | `2.0` | Per-classification timeout in seconds, in `(0, 30]`. A timeout routes to the strong model. |
| `builtin_thresholds` | `dict[str, float]` | `{}` | Optional overrides for built-in question thresholds, each in `[0, 1]`. Calibrate against representative queries before enforcing. |
| `questions` | `list[str \| dict]` | `[]` | Custom questions appended to the four built-in questions. A string is shorthand for `{question: ...}`. |

### Shared decision connection

The root `decision` block is shared by query routing and content safety. It enables neither feature. `Agent(decision=DecisionConfig(...))` supplies explicit immutable connection values; each consumer owns its client and questions. Configure connections only here, not inside either feature.

| Field | Required | Default / rule |
| :- | :- | :- |
| `decision.api_url` | No | Derived from the Agent's Ark endpoint as `/api/v1/systemone`; required for a custom gateway. |
| `decision.api_key` | No | Reuses the Agent's Ark key; required for a non-Ark decision endpoint. |
| `decision.model` | No | `doubao-seed-2-1-lite-260915`; the model used for SystemOne decisions. |

`DECISION_API_URL`, `DECISION_API_KEY`, and `DECISION_MODEL` override YAML. Overriding a configured destination requires its own `DECISION_API_KEY`. Explicit `DecisionConfig` values bypass file/environment loading. Questions, thresholds, and `decision_timeout` belong to each feature; changing routing policy does not change content-safety policy.

```python theme={null}
from veadk import Agent
from veadk.decision import DecisionConfig

agent = Agent(
    name="router",
    decision=DecisionConfig(model="doubao-seed-2-1-lite-260915"),
    query_routing={"simple_models": ["doubao-seed-2-1-lite-260915"]},
)
```

### Candidate model capabilities

Each `simple_models` entry can declare capabilities; anything not declared is treated as unsupported:

| Capability field | Type | Default | Description |
| :- | :- | :- | :- |
| `name` | `str` | required | Model name; `model` and `model_name` are accepted aliases. |
| `provider` | `str` | Agent provider | LiteLLM provider prefix for unqualified names. |
| `api` | `str` | Agent protocol | `chat_completions` or `responses` (Ark Responses adapter). |
| `api_base` | `str` | Agent endpoint | Independent endpoint. A different endpoint requires an explicit credential. |
| `api_key_env` / `api_key` | `str` | Agent credential | Environment variable name or secret value; mutually exclusive. Prefer `api_key_env`. |
| `extra_config` | `dict` | `{}` | Provider options. Cannot override routing, history or connection fields. Independent endpoints do not inherit the Agent's provider options. |
| `supports_tools` | `bool` | `False` | Whether the model supports tool calls. |
| `capability_description` | `str \| None` | `None` | Optional, 1–2000 characters. Describe validated task suitability, limitations, and tool dependencies to SystemOne. This does not override instructions, capability flags, or thresholds, and does not guarantee quality. Do not include credentials. |
| `supports_media` | `bool` | `False` | Whether the model supports image, audio, video, or file input. |
| `supports_structured_output` | `bool` | `False` | Whether the model supports structured output. |
| `max_context_chars` | `int` | `32000` | Character budget including instructions, tools, schemas and history; media uses an estimate. This is not a tokenizer-based context-window guarantee. |

### Built-in questions and thresholds

Control questions always use the `noul` type. Four questions are built in:

| Question ID | Default threshold | What it checks |
| :- | :- | :- |
| `is_complex` | `0.5` | Whether reasoning, planning, code or math exceeds the candidate's declared capabilities. |
| `needs_tools` | `0.5` | Whether tool orchestration or recovery exceeds the candidate's declared capabilities. Supported simple tool calls are not automatically escalated. |
| `needs_long_context` | `0.5` | Whether the current task requires global analysis across a long history or multiple documents. Extracting stated facts from a few recent messages is not long-context analysis. |
| `is_high_stakes` | `0.05` | Whether the current task asks for high-risk medical, legal, financial, or safety conclusions, or irreversible actions. A past high-risk topic does not automatically escalate an ordinary factual extraction; follow-up requests for related advice remain high-risk. |

The default thresholds are `0.5` for complex reasoning, tool orchestration and long context, and `0.05` for high stakes. Explicit `builtin_thresholds` values take precedence; custom questions still default to `0.15` when their threshold is omitted. A threshold bounds the SystemOne question probability, not the task error rate. These defaults apply only when routing is enabled; `shadow` mode still executes with the strong model.

A custom question only needs `question` and `threshold`; its ID is generated as `custom_1`, `custom_2`, and so on. Built-in IDs are reserved and cannot be overridden. Every question returns a probability from `0` to `1`; **the simple model is used only when all probabilities are at or below their thresholds**. Any probability above its threshold, a missing or invalid answer, a Decision timeout, or a Decision error routes the request to the strong model. Incomplete decision input, unsupported media or unavailable dynamic tool declarations also select the strong model. Effective history is never silently truncated to enable a downgrade. After selection, a provider failure propagates and never triggers a model switch. A transient failure (timeout, connection error, 429, or 5xx) excludes the simple model from selection for a 60-second cooldown, so subsequent turns use the strong model until it expires. Other 4xx responses are request-specific and do not open the cooldown. Late capability growth fails explicitly.

### Tool argument validation in enforce mode

In enforce mode, tool arguments are validated against the tool's declared schema before execution. Unambiguous decimal integer strings can be converted losslessly when the schema explicitly requires an integer; fractions, booleans, and ambiguous formats are not coerced to integers. Invalid arguments return a structured error without original argument values for correction by the model already selected for this turn. At most two correction responses are allowed across the root turn, including nested agents; further invalid calls fail explicitly. Tools that have already executed are not automatically retried. Tools without parameter schemas retain their existing behavior. Validator-infrastructure failures, such as a schema that cannot be built or a non-local `$ref`/`$dynamicRef`, are logged and skip validation for that invocation instead of blocking the tool call. Disabled routing, shadow mode, and turns that select the strong model preserve the original tool argument behavior.

### Responses continuation and routing

Responses continuation is reused only when the target, endpoint, identity, request configuration and effective history match. Model changes, including A → B → A, rebuild the chain from full business history; expired IDs retry with that history on the same model. Provider-specific reasoning and signatures are not replayed to a different target. `enable_responses_cache=False` always sends full history. Server-side caching still requires the provider's cache-service entitlement; Responses continuation can also use `store=True` with `extra_body={"caching": {"type": "disabled"}}`.

### Nested agents and lifecycle

Nested AgentTool calls retain separate sessions and inherit one root decision. Native ADK LlmAgent and standard sub-agent workflows are adapted on owned copies; custom native LlmAgent subclasses must implement turn binding explicitly. Resume uses the decision persisted under a per-router-agent key; independently configured routed agents reached by native transfer in the same invocation each keep their own record instead of overwriting one another, and a configuration change to the same routed agent still fails explicitly. The decision HTTP client is closed with the Agent/Runner lifecycle instead of being rebuilt after every continuation. Live bidirectional execution and external runtimes are outside this ADK text-turn contract. Concurrent execution of the same session still requires application-level serialization; cross-process simultaneous classification is not a distributed lock.

Model events expose `veadk_query_routing` metadata with root turn ID, route, model and target digest. The decision event also includes reason, latency and reported input tokens. Credentials and raw query text are excluded.

### Full example

```python title="agent.py" theme={null}
agent = Agent(
    model_name="strong-model",
    query_routing={
        "mode": "enforce",
        "simple_models": [{
            "name": "small-model",
            "provider": "openai",
            "api": "chat_completions",
            "api_base": "https://models.example.com/v1",
            "api_key_env": "SMALL_MODEL_API_KEY",
            "supports_tools": True,
        }],
    },
)
```

## Responses API

The Responses API supports conversation continuation, multimodal input, and structured output. Confirm that the model and endpoint support the Ark Responses protocol. An OpenAI-compatible endpoint does not automatically support every feature described here

### Enable

Requires `google-adk>=1.34.0`. After configuring the model, set `Agent(enable_responses=True)`; the feature is disabled by default. For BytePlus, select an available model and endpoint that explicitly support the required capabilities; the flag alone does not add support

### Multimodal input

`FileData.file_uri` accepts the following sources. Set `mime_type` to match the content:

| Source | Format | Requirement |
| :- | :- | :- |
| Local file | `file:///absolute/path/example.png` | Readable by the process; VeADK uploads it through the Files API |
| Uploaded file | `file_id://file-id` | An accessible Files API resource |
| Network URL | `https://...` | Reachable by the model service |

> [!NOTE]
>
> Local files are sent to the model service. Confirm that they are suitable for upload and check supported formats and size limits before running the example

Save a PNG as `example.png` in the current directory, then run `python image_reader.py`:

```python image_reader.py lines theme={null}
import asyncio
from pathlib import Path
from google.genai import types
from veadk import Agent, Runner

async def main():
    image_path = Path("example.png").resolve(strict=True)
    agent = Agent(name="image_reader", enable_responses=True)
    runner = Runner(agent=agent, app_name="image_demo", user_id="demo-user")
    await runner.session_service.create_session(
        app_name="image_demo", user_id="demo-user", session_id="image-session"
    )
    message = types.Content(role="user", parts=[
        types.Part(text="Describe this image."),
        types.Part(file_data=types.FileData(
            file_uri=image_path.as_uri(), mime_type="image/png"
        )),
    ])
    async for event in runner.run_async(
        user_id="demo-user", session_id="image-session", new_message=message
    ):
        if event.is_final_response() and event.content:
            print("".join(part.text or "" for part in event.content.parts or []))

if __name__ == "__main__":
    asyncio.run(main())
```

Set video metadata on `types.Part`, alongside `file_data`. This fragment can replace the image Part; the service determines the supported frame-rate range:

```python lines theme={null}
video_part = types.Part(
    file_data=types.FileData(
        file_uri=Path("example.mp4").resolve(strict=True).as_uri(),
        mime_type="video/mp4",
    ),
    video_metadata=types.VideoMetadata(fps=1),
)
```

### Configure Ark context management

For models supporting `context_management`, pass settings through `model_extra_config`. This fragment requests removal of older thinking content while retaining the most recent thinking turn:

```python lines theme={null}
agent = Agent(
    enable_responses=True,
    model_extra_config={
        "context_management": {
            "edits": [{
                "type": "clear_thinking",
                "keep": {"type": "thinking_turns", "value": 1},
            }],
        },
    },
)
```

### Context caching

Responses caching is enabled by default. Cache hits depend on the service and request content; reduced usage is not guaranteed. Set `enable_responses_cache=False` to disable it

In event `usage_metadata`, `cached_content_token_count` counts cached input tokens and `prompt_token_count` counts total input tokens. Calculate their ratio only when the latter is greater than zero. Read events with `Runner.run_async` to inspect usage

When `output_schema` is configured, VeADK removes cache settings that conflict with structured output. See [structured output](https://docs.veadk.xyz/productions/veadk/preview/en/components/agent/structured-output.md)


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