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

# FastAPI 应用

> 将代理托管为 FastAPI 应用。

FastAPI 应用用于通过具有 REST API 接口的 FastAPI 服务器来托管代理或团队。

### 示例用法

创建代理，用 `FastAPIApp` 进行封装，然后进行托管：

```python theme={null}
from agno.agent import Agent
from agno.app.fastapi.app import FastAPIApp
from agno.models.openai import OpenAIChat

basic_agent = Agent(
    name="Basic Agent",
    model=OpenAIChat(id="gpt-4o"), # 确保设置了 OPENAI_API_KEY
    add_history_to_messages=True,
    num_history_responses=3,
    add_datetime_to_instructions=True,
    markdown=True,
)

# 默认异步路由 (use_async=True)
fastapi_app = FastAPIApp(
    agent=basic_agent,
    name="Basic Agent",
    app_id="basic_agent",
    description="一个基础代理，可以回答问题并协助处理任务。",
)

app = fastapi_app.get_app()

# 对于同步路由：
# app = fastapi_app.get_app(use_async=False)

if __name__ == "__main__":
    fastapi_app.serve(app="basic:app", port=8001, reload=True)

```

**运行方法：**

1. 设置 `OPENAI_API_KEY` 环境变量。
2. API 地址为 `http://localhost:8001`，文档地址为 `http://localhost:8001/docs`。

将 `POST` 请求发送到 `http://localhost:8001/v1/run`：

```json theme={null}
{
  "message": "你好 Basic Agent，给我讲个有趣的冷知识！",
  "stream": false
}
```

## 核心组件

* `FastAPIApp`: 用于封装 Agno 代理/团队以用于 FastAPI。
* `FastAPIApp.serve`: 使用 Uvicorn 托管 FastAPI 应用。

`FastAPIApp` 使用辅助函数进行路由处理。

## `FastAPIApp` 类

Agno FastAPI 应用的主入口点。

### 初始化参数

| 参数            | 类型                         | 默认值    | 描述                               |
| ------------- | -------------------------- | ------ | -------------------------------- |
| `agents`      | `Optional[List[Agent]]`    | `None` | Agno `Agent` 实例列表。               |
| `teams`       | `Optional[List[Team]]`     | `None` | Agno `Team` 实例列表。                |
| `workflows`   | `Optional[List[Team]]`     | `None` | Agno `Workflow` 实例列表。            |
| `settings`    | `Optional[APIAppSettings]` | `None` | API 配置。如果为 `None` 则使用默认值。        |
| `api_app`     | `Optional[FastAPI]`        | `None` | 现有的 FastAPI 应用。如果为 `None` 则创建新的。 |
| `router`      | `Optional[APIRouter]`      | `None` | 现有的 APIRouter。如果为 `None` 则创建新的。  |
| `app_id`      | `Optional[str]`            | `None` | 应用标识符（如果未设置则自动生成）。               |
| `name`        | `Optional[str]`            | `None` | 应用名称。                            |
| `description` | `Optional[str]`            | `None` | 应用描述。                            |

*请提供 `agent` 或 `team`，不要同时提供两者。*

### 关键方法

| 方法        | 参数                                                  | 返回类型      | 描述                                           |
| --------- | --------------------------------------------------- | --------- | -------------------------------------------- |
| `get_app` | `use_async: bool = True`<br />`prefix: str = "/v1"` | `FastAPI` | 返回配置好的 FastAPI 应用（默认异步）。设置前缀、错误处理器、CORS 和文档。 |

## 端点

端点可在指定的前缀（默认为 `/v1`）下访问。

### 1. `POST /run`

* **描述**: 与代理/团队进行交互（使用 `agent.run()`/`arun()` 或 `team.run()`/`arun()`）。
* **请求表单参数**:
  | 参数           | 类型                           | 默认值                         | 描述             |
  | ------------ | ---------------------------- | --------------------------- | -------------- |
  | `message`    | `str`                        | `...`                       | 输入消息（必需）。      |
  | `stream`     | `bool`                       | `True` (同步), `False` (异步默认) | 流式响应。          |
  | `monitor`    | `bool`                       | `False`                     | 启用监控。          |
  | `session_id` | `Optional[str]`              | `None`                      | 用于会话连续性的会话 ID。 |
  | `user_id`    | `Optional[str]`              | `None`                      | 用户 ID。         |
  | `files`      | `Optional[List[UploadFile]]` | `None`                      | 要上传的文件。        |
* **响应**:
  * `stream=True`: `StreamingResponse` (`text/event-stream`)，包含 JSON `RunResponse`/`TeamRunResponse` 事件。
  * `stream=False`: JSON `RunResponse`/`TeamRunResponse` 字典。

### 参数

| 参数       | 类型                    | 默认值           | 描述                      |
| -------- | --------------------- | ------------- | ----------------------- |
| `app`    | `Union[str, FastAPI]` | `N/A`         | FastAPI 应用实例或导入字符串（必需）。 |
| `host`   | `str`                 | `"localhost"` | 要绑定的主机。                 |
| `port`   | `int`                 | `7777`        | 要绑定的端口。                 |
| `reload` | `bool`                | `False`       | 为开发启用自动重载。              |
