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

# AgentInput

> Reference for the AgentInput object received by structured agent functions and Agent.call()

> [!WARNING]
>
> You are reading the docs of Galtea 5.12. [Read this page in the latest version](https://docs.galtea.ai/sdk/api/agent/input.md).

## Overview

`AgentInput` is the input object your agent receives when using the **Structured** signature (`(input_data: AgentInput) -> AgentResponse`). It provides the conversation history, session context, and helper methods for accessing user messages.

When a test case has structured JSON input (e.g. `{"user_message": "hello", "chat_type": "support"}`), the SDK splits it: `user_message` becomes the message content, and the remaining fields (like `chat_type`) are placed in the first user message's `metadata`.

## Fields

**messages** `list[ConversationMessage]` *required*

The full conversation history up to this turn. Each `ConversationMessage` has:

* `role` (`str`): `"user"` or `"assistant"`
* `content` (`str`): The message text
* `retrieval_context` (`str | None`): Retrieved context (for RAG agents)
* `metadata` (`dict[str, Any] | None`): Additional fields. When the test case uses structured JSON input, non-message fields (e.g. `chat_type`, `priority`) appear here on the first user message.
* `input_files` (`list[AttachedFile]`): The files attached to a user message, ready for [`galtea.storage.download()`](https://docs.galtea.ai/v5.12/sdk/api/storage/download). Empty for a message that carries only text.
* `output_files` (`list[AttachedFile]`): The files an earlier assistant message answered with, read the same way. Empty for a message that carries only text.

**session\_id** `str` *required*

The current session identifier. Use this to maintain state in stateful agents.

**context\_data** `dict[str, Any] | None`

Structured context data from the test case. This comes from the test case's `context` / `context_data` field, not from the input. Use it to pass supplemental information like customer tier, environment, or domain context.

**metadata** `dict[str, Any] | None`

Additional metadata for the current execution.

**input\_files** `list[AttachedFile]`

The files attached to the **last user message**, as `AttachedFile` objects, empty when it carries none. Derived from `messages` rather than stored, so an `input_files` keyword passed to the constructor is ignored; attach files through `ConversationMessage(input_files=...)`. For an earlier turn's files, read that message's own `input_files`. See [Reading attached files](#reading-attached-files).

**trace\_id** `str | None`

The trace ID for this execution. Forward this to remote agents so they can attach spans to the correct session via `set_context(trace_id=...)`. See [Remote Agent Tracing](https://docs.galtea.ai/v5.12/sdk/tutorials/tracing-agent-operations.md#remote-agent-tracing).

## Helper Methods

**last\_user\_message\_str()** `str | None`

Returns the `content` of the last user message, or `None` if no user message exists. This is the simplest way to get the user's message text.

**last\_user\_message()** `ConversationMessage | None`

Returns the full `ConversationMessage` object for the last user message (with `role`, `content`, `retrieval_context`, `metadata`, `input_files`, and `output_files`), or `None` if not found. Use this when you need access to the message's `metadata`.

## Basic Usage

```python theme={"system"}
def my_basic_agent(input_data: galtea.AgentInput) -> galtea.AgentResponse:
    # Get the last user message content
    user_message = input_data.last_user_message_str()

    # Access session and context
    session_id = input_data.session_id
    context = input_data.context_data  # e.g. {"customer_tier": "premium"}

    return galtea.AgentResponse(content=f"Response to: {user_message}")
```

## Accessing Structured Input Fields

When your test case input is a JSON object (e.g. uploaded via CSV with `{"user_message": "hello", "chat_type": "support"}` in the input column), the SDK places `user_message` as the message content and remaining fields in `messages[0].metadata`:

```python theme={"system"}
def my_structured_agent(input_data: AgentInput) -> AgentResponse:
    # Get the last user message as a ConversationMessage object
    last_msg = input_data.last_user_message()
    if last_msg is None:
        return AgentResponse(content="No user message received.")

    # The message content (the user_message field from structured input)
    user_message = last_msg.content  # e.g. "hello"

    # Structured fields from the test case are in the first user message's metadata
    first_user_msg = input_data.messages[0] if input_data.messages else None
    if first_user_msg and first_user_msg.metadata:
        chat_type = first_user_msg.metadata.get("chat_type")  # e.g. "support"
        priority = first_user_msg.metadata.get("priority")  # e.g. "high"
    else:
        chat_type = None
        priority = None

    # Use structured fields to customize behavior
    if chat_type == "support":
        response = f"Support response (priority={priority}): {user_message}"
    else:
        response = f"General response: {user_message}"

    return AgentResponse(content=response)
```

## Accessing Context Data

`context_data` is separate from the input. It comes from the test case's context field and is useful for passing supplemental information that is not part of the user message:

```python theme={"system"}
def my_context_agent(input_data: AgentInput) -> AgentResponse:
    user_message = input_data.last_user_message_str()

    # context_data comes from the test case's context field
    if input_data.context_data:
        customer_tier = input_data.context_data.get("customer_tier", "standard")
    else:
        customer_tier = "standard"

    return AgentResponse(content=f"[{customer_tier}] Response to: {user_message}")
```

## Reading attached files

A test case can [attach files](https://docs.galtea.ai/v5.12/concepts/product/dataset/test-case.md#file-inputs) to its input. When your agent runs through `evaluations.run()`, `simulator.simulate()` or `traces.generate()`, those files reach it as `input_data.input_files`: one `AttachedFile` per attached file, with the same `uri`, `filename` and `mime_type` as `test_case.input_files`. Pass each one to [`galtea.storage.download()`](https://docs.galtea.ai/v5.12/sdk/api/storage/download) to get the bytes:

```python theme={"system"}
def my_document_agent(input_data: AgentInput) -> AgentResponse:
    # Each AttachedFile has the same uri, filename and mime_type as test_case.input_files.
    document_paths = [
        galtea_client.storage.download(attached, output_directory="./.temp/agent-inputs")
        for attached in input_data.input_files
    ]

    # Empty string for a test case that carries only a document and no text.
    question = input_data.last_user_message_str() or ""

    return AgentResponse(content=f"Answer to {question!r} from {len(document_paths)} file(s)")
```

When the document goes straight into a request of your own, [`read()`](https://docs.galtea.ai/v5.12/sdk/api/storage/read) returns the bytes and never touches the disk:

```python theme={"system"}
def my_multimodal_agent(input_data: AgentInput) -> AgentResponse:
    # read() keeps the bytes in memory, for a model that takes the document inline.
    parts = [
        {
            "type": "document",
            "media_type": attached.mime_type,
            "data": base64.b64encode(galtea_client.storage.read(attached)).decode(),
        }
        for attached in input_data.input_files
    ]

    question = input_data.last_user_message_str() or ""

    return AgentResponse(content=f"Answer to {question!r} from {len(parts)} inline document(s)")
```

`input_data.input_files` is a shortcut for the current turn. Each `ConversationMessage` keeps its own files, so an earlier turn's document stays reachable through `messages`:

```python theme={"system"}
def my_multi_turn_agent(input_data: AgentInput) -> AgentResponse:
    # Each user message carries its own files, so an earlier turn's document is still reachable.
    every_attachment = [
        attached for message in input_data.messages if message.role == "user" for attached in message.input_files
    ]
    # input_data.input_files is the shortcut for the current turn only.
    this_turn = input_data.input_files

    return AgentResponse(content=f"{len(this_turn)} file(s) on this turn, {len(every_attachment)} in the conversation")
```

> [!NOTE]
>
> A history with files on more than one turn only comes from turns you create yourself. Log earlier turns with
> [`traces.create()`](https://docs.galtea.ai/v5.12/sdk/api/trace/create) and `input_file_paths`, or run a turn with
> [`traces.generate()`](https://docs.galtea.ai/v5.12/sdk/api/trace/generate), passing `input={"user_message": "...", "content": [...]}`.
> The conversation simulator supports attached files on single-turn runs only, so
> `evaluations.run()` and `simulator.simulate()` put every file on the opening turn.

The metadata split is unchanged: `messages[0].metadata["content"]` still holds the raw content parts, files included, exactly as the platform stores them.

> [!WARNING]
>
> Only the **Structured** signature receives files. A `(str) -> str` or `(list[dict]) -> str` agent receives the text alone: the SDK logs one warning per agent when a test case also attaches files, and fails the trace with a `galtea.FileOnlyTextAgentException` (a `ValueError` subclass) when the test case attaches files and no text, since that agent would receive nothing. Annotate the first parameter as `galtea.AgentInput` to receive both.

## Structured Input on TestCase and Trace

Outside of `AgentInput`, the `TestCase` and `Trace` models provide three fields for accessing input:

* `.input` (`str`): The `user_message` value as a plain string
* `.input_data` (`dict`): The full structured input object with all fields
* `.input_files` (`list[AttachedFile]`): The files attached to the input, empty for text

`Trace` also provides three symmetric fields for the agent output:

* `.actual_output` (`str | None`): The scored output as a plain string. For voice turns this is the `assistant_message` transcript unwrapped from the content-parts envelope. `None` when the turn answered with files and no text.
* `.actual_output_data` (`dict | None`): The full output envelope when present (e.g. `{"assistant_message": "...", "content": [{"type": "audio", "uri": "...", "transcript": "..."}]}`), otherwise `None` for plain-text output.
* `.actual_output_files` (`list[AttachedFile]`): The files attached to the output, empty for text-only. See [Output Files](https://docs.galtea.ai/v5.12/concepts/product/version/session/trace.md#trace-properties).

> [!NOTE]
>
> When submitting an `actualOutput` content-parts envelope, each audio part must include either a non-empty `transcript` or a non-empty `uri`. If you provide only a `uri`, the API transcribes the stored audio automatically and fills in the transcript. A client-supplied `transcript` or `assistant_message` always takes precedence over the API's speech-to-text result. The strict transcript requirement applies only to the user turn (`input`) — the agent output side accepts audio-only parts.

```python theme={"system"}
# After running generate() or in a test loop, access the full structured input:
galtea_client = Galtea(api_key="YOUR_API_KEY")
test_case = galtea_client.test_cases.get(test_case_id=test_case_id)

# .input gives the user_message as a plain string
print(test_case.input)  # "hello"

# .input_data gives the full structured dict
print(test_case.input_data)  # {"user_message": "hello", "chat_type": "support"}

# Same pattern for traces (input side):
trace = galtea_client.traces.get(trace_id=trace_id)
print(trace.input)  # "hello"
print(trace.input_data)  # {"user_message": "hello", "chat_type": "support"}

# Output side — symmetric pair:
print(trace.actual_output)  # "the answer is 42" (plain string for text; transcript for voice)
print(trace.actual_output_data)  # None for plain text; {"assistant_message": "...", "content": [...]} for voice
```

## How Structured Input Flows Through the System

1. **Test case CSV**: You provide JSON in the `input` column: `{"user_message": "hello", "chat_type": "support"}`
2. **TestCase model**: `.input` = `"hello"`, `.input_data` = `{"user_message": "hello", "chat_type": "support"}`
3. **Endpoint templates**: Use `{{ input.user_message }}` or `{{ input.chat_type }}` to access individual fields. Bare `{{ input }}` is rejected, because it renders the whole object. The download URL of a file is never part of `input`, so read a file with [`input_files`](https://docs.galtea.ai/v5.12/concepts/product/endpoint-connection-template-syntax#attached-files-and-audio)
4. **AgentInput (SDK)**: `messages[0].content` = `"hello"`, `messages[0].metadata` = `{"chat_type": "support"}`
5. **Trace**: `.input` = `"hello"`, `.input_data` = `{"user_message": "hello", "chat_type": "support"}`

## Related

> [card] [Simulating Conversations](https://docs.galtea.ai/v5.12/sdk/tutorials/simulating-conversations.md)
>
> Multi-turn conversation simulation tutorial.

> [card] [Generate Trace](https://docs.galtea.ai/v5.12/sdk/api/trace/generate.md)
>
> Single-turn agent execution with automatic span collection.

> [card] [Templates & Mapping](https://docs.galtea.ai/v5.12/concepts/product/endpoint-connection-configuration.md)
>
> Endpoint template syntax including `{{ input.field_name }}`.

> [card] [Tracing Agent Operations](https://docs.galtea.ai/v5.12/sdk/tutorials/tracing-agent-operations.md)
>
> Capture internal operations and forward trace\_id to remote agents.


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