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

# Embedding GAIA in a Server

> Run the agent loop as a library inside your own service, with your own tools and model client

GAIA's agent loop was built for a desktop app that acts on files. Inside a server
that answers end users it needs four things set differently. This page is the short
list.

## A minimal chat agent

```python theme={null}
from gaia.agents.base.agent import Agent
from gaia.agents.base.tool_outcome import tool_refusal
from gaia.agents.base.tools import tool


class SupportAgent(Agent):
    def __init__(self, session, **kwargs):
        self.session = session
        super().__init__(
            host="conversation",     # replies go to an end user
            skip_lemonade=True,      # no local model server
            silent_mode=True,        # no console output
            max_steps=8,
            max_output_tokens=1200,  # the real cap, so cut-off prompts name it
            **kwargs,
        )

    def _get_system_prompt(self) -> str:
        return "You answer questions about orders."

    def _register_tools(self) -> None:
        tools = {}

        @tool(registry=tools)
        def get_order(order_number: str) -> dict:
            """Look up an order by its number."""
            if not self.session.verified(order_number):
                return tool_refusal("That order has not been confirmed in this chat.")
            return {"status": "success", "order": self.session.order(order_number)}

        self._instance_tools = tools
```

Build one agent per request. With `skip_lemonade=True` construction takes a few
milliseconds, and nothing is shared between two agents.

## The four settings

| Setting | Why |
| - | - |
| `host="conversation"` | The default host reads the user's message for files to write and sends back a reply that sounds like a plan. A customer who types "the box was dated 10/15" gets neither. The reply is returned exactly as the model wrote it |
| `@tool(registry=...)` + `self._instance_tools` | Keeps each request's tools out of the process-wide registry, so two requests never see each other's |
| `tool_refusal("...")` | A business rule saying no is an answer, not a failure. See [Return Value Patterns](https://amd-gaia.ai/docs/sdk/core/tools.md#pattern-3-refusal) |
| `max_output_tokens` | If your client caps output itself, pass the same number here so GAIA's "your reply was cut off" prompt names the real limit |

GAIA adds one tool of its own, `read_tool_output`, so the model can page through a
result too long to send whole. Pass
`tool_scope=["get_order", "read_tool_output"]` to refuse any call outside that list.

## Reading the result

`process_query()` returns a dict. Decide what to show from `status` and
`stop_reason`, never from the text.

```python theme={null}
result = agent.process_query(user_message)

if result["status"] == "success":
    reply = result["result"]
elif result["stop_reason"] == "model_call":
    reply = hand_off("model unavailable")
else:
    reply = hand_off(result["stop_reason"])
```

> [!WARNING]
>
> Show `result["result"]` to an end user only when `status` is `"success"`. On any
> other status it holds GAIA's own explanation, written for a desktop user, and can
> name tools, step limits or the raw provider error.

| Key | What it holds |
| - | - |
| `status` | `success`, `incomplete`, `failed` or `cancelled` |
| `stop_reason` | Why the turn ended: `answered`, `max_steps`, `deadline`, `model_call`, `output_cap`, `tool_call_format`, `reprompt_budget`, `repeated_calls`, `tool_error`, `completion_gaps`, `cancelled`, `no_answer` |
| `tool_calls` | Every tool call in order: `name`, `args`, `result`, `ran`, `failed`. Check a reply's promises against this before sending it |
| `reprompts` | Each time a check sent the model back for another reply: `guard`, `step`. More than a few per turn means a guard is fighting your prompt |
| `caveats` | Everything GAIA would have appended to the answer on a workspace host: a tool result that carried instructions, a problem your own `answer_problems` found and the model did not fix. On a conversation host read this key; `completion_caveats` is the workspace host's and stays empty |
| `input_tokens`, `output_tokens`, `cached_tokens`, `cost_usd` | Usage for the turn. `cost_usd` is Fireworks' list price from `gaia.llm.pricing`. It is `None` for a model with no card there and for any other provider; set `provider_name = "fireworks"` on your client when that is where the model runs |
| `timing_summary` | Model seconds, tool seconds and model calls |

## Your own model client

Subclass `LLMClient` and put it where the agent's client sits. `chat()` returns the
model's text, or `tool_calls_reply(...)` when the model called tools.

```python theme={null}
from gaia.llm.base_client import LLMClient
from gaia.llm.tool_calls import tool_calls_reply


class MyClient(LLMClient):
    provider_name = "my-provider"

    def chat(self, messages, model=None, stream=False, **kwargs):
        response = self._post(messages, model, kwargs.get("tools"), kwargs["max_tokens"])
        message = response["choices"][0]["message"]
        self._usage = response.get("usage")
        self._finish = response["choices"][0].get("finish_reason")
        if message.get("tool_calls"):
            return tool_calls_reply(
                message["tool_calls"], message.get("content"), self._finish
            )
        return message.get("content") or ""

    def generate(self, prompt, model=None, stream=False, **kwargs):
        return self.chat([{"role": "user", "content": prompt}], model, stream, **kwargs)

    def get_last_usage(self):
        return self._usage

    def get_last_finish_reason(self):
        return self._finish


agent = SupportAgent(session, model_id="deepseek-v4p1-flash")
agent.chat.llm_client = MyClient()
```

Things to know about this seam:

* **Raise your own exceptions.** GAIA catches them and ends the turn with
  `status: "failed"` and `stop_reason: "model_call"`. Keep the exception on your
  client if you need its type afterwards.
* **Accept `**kwargs`.** Besides `messages`, `model`, `stream`, `tools` and
  `max_tokens`, the loop can pass `temperature`, `top_p`, `tool_choice`,
  `reasoning_effort` and `stop`. Forward the ones your provider takes.
* **Use a model id with no provider prefix.** Ids shaped like `provider.model` are
  looked up in Lemonade's cloud catalogue, and an id it does not list gets its tools
  as text in the system prompt instead of `tools=`.
* **Return `finish_reason`.** `"length"` on a tool call is how GAIA knows the call
  was cut off and asks for it again.
* **Return `usage`.** The result's token counts and `cost_usd` are summed from
  `get_last_usage()`, in the OpenAI shape. It must describe the most recent call
  only, or a step's tokens are counted twice.

## Testing

`gaia.testing.ScriptedLLMClient` runs the same loop with no network. See
[Scripting the Model](https://amd-gaia.ai/docs/sdk/testing.md#17-3-scripting-the-model).

```python theme={null}
from gaia.testing import ScriptedLLMClient

model = ScriptedLLMClient()
model.push(call="get_order", order_number="1001")
model.push(say="It shipped on Monday.")
agent = SupportAgent(session)
agent.chat.llm_client = model

assert agent.process_query("Where is order 1001?")["result"] == "It shipped on Monday."
```

## What stays your job

* **Budgets.** `max_steps` and `max_output_tokens` are the limits the loop enforces.
  Dollar and wall-clock limits belong in your client, between calls.
* **Credentials.** Read them from the environment in your client. GAIA's OS keyring
  lookup is for desktops.
* **Checking the reply.** On a conversation host GAIA sends a reply back only when
  it is malformed: a tool call or tool output written out as text. Two tries, then
  the turn ends `incomplete` with `stop_reason: "tool_call_format"`. Whether the
  reply is true is yours to check: compare it with `tool_calls` before it reaches a
  customer.
* **Hooks you add still run.** An `answer_problems` override, or a mixin such as
  memory, can still send the model back. Those show up in `reprompts`.


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