> This page is for version Dev.
> For other versions, use one of these documentation indexes:
> - Latest (v0.4.0) (default): https://docs.nvidia.com/nemo/switchyard/latest/llms.txt
> - Dev: https://docs.nvidia.com/nemo/switchyard/dev/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/nemo/switchyard/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.nvidia.com/nemo/switchyard/_mcp/server.

# Host Integration

Add libsy where your gateway or agent harness chooses and calls a model. Your
application keeps its transport, credentials, and lifecycle.

Start with the **[Rust quickstart](/nemo/switchyard/dev/get-started/getting-started)** for a working example.
Use **[Mechanics of Libsy](/nemo/switchyard/dev/integrate-switchyard/mechanics-of-libsy)** for execution and
**[Switchyard Protocols](/nemo/switchyard/dev/integrate-switchyard/switchyard-protocols/switchyard-protocols)** for data conversion. This page
covers the responsibilities specific to your host.

## Choose the integration boundary \[#choose-the-integration-boundary]

| Host          | Insert routing here                                                     | Preserve from the existing application                                                                   |
| ------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| Gateway       | After request admission and input decoding, before model dispatch.      | Authentication, tenant isolation, budgets, model inventory, provider credentials, and response delivery. |
| Agent harness | Before each model turn, after assembling conversation and tool history. | Tool execution, task state, model clients, conversation storage, and the agent loop.                     |

## Host responsibilities \[#host-responsibilities]

