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

# invoke_agent

> Load an agent and create a task in one call.

`Backend.ainvoke_agent` (and its sync sibling `invoke_agent`) is shorthand for "load the agent and create a task." Internally it calls `Agents.aget(agent_id)` followed by `Agent.acreate_task(...)`, returning the resulting `Task`.

Use this when you want to invoke an agent from outside the `@on_task` runtime: for example, from a webhook handler, a script, or another agent.

<Note>
  If `prompt` happens to be a JSON string containing `xpander_task_id`, the method short-circuits and returns the existing task instead of creating a new one. This is how the platform passes task continuations through chat-style integrations.
</Note>

```python theme={"dark"}
from xpander_sdk import Backend

backend = Backend()
task = await backend.ainvoke_agent(
    agent_id="agent-123",
    prompt="Summarize the latest sales report",
)
print(task.id, task.status)
```

### Parameters

| Parameter                     | Type           | Required | Default                    | Description                                                                               |
| ----------------------------- | -------------- | -------- | -------------------------- | ----------------------------------------------------------------------------------------- |
| `agent_id`                    | `str`          | No       | `XPANDER_AGENT_ID` env var | Agent to invoke. Falls back to env var if omitted.                                        |
| `prompt`                      | `str`          | No       | `""`                       | Natural-language input for the agent.                                                     |
| `existing_task_id`            | `str`          | No       | `None`                     | Continue an existing task instead of creating a new one.                                  |
| `file_urls`                   | `list[str]`    | No       | `None`                     | URLs of files to attach (PDFs, images, CSVs, …).                                          |
| `user_details`                | `User`         | No       | `None`                     | End-user context for memory and personalization.                                          |
| `agent_version`               | `str`          | No       | `None`                     | Pin a specific agent version. Defaults to the latest.                                     |
| `tool_call_payload_extension` | `dict`         | No       | `None`                     | Extra fields merged into every tool-call payload.                                         |
| `source`                      | `str`          | No       | `"sdk"`                    | Origin tag stored on the task (e.g. `"webhook"`, `"slack"`).                              |
| `worker_id`                   | `str`          | No       | `None`                     | Pin execution to a specific worker.                                                       |
| `run_locally`                 | `bool`         | No       | `False`                    | Mark the task as locally executed (skips cloud worker dispatch).                          |
| `output_format`               | `OutputFormat` | No       | `None`                     | `Text`, `Markdown`, `Json`, or `Voice`.                                                   |
| `output_schema`               | `dict`         | No       | `None`                     | JSON schema for structured output (paired with `OutputFormat.Json`).                      |
| `events_streaming`            | `bool`         | No       | `False`                    | Enable SSE streaming via `task.aevents()`.                                                |
| `additional_context`          | `str`          | No       | `None`                     | Extra context appended to the system prompt for this run.                                 |
| `expected_output`             | `str`          | No       | `None`                     | Description of the expected output shape (used by some frameworks for self-verification). |

### Returns `Task`

The created `Task` object, populated with the platform-assigned `id` and an initial `status` of `pending`. See [`Task`](/developers/sdk-reference/tasks/task) for the full attribute list.

## Examples

### Attach files

```python theme={"dark"}
task = await backend.ainvoke_agent(
    agent_id="agent-123",
    prompt="Find action items from this meeting recording.",
    file_urls=[
        "https://example.com/recordings/meeting.mp3",
        "https://example.com/transcripts/notes.pdf",
    ],
)
```

PDFs and images are auto-categorized by `Task.get_files()` / `get_images()` for Agno. Other file types (CSV, JSON, TXT, …) are inlined into the message via `Task.to_message()`.

### Structured output

```python theme={"dark"}
from xpander_sdk import OutputFormat

task = await backend.ainvoke_agent(
    agent_id="agent-123",
    prompt="Extract company name and revenue from the press release.",
    file_urls=["https://example.com/press-release.pdf"],
    output_format=OutputFormat.Json,
    output_schema={
        "type": "object",
        "properties": {
            "company": {"type": "string"},
            "revenue_usd": {"type": "number"},
        },
        "required": ["company"],
    },
)
```

### Stream events

```python theme={"dark"}
task = await backend.ainvoke_agent(
    agent_id="agent-123",
    prompt="Long-running research task",
    events_streaming=True,
)

async for event in task.aevents():
    print(event.type, event.data)
```

### Continue an existing task

```python theme={"dark"}
task = await backend.ainvoke_agent(
    agent_id="agent-123",
    existing_task_id="task_abc123",
    prompt="Now summarize what you found.",
)
```

`existing_task_id` reuses the same memory thread, so the agent has full context from the prior run.

### Per-end-user context

```python theme={"dark"}
from xpander_sdk import User

task = await backend.ainvoke_agent(
    agent_id="agent-123",
    prompt="What's on my calendar this afternoon?",
    user_details=User(
        id="user_42",
        email="alex@example.com",
        first_name="Alex",
        timezone="America/New_York",
    ),
)
```

The `User` object scopes user-memory storage and connector authentication (e.g. OAuth tokens for Gmail or Calendar) to the right end user.

## Sync version

```python theme={"dark"}
task = backend.invoke_agent(
    agent_id="agent-123",
    prompt="Hello!",
)
```

Identical signature; blocks until the task is created. Don't call from inside a running event loop: use `ainvoke_agent` there.
