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

# 模型服务

> 将训练好的模型作为 API 服务

# 模型服务

为生产推理服务您训练好的模型。

## 聊天界面

测试和与模型交互的最简单方法：

```bash theme={null}
aitraining chat
```

在 `http://localhost:7860/inference` 打开 Web 界面。Chat UI 允许您加载任何本地或 Hub 模型进行交互式测试。

### 自定义端口

```bash theme={null}
aitraining chat --port 3000
```

### 自定义主机

```bash theme={null}
aitraining chat --host 0.0.0.0
```

## API 服务器

API 服务器是一个**训练运行器**，不是推理服务器。它在运行训练作业时暴露用于健康检查的最小端点。

### 启动 API 服务器

```bash theme={null}
aitraining api
```

默认在 `http://127.0.0.1:7860` 启动训练 API。

### 参数

| 参数       | 描述         | 默认值         |
| -------- | ---------- | ----------- |
| `--port` | 运行 API 的端口 | `7860`      |
| `--host` | 绑定的主机      | `127.0.0.1` |
| `--task` | 要运行的任务（可选） | `None`      |

### 自定义端口/主机

```bash theme={null}
aitraining api --port 8000 --host 0.0.0.0
```

### 环境变量

API 服务器从环境变量读取配置：

| 变量                   | 描述                        |
| -------------------- | ------------------------- |
| `HF_TOKEN`           | Hugging Face token 用于身份验证 |
| `AUTOTRAIN_USERNAME` | 训练用户名                     |
| `PROJECT_NAME`       | 项目名称                      |
| `TASK_ID`            | 任务标识符                     |
| `PARAMS`             | 训练参数（JSON）                |
| `DATA_PATH`          | 训练数据路径                    |
| `MODEL`              | 要使用的模型                    |

### 端点

| 端点            | 描述            |
| ------------- | ------------- |
| `GET /`       | 返回训练状态消息      |
| `GET /health` | 健康检查（返回 "OK"） |

<Note>
  当没有活动训练作业时，API 服务器会自动关闭。对于生产推理，请改用 vLLM 或 TGI。
</Note>

## 生产部署

### 使用 vLLM

用于高吞吐量的生产级服务：

```bash theme={null}
pip install vllm

python -m vllm.entrypoints.openai.api_server \
  --model ./my-trained-model \
  --port 8000
```

### 使用 Text Generation Inference (TGI)

```bash theme={null}
docker run --gpus all -p 8080:80 \
  -v ./my-model:/model \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id /model
```

### OpenAI 兼容 API

vLLM 和 TGI 都提供 OpenAI 兼容端点：

```python theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="dummy"  # 本地不需要
)

response = client.chat.completions.create(
    model="my-model",
    messages=[
        {"role": "user", "content": "Hello!"}
    ]
)
```

## Docker 部署

### Dockerfile 示例

```dockerfile theme={null}
FROM python:3.10-slim

WORKDIR /app

# 安装依赖
RUN pip install aitraining torch

# 暴露端口
EXPOSE 7860

# 运行聊天服务器
CMD ["aitraining", "chat", "--host", "0.0.0.0", "--port", "7860"]
```

构建并运行：

```bash theme={null}
docker build -t my-model-server .
docker run -p 7860:7860 my-model-server
```

### 使用 GPU

```bash theme={null}
docker run --gpus all -p 7860:7860 my-model-server
```

## 负载测试

### 使用 hey

```bash theme={null}
hey -n 100 -c 10 \
  -m POST \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello", "max_tokens": 50}' \
  http://localhost:8000/generate
```

### 使用 locust

```python theme={null}
# locustfile.py
from locust import HttpUser, task

class ModelUser(HttpUser):
    @task
    def generate(self):
        self.client.post("/generate", json={
            "prompt": "Hello, how are you?",
            "max_tokens": 50
        })
```

```bash theme={null}
locust -f locustfile.py --host http://localhost:8000
```

## 监控

### Prometheus 指标

如果使用 vLLM 或 TGI，指标在 `/metrics` 可用。

### 日志记录

```bash theme={null}
aitraining api --port 8000 2>&1 | tee server.log
```

## 下一步

<CardGroup cols={2}>
  <Card title="基准测试" href="/cli/benchmarking">
    测量模型性能
  </Card>

  <Card title="聊天界面" href="/chat/launching">
    交互式测试
  </Card>
</CardGroup>