**Dispatch every requested call.** Apply your credentials, budgets, and access
policy to routing-time judge calls as well as answer calls. Send internal calls
through model dispatch without entering the same router again. Supply only
models your host can reach. See [call handling](/nemo/switchyard/dev/integrate-switchyard/mechanics-of-libsy#read-the-next-step)
and [final-outcome handling](/nemo/switchyard/dev/integrate-switchyard/mechanics-of-libsy#stepdone).

**Keep history and state.** Supply the tool history required by the algorithm;
provider continuation IDs alone can hide that evidence. Scope session IDs to
the tenant and conversation. Reuse algorithm instances when they retain session
decisions, and decide how your host handles concurrent turns and multiple
processes. State behavior is algorithm-specific; see [Composite sessions](/nemo/switchyard/dev/routing/algorithms/composite-routing#sessions)
and the [Plan/Execute history requirement](/nemo/switchyard/dev/routing/algorithms/execution-stage-router#plan-and-execute).

**Observe the complete run.** Include judge calls and final model work in your
host's observations. Configure telemetry collection in your application and
instrument model I/O performed by your own clients. See the
[OpenTelemetry reference](/nemo/switchyard/dev/reference/opentelemetry#host-setup).

For existing integrations, check [NeMo Relay](/nemo/switchyard/dev/integrate-switchyard/gateways/nemo-relay)
or the [LiteLLM compatibility notes](https://github.com/NVIDIA-NeMo/Switchyard/blob/bc716b420f3f76a77c0e93dde08c14b97ec2120f/examples/litellm/README.md#supported-algorithm-semantics).
The experimental LiteLLM plugin supports decision-only routing and cannot serve
intermediate model calls.

## Serve routing-time calls \[#serve-routing-time-calls]

Use your existing client as shown in the [Step loop](/nemo/switchyard/dev/integrate-switchyard/mechanics-of-libsy#read-the-next-step).
The shared client traits below are optional.

#### Optional: adapt the shared client traits

### Rust API \[#rust-api]

These adapters use the asynchronous reply API in Switchyard v0.4.0.
Follow the [Rust quickstart](/nemo/switchyard/dev/get-started/getting-started#install) for dependencies.

When using
[`RoutedLlmClient`](https://nvidia-nemo.github.io/Switchyard/rust/switchyard_protocol/client/trait.RoutedLlmClient.html)
or [`RoutedDecisionClient`](https://nvidia-nemo.github.io/Switchyard/rust/switchyard_protocol/client/trait.RoutedDecisionClient.html),
adapt errors to [`LibsyError`](https://nvidia-nemo.github.io/Switchyard/rust/switchyard_libsy/enum.LibsyError.html):

```rust
use switchyard_libsy::{CallDecision, CallModel, LibsyError, Result};
use switchyard_protocol::{RoutedDecisionClient, RoutedLlmClient};

async fn serve(call: CallModel, client: &dyn RoutedLlmClient) -> Result<()> {
    let request = call.request.clone();
    let model = call.models[0].clone();
    call.respond(async move {
        client.call(request).await.map_err(|error| LibsyError::client_call(model, error))
    }).await
}

async fn serve_decision(call: CallDecision, client: &dyn RoutedDecisionClient) -> Result<()> {
    let request = call.request.clone();
    let model = call.model.clone();
    call.respond(async move {
        client.call(request).await.map_err(|error| LibsyError::client_call(model, error))
    }).await
}
```

## Python bindings \[#python-bindings]

The bindings run the same Rust algorithms. Install `nemo-switchyard==0.4.0`
for the asynchronous callbacks, target requirements, and cleanup described below.
See the complete [Python host example](https://github.com/NVIDIA-NeMo/Switchyard/blob/bc716b420f3f76a77c0e93dde08c14b97ec2120f/examples/libsy.py).

#### Python setup, callbacks, and metadata

With Python 3.10+ and [uv](https://docs.astral.sh/uv/getting-started/installation/),
create a project and install the released package:

```bash
uv init --bare switchyard-python-demo
cd switchyard-python-demo
uv add "nemo-switchyard==0.4.0"
```

Save as `route.py`:

```python
import asyncio
from switchyard.libsy import Step, algorithms
from switchyard.translation import TranslationEngine, WireFormat

async def main():
    engine = TranslationEngine()
    oai_chat_request = {"messages": [{"role": "user", "content": "Hello"}]}
    decoded = engine.decode_request(WireFormat.OPENAI_CHAT, oai_chat_request)
    request = decoded["request"]
    if decoded["diagnostics"]:
        print(f"Translation diagnostics: {decoded['diagnostics']}")

    router = algorithms.stage_router(
        picker="efficient_first", confidence_threshold=0.5)
    models = {"efficient": ["Efficient"], "capable": ["Capable"]}
    models["any"] = ["Efficient", "Capable"]

    async for step in router.run_stream(request, models):
        if isinstance(step, Step.Done):
            print("Selected:", step.outcome.selected_model_ids[0])

asyncio.run(main())
```

`uv run route.py` prints `Selected: Efficient` without making a network call.

### Target requirements \[#target-requirements]

With the v0.4.0 bindings, load deployment TOML that declares target
labels and route eligibility. Build once and reuse the returned handles:

```python
from switchyard.libsy import AlgorithmFactory

routes = AlgorithmFactory.from_toml(toml).build_configured()
coding = routes["switchyard/coding"]
targets = coding.target_models()

steps = coding.run_stream(
    request,
    required_labels=["private", "customer_data"],
    task_id=trusted_task_id,
)
```

For each `Step.CallModel`, resolve the returned target before calling your client.
Here `clients` is supplied by the gateway and keyed by the TOML client aliases,
not a new Switchyard interface. Its clients follow the
[Python host example](https://github.com/NVIDIA-NeMo/Switchyard/blob/bc716b420f3f76a77c0e93dde08c14b97ec2120f/examples/libsy.py): they accept a normalized request
and provider model ID, and return `LlmResponse.Agg` or `LlmResponse.Stream`.

```python
async def serve_model(call):
    target = targets[call.models[0]]
    client = clients[target["client"]]
    await call.respond(client.call(call.request, target["id"]))
```

Use the first routing-time candidate and pass client failures back to Switchyard.
Typed Decision calls use `targets[call.model]` and their own Decision handler.
For a final answer candidate, use `targets[outcome.selected_model_ids[0]]`.
The lookup contains all possible targets, not the eligible pool for this request;
use only keys returned by calls and outcomes. `build()` handles reject this lookup.

The host supplies the assessment and an authorized task ID. An explicit task ID
overrides a task ID from headers. Omitted labels mean no assessment; `[]` supplies
no new requirements. In task scope, earlier requirements remain in effect.
Invalid requirements or missing approved targets fail before any routing call.

Consume `steps` through the same model and Decision call handlers. Switchyard
does not create provider clients or read their credentials. The host owns target
prompts, provider settings and transport, and must keep answer attempts and
fallbacks within the returned candidates. Existing `build()` handles do not
accept target requirements. Per-run libsy state is not carried between Python calls.

### Concurrent calls and cancellation \[#concurrent-calls-and-cancellation]

The client coroutine returns `LlmResponse.Agg` or `LlmResponse.Stream`.
Pass the coroutine itself to `respond`:

```python
await call.respond(client.call(call.request, call.models[0]))
```

`respond` cancels and awaits the supplied provider work before returning.
For concurrent algorithms, create handler tasks and cancel and await the remaining
handlers when the run ends, as in the [Python host example](https://github.com/NVIDIA-NeMo/Switchyard/blob/bc716b420f3f76a77c0e93dde08c14b97ec2120f/examples/libsy.py).
Awaiting one handler at a time serializes execution. `call.fail(error)` is also
awaitable; decision calls use the same reply pattern.

For the shared cancellation behavior and upstream limits, see
[Mechanics](/nemo/switchyard/dev/integrate-switchyard/mechanics-of-libsy#control-how-work-runs).

### Metadata and telemetry \[#metadata-and-telemetry]

After checking that `outcome.metadata` is present, read its `outcome_id`,
`algorithm`, and `evidence` attributes. Evidence is a normal Python value, usually
a dictionary; algorithms without evidence return `None`. See the
[OpenTelemetry reference](/nemo/switchyard/dev/reference/opentelemetry) for signals and export setup.