# https://github.com/togethercomputer/together-python 项目说明书

生成时间: 2026-05-21 18:14:28 UTC

## 目录

- [项目介绍](#page-introduction)
- [安装与配置](#page-installation)
- [客户端架构](#page-client-architecture)
- [请求流程与抽象层](#page-request-flow)
- [聊天补全 API](#page-chat-completions)
- [文本补全 API](#page-completions)
- [多模态功能](#page-multimodal)
- [嵌入与重排序](#page-embeddings-rerank)
- [文件管理](#page-files-management)
- [模型微调](#page-finetuning)

<a id='page-introduction'></a>

## 项目介绍

### 相关页面

相关主题：[安装与配置](#page-installation), [客户端架构](#page-client-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)
- [src/together/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/__init__.py)
- [CONTRIBUTING.md](https://github.com/togethercomputer/together-python/blob/main/CONTRIBUTING.md)
- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)
- [src/together/resources/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)
- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)
</details>

# 项目介绍

Together Python 是一个开源的 Python 客户端库和命令行工具，用于与 Together AI 平台进行交互。该项目提供了对 Together AI 强大语言模型、嵌入模型、图像生成和微调服务的便捷访问能力。

## 项目概述

Together Python 由 Together Computer 团队开发和维护，旨在为开发者提供一套完整、简洁的 API 接口，使其能够轻松地将 Together AI 平台的各种 AI 能力集成到自己的应用程序中。

### 核心特性

| 特性 | 说明 |
|------|------|
| **Python 客户端** | 面向对象的 Python API，简化与 Together AI 的交互 |
| **CLI 工具** | 命令行界面，支持快速调用和脚本集成 |
| **流式输出** | 支持实时流式 token 输出 |
| **异步支持** | 提供异步客户端，支持并发请求处理 |
| **多模态支持** | 支持文本、图像等多种输入类型 |
| **微调服务** | 提供完整的模型微调工作流 |

资料来源：[README.md:1-30]()

## 项目架构

Together Python 采用模块化设计，主要包含以下几个核心组件：

### 架构图

```mermaid
graph TD
    subgraph "客户端层"
        Python[Python 客户端]
        CLI[CLI 命令行工具]
        Async[异步客户端]
    end
    
    subgraph "资源模块"
        Chat[Chat Completions]
        Completions[Completions]
        Embeddings[Embeddings]
        Images[Images]
        Rerank[Reranking]
        FineTuning[Fine-Tuning]
    end
    
    subgraph "核心层"
        Requestor[API Requestor]
        FileManager[文件管理器]
        Error[错误处理]
    end
    
    subgraph "Together AI 平台"
        API[REST API]
        Models[模型服务]
    end
    
    Python --> Chat
    Python --> Completions
    Python --> Embeddings
    Python --> Images
    Python --> Rerank
    Python --> FineTuning
    
    CLI --> Chat
    CLI --> Completions
    CLI --> FineTuning
    
    Async --> Chat
    Async --> Completions
    
    Chat --> Requestor
    Completions --> Requestor
    Embeddings --> Requestor
    Images --> Requestor
    Rerank --> Requestor
    FineTuning --> Requestor
    
    Requestor --> API
    FineTuning --> FileManager
    FileManager --> API
    API --> Models
```

### 核心模块说明

#### 异常处理模块

项目定义了一套完整的异常类型体系，用于处理各种错误场景：

| 异常类型 | 说明 |
|---------|------|
| `TogetherException` | 基础异常类 |
| `RateLimitError` | 速率限制错误 |
| `FileTypeError` | 文件类型错误 |
| `APIConnectionError` | API 连接错误 |
| `Timeout` | 超时错误 |

资料来源：[src/together/error.py:1-60]()

#### 聊天补全模块

提供 Chat Completions API 接口，支持多种消息格式和工具调用：

```python
response = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=[{"role": "user", "content": "tell me about new york"}],
)
```

资料来源：[README.md:30-40]()

#### 微调模块

提供完整的模型微调工作流程，包括价格估算、训练配置和检查点管理：

| 参数 | 说明 |
|------|------|
| `n_epochs` | 训练轮数 |
| `batch_size` | 批处理大小 |
| `learning_rate` | 学习率 |
| `lora` | 是否启用 LoRA |
| `training_method` | 训练方法（DPO、SimPO 等）|

资料来源：[src/together/resources/finetune.py:1-100]()

## 主要功能

### 1. 对话补全（Chat Completions）

支持单轮和多轮对话，以及多模态输入（文本+图像）：

```mermaid
graph LR
    A[用户消息] --> B[构建消息列表]
    B --> C[API 请求]
    C --> D{流式?}
    D -->|是| E[流式响应]
    D -->|否| F[完整响应]
    E --> G[逐块处理]
    F --> H[返回完整结果]
```

资料来源：[src/together/resources/chat/completions.py:1-50]()

### 2. 补全（Completions）

提供传统的文本补全功能：

```python
response = client.completions.create(
    model="codellama/CodeLlama-34b-Python-hf",
    prompt="Write a Next.js component with TailwindCSS for a header component.",
    max_tokens=200,
)
```

资料来源：[README.md:80-90]()

### 3. 嵌入（Embeddings）

支持文本嵌入向量生成：

```python
outputs = client.embeddings.create(
    model='togethercomputer/m2-bert-80M-8k-retrieval',
    input=texts
)
```

### 4. 图像生成（Image Generation）

提供图像生成能力：

```python
response = client.images.generate(
    prompt="space robots",
    model="stabilityai/stable-diffusion-xl-base-1.0",
    steps=10,
    n=4,
)
```

### 5. 重排序（Reranking）

支持文档重排序功能：

```python
outputs = client.rerank.create(
    model=model,
    query=query,
    documents=documents,
    top_n=top_n
)
```

### 6. 模型微调（Fine-Tuning）

提供完整的微调工作流程：

```bash
# 启动微调任务
together fine-tuning create \
  --training-file <FILE_ID> \
  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --n-epochs 3
```

#### 支持的微调方法

| 训练方法 | 说明 |
|---------|------|
| `full` | 全参数微调 |
| `lora` | LoRA 低秩适配微调 |
| `dpo` | 直接偏好优化 |
| `simpo` | 简单偏好优化 |
| `rpo` | 相对偏好优化 |

资料来源：[src/together/resources/finetune.py:50-150]()

## 安装与配置

### 环境要求

- Python 3.10+
- Poetry 1.6.1+

### 安装步骤

1. **获取 API Key**：访问 [Together AI 注册页面](https://api.together.xyz/) 获取 API Key

2. **设置环境变量**：

```shell
export TOGETHER_API_KEY=xxxxx
```

3. **安装依赖**：

```bash
poetry install --with quality,tests
```

4. **设置 pre-commit**：

```bash
pre-commit install
```

资料来源：[CONTRIBUTING.md:1-30]()

## 使用方式

### Python 客户端使用

```python
from together import Together

# 初始化客户端
client = Together(api_key="xxxxx")

# 创建聊天请求
response = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=[{"role": "user", "content": "Hello, how are you?"}]
)

print(response.choices[0].message.content)
```

### 异步客户端使用

```python
from together import AsyncTogether

async_client = AsyncTogether()

tasks = [
    async_client.completions.create(model="...", prompt="..."),
    async_client.completions.create(model="...", prompt="...")
]

responses = await asyncio.gather(*tasks)
```

### CLI 命令行使用

```bash
# 聊天补全
together chat.completions --message "Hello" --model meta-llama/Llama-4-Scout-17B-16E-Instruct

# 文本补全
together completions "Large language models are " --model meta-llama/Llama-4-Scout-17B-16E-Instruct

# 图像生成
together images generate "space robots" --model stabilityai/stable-diffusion-xl-base-1.0

# 文件操作
together files upload example.jsonl
together files list
together files retrieve <FILE_ID>

# 微调任务
together fine-tuning create --training-file <FILE_ID> --model <MODEL>
together fine-tuning list
together fine-tuning events <FINE_TUNE_ID>
together fine-tuning download <FINE_TUNE_ID>
```

## 错误处理

项目实现了完善的错误处理机制：

```mermaid
graph TD
    A[API 请求] --> B{响应状态}
    B -->|成功| C[返回结果]
    B -->|4xx 错误| D[客户端错误]
    B -->|5xx 错误| E[服务器错误]
    B -->|速率限制| F[RateLimitError]
    B -->|超时| G[Timeout]
    
    D --> H[TogetherException]
    E --> H
    F --> H
    G --> H
```

## 开发指南

### 本地开发设置

```bash
# 安装开发依赖
poetry install --with quality,tests

# 格式化和代码检查
make format

# 运行测试
make tests
```

### 测试说明

| 测试类型 | 说明 | 命令 |
|---------|------|------|
| 单元测试 | 不需要 API Key | `make tests` |
| 集成测试 | 需要 API Key，会产生费用 | `make integration_tests` |

资料来源：[CONTRIBUTING.md:30-60]()

## 技术规格

### 支持的模型类型

| 类型 | 示例模型 |
|------|---------|
| 聊天模型 | Llama-4, Llama-3, Qwen, Gemma |
| 代码模型 | CodeLlama, DeepSeek-Coder |
| 嵌入模型 | M2-BERT, GTE |
| 图像模型 | Stable Diffusion XL |
| 视觉模型 | Llama-3.2-Vision |

### API 特性支持

| 功能 | 支持状态 |
|------|---------|
| 流式输出 | ✅ 支持 |
| 工具/函数调用 | ✅ 支持 |
| JSON 模式 | ✅ 支持 |
| 多模态输入 | ✅ 支持 |
| 并发请求 | ✅ 支持 |
| 文件管理 | ✅ 支持 |
| 微调训练 | ✅ 支持 |

## 项目结构

```
together-python/
├── src/together/
│   ├── __init__.py          # 主入口
│   ├── error.py             # 异常定义
│   ├── version.py           # 版本信息
│   ├── client.py            # 客户端实现
│   ├── filemanager.py       # 文件管理器
│   ├── resources/           # API 资源模块
│   │   ├── chat/
│   │   │   └── completions.py
│   │   ├── completions.py
│   │   ├── embeddings.py
│   │   ├── images.py
│   │   ├── rerank.py
│   │   └── finetune.py
│   ├── utils/
│   │   └── files.py         # 文件处理工具
│   └── cli/
│       └── api/             # CLI 命令
│           ├── chat.py
│           ├── completions.py
│           ├── finetune.py
│           └── ...
└── tests/                   # 测试文件
```

## 总结

Together Python 是一个功能全面、易于使用的 Python 客户端库，为开发者提供了与 Together AI 平台交互的便捷方式。通过统一的 Python API 和 CLI 工具，开发者可以轻松实现聊天补全、文本补全、嵌入生成、图像生成和模型微调等多种 AI 功能。项目采用模块化设计，具有良好的可扩展性和维护性，适合各类 AI 应用的开发和部署。

---

<a id='page-installation'></a>

## 安装与配置

### 相关页面

相关主题：[项目介绍](#page-introduction), [客户端架构](#page-client-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)
- [CONTRIBUTING.md](https://github.com/togethercomputer/together-python/blob/main/CONTRIBUTING.md)
- [pyproject.toml](https://github.com/togethercomputer/together-python/blob/main/pyproject.toml)
- [src/together/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/__init__.py)
- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)
</details>

# 安装与配置

本文档详细说明 together-python 项目的安装方法、环境配置、依赖管理以及开发环境搭建流程。

## 概述

together-python 是 Together AI 提供的官方 Python SDK，提供了 Python 客户端库和 CLI 工具两种使用方式。该库支持多种核心功能，包括对话补全、文本补全、图像生成、嵌入向量生成以及模型微调等。资料来源：[README.md:1-10]()

## 环境要求

### 系统要求

| 要求项 | 最低版本 | 推荐版本 |
|--------|----------|----------|
| Python | 3.10 | 3.10+ |
| Poetry | 1.6.1 | 1.6.1+ |
| pip | 21.0 | 最新版本 |

### 依赖环境管理器说明

该项目使用 [Poetry](https://python-poetry.org/) v1.6.1+ 作为依赖管理器。如果使用 Conda 或 Pyenv 作为环境或包管理器，安装 Poetry 后需要配置 Poetry 使用虚拟环境的 Python 解释器。资料来源：[CONTRIBUTING.md:60-70]()

```bash
poetry config virtualenvs.prefer-active-python true
```

## 安装方式

### 方式一：通过 PyPI 安装（推荐）

使用 pip 直接安装 together-python 包：

```bash
pip install together
```

### 方式二：通过 Poetry 安装开发依赖

克隆仓库后，使用 Poetry 安装本地开发环境：

```bash
git clone https://github.com/togethercomputer/together-python.git
cd together-python
poetry install --with quality,tests
```

此命令会安装所有必要的依赖，包括：
- **quality**: 代码格式化和静态检查工具
- **tests**: 测试框架和测试依赖

资料来源：[CONTRIBUTING.md:54-58]()

### 方式三：从源码安装

```bash
pip install git+https://github.com/togethercomputer/together-python.git
```

## 环境变量配置

### 获取 API Key

1. 访问 Together Playground: https://api.together.ai
2. 在设置页面创建 API Key: https://api.together.xyz/settings/api-keys

### 配置环境变量

**Linux/macOS:**

```bash
export TOGETHER_API_KEY=your_api_key_here
```

**Windows (PowerShell):**

```powershell
$env:TOGETHER_API_KEY="your_api_key_here"
```

**永久配置：**

将上述命令添加到 shell 配置文件（`~/.bashrc`、`~/.zshrc` 或 `~/.profile`）中。

资料来源：[README.md:5-10]()

## 客户端初始化

### 基础客户端初始化

在代码中使用 API Key 初始化客户端：

```python
from together import Together

# 使用环境变量中的 API Key
client = Together()

# 或显式传入 API Key
client = Together(api_key="your_api_key_here")
```

资料来源：[README.md:13-18]()

### 异步客户端

对于需要异步处理的场景，使用 `AsyncTogether` 类：

```python
from together import AsyncTogether

async_client = AsyncTogether()
```

### CLI 客户端

CLI 工具在安装包后自动可用，无需额外配置。确保 `TOGETHER_API_KEY` 环境变量已设置即可。

## 开发环境配置

### 安装预提交钩子

项目使用 pre-commit 进行代码格式化和 linting 自动检查。安装开发依赖后，运行：

```bash
pre-commit install
```

这会在每次提交前自动执行格式化和检查。

资料来源：[CONTRIBUTING.md:58-60]()

### 代码格式化和检查

提交代码前手动运行检查：

```bash
# 格式化代码
make format

# 运行测试
make tests

# 运行集成测试（需要 API Key，会产生费用）
make integration_tests
```

资料来源：[CONTRIBUTING.md:40-50]()

## 可选依赖管理

项目采用可选依赖策略，大部分用户不会安装所有依赖。引入新依赖时应遵循以下流程：

1. 将依赖添加到可选组：
   ```bash
   poetry add --optional [package_name]
   ```

2. 在 `pyproject.toml` 中将依赖添加到 `extended_testing` extra

3. 重新锁定依赖：
   ```bash
   poetry lock --no-update
   ```

4. 添加至少导入该代码的单元测试

5. 使用 `@pytest.mark.requires(package_name)` 装饰需要该依赖的测试

资料来源：[CONTRIBUTING.md:18-35]()

## 项目结构

```
together-python/
├── pyproject.toml          # 项目配置和依赖定义
├── src/
│   └── together/
│       ├── __init__.py     # 包初始化和导出
│       ├── error.py        # 异常定义
│       ├── constants.py    # 常量定义
│       ├── resources/      # 功能资源模块
│       │   ├── chat/       # 聊天补全
│       │   ├── completions.py  # 文本补全
│       │   ├── images.py   # 图像生成
│       │   ├── embeddings.py   # 嵌入向量
│       │   ├── rerank.py    # 重排序
│       │   └── finetune.py  # 模型微调
│       └── cli/            # CLI 工具实现
│           └── api/        # CLI 命令
└── tests/                  # 测试文件
```

## 配置验证

### 验证安装

```python
import together

# 检查版本
print(together.__version__)

# 验证连接
client = Together()
models = client.models.list()
print(f"可用模型数量: {len(models.data)}")
```

### 常见配置错误

| 错误类型 | 错误信息 | 解决方案 |
|----------|----------|----------|
| 缺少 API Key | `AuthenticationError` | 设置 `TOGETHER_API_KEY` 环境变量 |
| API Key 无效 | `AuthenticationError` | 检查 API Key 是否正确，确认账户状态 |
| 速率限制 | `RateLimitError` | 降低请求频率，等待冷却时间 |
| 网络问题 | `APIConnectionError` | 检查网络连接，确认代理设置 |

资料来源：[src/together/error.py:1-50]()

## 工作流程图

```mermaid
graph TD
    A[开始] --> B{是否安装 SDK?}
    B -->|否| C[安装 together-python]
    C --> D{是否有 API Key?}
    D -->|否| E[申请 API Key]
    E --> F[配置环境变量]
    D -->|是| F
    F --> G[初始化客户端]
    G --> H{使用场景}
    H -->|同步| I[使用 Together 客户端]
    H -->|异步| J[使用 AsyncTogether 客户端]
    H -->|CLI| K[使用 together CLI]
    I --> L[调用 API]
    J --> L
    K --> L
```

## 下一步

- [快速开始指南](../quickstart) - 了解基本使用方法
- [聊天补全](../chat-completions) - 对话功能详解
- [模型微调](../fine-tuning) - 自定义模型训练
- [CLI 参考](../cli-reference) - 命令行工具完整文档

---

<a id='page-client-architecture'></a>

## 客户端架构

### 相关页面

相关主题：[项目介绍](#page-introduction), [请求流程与抽象层](#page-request-flow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)
- [src/together/abstract/api_requestor.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/api_requestor.py)
- [src/together/together_response.py](https://github.com/togethercomputer/together-python/blob/main/src/together/together_response.py)
- [src/together/resources/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/__init__.py)
- [src/together/resources/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)
- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)
- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)
- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)

</details>

# 客户端架构

## 概述

Together Python 客户端是一个轻量级且易于使用的 Python 库和命令行工具，为 Together AI 平台提供统一的 API 接口。该客户端架构采用分层设计，核心层负责 HTTP 通信和请求处理，资源层提供各类 AI 能力的抽象接口，CLI 层提供命令行交互能力。

客户端的核心设计目标包括：

- **简化 API 调用**：通过 Pythonic 的接口封装底层 HTTP 请求细节
- **支持同步和异步操作**：提供 `Together` 和 `AsyncTogether` 两种客户端实现
- **流式响应支持**：原生支持流式输出，便于实时展示生成结果
- **完整的类型提示**：使用 Pydantic 模型进行请求参数和响应数据的验证

资料来源：[src/together/client.py]()

## 架构分层

### 整体架构图

```mermaid
graph TD
    A[客户端入口] --> B[Together / AsyncTogether]
    B --> C[资源层 Resources]
    C --> D[Chat Completions]
    C --> E[Completions]
    C --> F[Embeddings]
    C --> G[Images]
    C --> H[Fine-tuning]
    C --> I[Files]
    C --> J[Rerank]
    B --> K[APIRequestor]
    K --> L[HTTP 请求处理]
    L --> M[Together API]
```

### 核心组件

| 组件名称 | 文件路径 | 职责描述 |
|---------|---------|---------|
| Together | client.py | 同步客户端入口，管理 API 密钥和资源实例 |
| AsyncTogether | client.py | 异步客户端入口，支持 asyncio 并发操作 |
| APIRequestor | abstract/api_requestor.py | HTTP 请求的实际执行者，处理认证、重试、超时 |
| TogetherResponse | together_response.py | 统一响应数据结构定义 |
| 资源类 | resources/*.py | 封装各类 AI 能力的业务逻辑 |

资料来源：[src/together/client.py](), [src/together/abstract/api_requestor.py]()

## 客户端初始化

### 基本用法

```python
from together import Together

# 使用环境变量中的 API Key
client = Together()

# 直接指定 API Key
client = Together(api_key="your-api-key-here")
```

客户端初始化时接受以下配置参数：

| 参数名 | 类型 | 默认值 | 说明 |
|-------|------|-------|------|
| api_key | str | None | Together API 密钥，默认从环境变量 `TOGETHER_API_KEY` 读取 |
| base_url | str | api.together.xyz | API 基础 URL |
| timeout | float | 600 | 请求超时时间（秒） |
| max_retries | int | 2 | 失败重试次数 |
| client | httpx.Client | None | 可自定义的 HTTP 客户端实例 |

资料来源：[src/together/client.py]()

### 异步客户端

```python
from together import AsyncTogether

async_client = AsyncTogether()

# 在 async 函数中使用
async def main():
    response = await async_client.chat.completions.create(
        model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
        messages=[{"role": "user", "content": "Hello!"}]
    )
```

异步客户端继承自 `AsyncHTTPHandler`，支持使用 `asyncio.gather` 等工具进行并发请求。

资料来源：[src/together/resources/__init__.py]()

## 请求处理流程

### 同步请求流程

```mermaid
sequenceDiagram
    participant C as Together 客户端
    participant R as Resources
    participant A as APIRequestor
    participant H as HTTP Handler
    
    C->>R: 调用 .chat.completions.create()
    R->>A: 创建 TogetherRequest
    A->>H: request_raw() / request()
    H->>H: 添加认证头
    H->>H: 处理重试逻辑
    H->>Together API: 发送 HTTP 请求
    Together API-->>H: 返回响应
    H-->>A: 解析响应数据
    A-->>R: 返回 TogetherResponse
    R-->>C: 转换为 Pydantic 模型
```

### 流式响应处理

```python
stream = client.completions.create(
    model="codellama/CodeLlama-34b-Python-hf",
    prompt="Write a Next.js component",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

流式响应使用生成器模式，逐块返回数据。每个 chunk 都是一个 `CompletionChunk` 或 `ChatCompletionChunk` 对象。

资料来源：[src/together/resources/completions.py](), [src/together/resources/chat/completions.py]()

## API 请求器

### APIRequestor 职责

`APIRequestor` 是底层的 HTTP 请求处理器，封装了所有与 Together API 的通信逻辑：

| 功能 | 说明 |
|-----|------|
| 认证处理 | 自动添加 Authorization 头和 Together-Version 头 |
| 重试机制 | 基于指数退避的自动重试 |
| 超时控制 | 支持可配置的总超时和连接超时 |
| 错误处理 | 将 HTTP 错误转换为 Python 异常 |
| 流式支持 | 处理 Server-Sent Events (SSE) 流 |

### 请求方法

```python
# 同步请求
response, status_code, duration = requestor.request(
    options=TogetherRequest(
        method="POST",
        url="chat/completions",
        params=payload,
    ),
)

# 原始响应（用于文件下载等场景）
raw_response = requestor.request_raw(
    options=TogetherRequest(
        method="GET",
        url=file_url,
        headers={"Range": "bytes=0-1"},
    ),
)
```

资料来源：[src/together/abstract/api_requestor.py]()

## 响应模型

### 统一响应结构

```mermaid
classDiagram
    class TogetherResponse {
        +Any data
        +int status_code
    }
    
    class ChatCompletionResponse {
        +str id
        +str object
        +int created
        +str model
        +list choices
        +Usage usage
    }
    
    class CompletionResponse {
        +str id
        +str object
        +int created
        +str model
        +list choices
        +Usage usage
    }
    
    TogetherResponse <|-- ChatCompletionResponse
    TogetherResponse <|-- CompletionResponse
```

### 响应模型字段

| 模型类 | 主要字段 | 说明 |
|-------|---------|------|
| ChatCompletionResponse | id, model, choices, usage | 聊天完成响应 |
| CompletionResponse | id, model, choices, usage | 文本补全响应 |
| EmbeddingResponse | data, model, usage | 向量嵌入响应 |
| ImageResponse | data | 图像生成响应 |
| Usage | prompt_tokens, completion_tokens, total_tokens | Token 使用统计 |

资料来源：[src/together/together_response.py]()

## 资源层设计

### 资源模块概览

```mermaid
graph TD
    Resources --> Chat
    Resources --> Completions
    Resources --> Embeddings
    Resources --> Images
    Resources --> Files
    Resources --> FineTuning
    Resources --> Rerank
    Resources --> Models
```

| 资源类 | 功能 | 核心方法 |
|-------|-----|---------|
| Chat | 聊天完成 | `create()`, `create_async()` |
| Completions | 文本补全 | `create()`, `create_async()` |
| Embeddings | 向量嵌入 | `create()` |
| Images | 图像生成 | `generate()` |
| Files | 文件管理 | `upload()`, `download()`, `list()`, `retrieve()`, `delete()` |
| FineTuning | 模型微调 | `create()`, `submit()`, `estimate_price()` |
| Rerank | 文档重排序 | `create()` |

资料来源：[src/together/resources/__init__.py]()

### 聊天完成资源

聊天完成是最常用的功能之一，支持多种消息格式和工具调用：

```python
# 简单文本消息
response = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=[{"role": "user", "content": "tell me about new york"}],
)

# 多模态消息（文本+图像）
response = client.chat.completions.create(
    model="meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {"type": "image_url", "image_url": {"url": "https://example.com/image.png"}}
        ]
    }]
)
```

资料来源：[src/together/resources/chat/completions.py]()

### 文件管理

文件管理模块提供完整的上传、下载、列表查询等功能：

```python
# 上传文件
response = client.files.upload(file=open("data.jsonl", "rb"))

# 检查文件
client.files.check(file_id)

# 下载文件内容
content = client.files.retrieve_content(file_id)

# 列出文件
files = client.files.list()
```

资料来源：[src/together/filemanager.py]()

## 错误处理

### 异常层次结构

```mermaid
classDiagram
    class TogetherException {
        +str message
        +Any http_status
        +Any body
    }
    
    class AuthenticationError {
        <<extends TogetherException>>
    }
    
    class RateLimitError {
        <<extends TogetherException>>
    }
    
    class APIConnectionError {
        <<extends TogetherException>>
    }
    
    class Timeout {
        <<extends TogetherException>>
    }
    
    class APIError {
        <<extends TogetherException>>
    }
```

### 异常类型说明

| 异常类 | HTTP 状态码 | 说明 |
|-------|------------|------|
| TogetherException | - | 所有异常的基类 |
| AuthenticationError | 401 | API 密钥无效或缺失 |
| RateLimitError | 429 | 请求频率超限 |
| APIConnectionError | - | 网络连接问题 |
| Timeout | - | 请求超时 |
| APIError | 4xx/5xx | 其他 API 错误 |

```python
from together.error import RateLimitError, AuthenticationError

try:
    response = client.chat.completions.create(
        model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
        messages=[{"role": "user", "content": "Hello"}],
    )
except AuthenticationError as e:
    print("Invalid API key")
except RateLimitError as e:
    print("Rate limit exceeded, please wait")
```

资料来源：[src/together/error.py]()

## 配置管理

### 环境变量

| 环境变量 | 说明 | 必需 |
|---------|-----|-----|
| TOGETHER_API_KEY | Together AI API 密钥 | 是 |
| TOGETHER_BASE_URL | API 基础 URL（可选） | 否 |

### 客户端配置示例

```python
from together import Together
import os

# 方式一：环境变量
client = Together()  # 自动读取 TOGETHER_API_KEY

# 方式二：直接传入
client = Together(api_key=os.environ.get("TOGETHER_API_KEY"))

# 方式三：自定义配置
client = Together(
    api_key="your-key",
    base_url="https://api.together.xyz",
    timeout=120,
    max_retries=3
)
```

资料来源：[src/together/client.py]()

## 最佳实践

### 1. 异步并发请求

```python
import asyncio
from together import AsyncTogether

async_client = AsyncTogether()

async def batch_requests():
    tasks = [
        async_client.chat.completions.create(
            model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
            messages=[{"role": "user", "content": prompt}],
        )
        for prompt in prompts
    ]
    responses = await asyncio.gather(*tasks)
    return responses
```

### 2. 流式响应处理

```python
stream = client.completions.create(
    model="codellama/CodeLlama-34b-Python-hf",
    prompt="Write a Next.js component",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

### 3. 错误重试机制

客户端内置自动重试机制，支持指数退避策略。默认配置：

- 最大重试次数：2
- 超时时间：600 秒
- 可通过自定义 httpx.Client 调整

资料来源：[src/together/abstract/api_requestor.py]()

## 扩展性

### 自定义 HTTP 客户端

```python
import httpx
from together import Together

# 使用自定义配置的 HTTP 客户端
custom_client = httpx.Client(
    timeout=httpx.Timeout(60.0, connect=10.0),
    proxies={"http://": "http://proxy.example.com:8080"},
)

client = Together(client=custom_client)
```

### 资源扩展

新功能可以通过扩展资源类来实现，所有资源类都遵循统一的接口模式：

```python
class BaseResource:
    def __init__(self, client: TogetherClient) -> None:
        self._client = client
```

资料来源：[src/together/resources/__init__.py]()

## 总结

Together Python 客户端采用清晰的分层架构设计，将 API 通信细节封装在 `APIRequestor` 中，对外提供直观的资源接口。核心设计原则包括：

1. **简洁易用**：通过高级抽象简化 API 调用复杂度
2. **类型安全**：使用 Pydantic 模型确保请求参数和响应数据的正确性
3. **灵活扩展**：分层设计便于添加新功能和自定义行为
4. **完善的错误处理**：层次化的异常体系便于精准捕获和处理错误

该架构既适合快速原型开发，也能满足生产环境对稳定性和性能的要求。

---

<a id='page-request-flow'></a>

## 请求流程与抽象层

### 相关页面

相关主题：[客户端架构](#page-client-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/together/abstract/api_requestor.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/api_requestor.py)
- [src/together/abstract/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/__init__.py)
- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)
- [src/together/together_response.py](https://github.com/togethercomputer/together-python/blob/main/src/together/together_response.py)
- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)
- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)
</details>

# 请求流程与抽象层

## 概述

Together Python SDK 的请求流程与抽象层是整个库的核心架构部分，负责处理所有与 Together API 的通信交互。该层通过分层设计实现了请求的发送、响应的处理、错误的捕获与转换，以及同步/异步操作的支持。开发者通过 `Together` 客户端实例发起各类请求（如聊天补全、文生图、嵌入等），而底层的抽象层则负责将高层 API 调用转换为底层的 HTTP 请求，并与 Together 服务器进行交互。

该架构的核心价值在于**解耦**与**统一**：上层资源（如 `Completions`、`Chat`、`Embeddings` 等）无需关心具体的网络通信细节，只需专注于业务逻辑参数的准备和响应数据的解析。所有底层网络通信、认证、超时重试等机制都由抽象层统一处理，确保了整个 SDK 的一致性与可维护性。

从架构层面看，Together SDK 采用了典型的**客户端-请求者-响应**三层模型。`Together` 客户端作为入口点，提供各类资源对象；资源对象负责构建请求参数并调用请求者；`APIRequestor` 则处理底层的 HTTP 通信，包括认证头的生成、请求发送、超时控制以及错误处理。最终，响应数据通过 `TogetherResponse` 和具体的响应模型类（如 `ChatCompletionResponse`、`CompletionResponse`）返回给调用者。

## 核心组件架构

Together SDK 的请求流程涉及多个核心组件，它们各司其职、协同工作。下表列出了主要组件及其职责：

| 组件 | 文件位置 | 职责描述 |
|------|----------|----------|
| `Together` | `client.py` | 主客户端入口，管理所有资源实例 |
| `APIRequestor` | `abstract/api_requestor.py` | 底层 HTTP 请求处理 |
| `TogetherResponse` | `together_response.py` | 原始响应包装器 |
| `TogetherRequest` | `abstract/` | 请求配置（URL、方法、参数） |
| 资源类 | `resources/*.py` | 各业务功能的参数构建与响应解析 |

`Together` 主类定义了所有支持的资源类型，包括 `completions`、`chat`、`embeddings`、`files`、`images`、`models`、`fine_tuning`、`rerank`、`audio`、`batches`、`code_interpreter`、`evaluation` 和 `videos`。每个资源都持有对底层客户端的引用，可以直接调用 `APIRequestor` 发起请求。这种设计使得添加新的 API 功能只需扩展资源类，而无需修改底层通信机制。

```mermaid
graph TD
    A[Together 客户端] --> B[资源层<br/>Completions/Chat/Embeddings...]
    B --> C[请求构建<br/>参数序列化]
    C --> D[APIRequestor<br/>抽象请求者]
    D --> E[HTTP 通信层<br/>requests/httpx]
    E --> F[Together API 服务器]
    F --> G[TogetherResponse<br/>原始响应]
    G --> H[响应解析<br/>Pydantic 模型]
    H --> I[业务响应对象<br/>ChatCompletion/Completion...]
```

## 请求流程详解

### 同步请求流程

同步请求是最基本的请求模式，适用于大多数使用场景。请求从客户端发起，经过资源层、请求构建层，最终由 `APIRequestor` 发送 HTTP 请求。以聊天补全为例，完整的请求流程如下：

1. **客户端实例化**：用户创建 `Together` 客户端实例，可传入 `api_key`、`base_url`、`timeout` 等配置参数。若未显式提供，`api_key` 会自动从环境变量 `TOGETHER_API_KEY` 获取。
2. **资源调用**：用户通过 `client.chat.completions.create()` 发起聊天补全请求，传入模型名称、消息列表等参数。
3. **参数构建**：资源类将用户参数转换为 API 所需的格式，包括默认值填充、参数校验和序列化。
4. **请求发送**：`APIRequestor` 接收 `TogetherRequest` 对象，构建完整的 HTTP 请求，包括认证头、内容类型等。
5. **响应处理**：服务器响应后，`APIRequestor` 将原始响应包装为 `TogetherResponse` 对象返回。
6. **结果解析**：资源类将 `TogetherResponse` 中的数据解析为具体的响应模型（如 `ChatCompletionResponse`），返回给用户。

在 `client.py` 中，`Together` 类的初始化逻辑展示了配置参数的优先级处理：

```python
def __init__(
    self,
    *,
    api_key: str | None = None,
    base_url: str | None = None,
    timeout: float | None = None,
    max_retries: int | None = None,
    supplied_headers: Dict[str, str] | None = None,
) -> None:
```

配置参数按照以下优先级获取：显式传入的参数 > 环境变量 > 默认值。这种设计既提供了灵活性，又保证了向后兼容性。

### 异步请求流程

Together SDK 完全支持异步操作，通过 `AsyncTogether` 类提供异步版本的客户端。异步请求在处理大量并发请求时具有显著优势，能够有效利用系统资源并提高吞吐量。

异步请求的核心差异在于 `APIRequestor` 使用 `arequest` 方法而非 `request` 方法。在 `resources/chat/completions.py` 中可以看到异步请求的实现模式：

```python
response, _, _ = await requestor.arequest(
    options=TogetherRequest(
        method="POST",
        url="chat/completions",
        params=parameter_payload,
    ),
    stream=stream,
)
```

异步方法返回协程对象，配合 `asyncio` 或 `aiohttp` 等异步框架使用。资源类可以将异步请求封装为异步生成器，便于处理流式响应。流式响应通过异步生成器实现，每次迭代返回一个新的响应块，直到所有数据发送完毕。

```mermaid
sequenceDiagram
    participant User as 用户代码
    participant Client as AsyncTogether
    participant Resource as 资源类
    participant Requestor as APIRequestor
    participant Server as Together API
    
    User->>Client: 异步调用
    Client->>Resource: create()
    Resource->>Resource: 构建参数
    Resource->>Requestor: arequest()
    Requestor->>Server: async HTTP POST
    Server-->>Requestor: 流式响应
    loop 流式处理
        Requestor-->>Resource: 异步生成器
        Resource-->>User: ChatCompletionChunk
    end
```

### 流式响应处理

流式响应是 Together API 的重要特性，特别适用于需要实时展示生成内容的场景，如聊天机器人和代码补全。SDK 对流式响应的处理采用了异步生成器模式，既保证了实时性，又提供了良好的编程接口。

在 `resources/completions.py` 中，流式响应的处理逻辑展示了响应类型的动态判断：

```python
if stream:
    # must be an iterator
    assert not isinstance(response, TogetherResponse)
    return (CompletionChunk(**line.data) async for line in response)
assert isinstance(response, TogetherResponse)
return CompletionResponse(**response.data)
```

当启用流式传输时，响应对象不再是单一的 `TogetherResponse`，而是变成了一个异步迭代器。每次迭代从服务器接收一个数据块，解析为对应的 Chunk 类型（如 `CompletionChunk` 或 `ChatCompletionChunk`）。这种设计允许用户实时处理响应数据，无需等待完整响应生成。

## 抽象层设计

### APIRequestor 职责

`APIRequestor` 是请求流程抽象层的核心组件，负责所有底层的 HTTP 通信逻辑。它封装了认证、请求发送、超时控制、重试机制和错误处理等复杂逻辑，为上层资源类提供简洁统一的接口。

`APIRequestor` 的主要职责包括：

- **认证管理**：自动从环境变量或客户端配置获取 API 密钥，生成符合 Together API 规范的认证头。在 `filemanager.py` 中可以看到认证头的生成方式：`together.utils.get_headers(method, requestor.api_key)`
- **请求发送**：支持同步的 `request` 方法和异步的 `arequest` 方法，处理不同类型的 HTTP 请求（GET、POST 等）
- **参数传递**：接收 `TogetherRequest` 对象作为请求配置，包含 URL、HTTP 方法、查询参数、请求体等
- **响应包装**：将原始 HTTP 响应转换为 `TogetherResponse` 对象，统一响应处理流程
- **错误转换**：捕获 HTTP 错误和业务错误，转换为合适的异常类型抛出

`APIRequestor` 的设计遵循了**单一职责原则**，将网络通信的复杂性隔离在抽象层内部。上层代码只需关注业务逻辑，无需直接处理 HTTP 协议的细节。这种设计也便于单元测试，因为可以使用 Mock 对象替代真实的网络请求。

### TogetherRequest 配置对象

`TogetherRequest` 是请求配置的数据类，封装了发起 HTTP 请求所需的所有信息。它是连接上层业务逻辑与底层网络通信的桥梁，确保了请求参数的完整性和一致性。

`TogetherRequest` 通常包含以下字段：

| 字段 | 类型 | 描述 |
|------|------|------|
| `method` | `str` | HTTP 方法（GET、POST、DELETE 等） |
| `url` | `str` | API 端点路径 |
| `params` | `Dict` | 查询参数或请求体数据 |
| `headers` | `Dict` | 自定义请求头 |
| `stream` | `bool` | 是否启用流式响应 |
| `override_headers` | `bool` | 是否覆盖默认头 |
| `allow_redirects` | `bool` | 是否允许重定向 |

通过使用 `model_dump(exclude_none=True)` 方法，可以方便地将请求配置序列化为字典，去除 `None` 值，保持请求体的简洁。

### TogetherResponse 响应包装

`TogetherResponse` 是对原始 HTTP 响应的封装类，它将底层的响应状态码、响应头和响应体统一包装在一起。这种设计简化了响应数据的访问方式，并提供了类型安全的数据访问接口。

`TogetherResponse` 的主要属性包括：

- **status_code**：HTTP 状态码，用于判断请求是否成功
- **headers**：响应头信息，包含内容类型、字符编码等元数据
- **data**：响应体数据，已经过 JSON 解析的字典或列表

在非流式响应场景下，资源类通过 `TogetherResponse.data` 访问响应内容，并使用 Pydantic 模型进行数据验证和解析。这种模式确保了响应数据的结构符合预期，提供了自动的类型转换和验证功能。

## 错误处理机制

### 异常层次结构

Together SDK 定义了一套完整的异常层次结构，从基类 `TogetherException` 派生出各类具体异常。这种设计允许调用者采用**宽捕获**或**精确捕获**的方式处理错误，既可以捕获所有 Together 相关错误，也可以针对特定错误类型进行处理。

在 `error.py` 中定义的主要异常类型包括：

| 异常类型 | 描述 | 典型场景 |
|----------|------|----------|
| `TogetherException` | 基类异常 | 所有异常的父类 |
| `AuthenticationError` | 认证错误 | API 密钥无效或缺失 |
| `RateLimitError` | 速率限制错误 | 请求频率超出限制 |
| `FileTypeError` | 文件类型错误 | 上传了不支持的文件格式 |
| `APIConnectionError` | 连接错误 | 网络连接失败 |
| `Timeout` | 超时错误 | 请求超时 |
| `APIError` | 通用 API 错误 | 服务器返回的错误响应 |

异常类的构造函数接收多种类型的消息参数，包括 `TogetherErrorResponse`（服务器返回的错误响应结构）、`Exception`（原始异常对象）、字符串消息或 `RequestException`。这种灵活性使得错误信息可以来自不同的来源，便于调试和日志记录。

### 错误处理流程

错误处理贯穿整个请求流程，在多个层面进行：

1. **HTTP 层错误捕获**：`APIRequestor` 捕获底层 HTTP 异常（如连接超时、DNS 解析失败等），转换为 `APIConnectionError` 或 `Timeout`。
2. **HTTP 状态码检查**：响应返回后检查状态码，非 2xx 状态码会触发异常。在 `filemanager.py` 中可以看到：`response.raise_for_status()` 用于触发 HTTP 状态码异常。
3. **业务错误解析**：Together API 返回的错误响应会解析为结构化的错误信息，便于调用者理解错误原因。
4. **重试机制**：`APIRequestor` 实现了一定的重试逻辑，对于临时性错误（如 503 Service Unavailable）会自动重试。

```mermaid
graph TD
    A[发起请求] --> B{网络正常?}
    B -->|否| C[APIConnectionError]
    B -->|是| D{状态码 2xx?}
    D -->|否| E{可重试状态码?}
    D -->|是| F{流式响应?}
    F -->|否| G[TogetherResponse]
    F -->|是| H[异步生成器]
    E -->|是| I[重试请求]
    E -->|否| J[APIError]
    I --> A
```

## 文件管理中的请求流程

文件管理模块展示了请求流程的另一个应用场景，包括文件上传、下载和元数据获取等操作。该模块使用了重定向机制来处理大文件上传，这是标准的 multipart/form-data 上传模式。

### 上传流程

文件上传采用了**重定向模式**：首先向 API 发起初始化请求，获取预签名的上传 URL；然后直接向该 URL 上传文件内容；最后确认上传完成。这种模式可以将大文件上传的负载分散到对象存储服务，减轻 API 服务器的压力。

在 `filemanager.py` 中，`get_upload_url` 方法展示了重定向流程的实现：

```python
response = requestor.request_raw(
    options=TogetherRequest(
        method=method,
        url=url,
        params=data,
        allow_redirects=False,
        override_headers=True,
        headers=headers,
    ),
    remaining_retries=MAX_RETRIES,
)
```

设置 `allow_redirects=False` 使得响应返回重定向头而非自动跟随，SDK 可以获取 `Location` 头获取实际的 upload URL 和文件 ID。

### 下载流程

文件下载支持断点续传和并发控制。通过发送 Range 请求获取文件大小信息，然后使用 `FileLock` 防止同一文件的并发下载。下载过程中使用临时文件，写入完成后原子性地重命名，确保文件完整性。

## 参数构建与序列化

资源类在发起请求前，需要将用户友好的参数转换为 API 所需的格式。这一过程包括默认值填充、参数校验、类型转换和序列化。

以聊天补全为例，参数构建在资源类中完成：

```python
parameter_payload = ChatCompletionCreateParams(
    model=model,
    messages=messages,
    temperature=temperature,
    max_tokens=max_tokens,
    top_p=top_p,
    ...
).model_dump(exclude_none=True)
```

使用 Pydantic 的 `model_dump(exclude_none=True)` 方法可以方便地生成 API 兼容的 JSON 字典，自动排除值为 `None` 的可选参数。这种模式既保证了参数的规范性，又提供了灵活的默认值处理。

## 总结

Together Python SDK 的请求流程与抽象层通过分层设计实现了优雅的架构：主客户端提供统一入口，资源类封装业务逻辑，请求者抽象处理底层通信细节。这种设计既保证了代码的可读性和可维护性，又为扩展新功能提供了清晰的方向。

核心的抽象包括 `APIRequestor` 负责 HTTP 通信、`TogetherRequest` 封装请求配置、`TogetherResponse` 包装响应数据、`TogetherException` 及其子类处理错误。这些组件协同工作，为开发者提供了简洁而强大的 API 调用体验。开发者无需关心网络通信的复杂性，只需关注业务逻辑的实现，通过高层 API 即可完成与 Together 平台的所有交互。

---

<a id='page-chat-completions'></a>

## 聊天补全 API

### 相关页面

相关主题：[文本补全 API](#page-completions), [多模态功能](#page-multimodal)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/together/resources/chat/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/__init__.py)
- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)
- [src/together/types/chat_completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/chat_completions.py)
- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)
- [src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)
</details>

# 聊天补全 API

## 概述

聊天补全 API（Chat Completions API）是 together-python 客户端库的核心功能之一，提供与 Together 平台上的大语言模型进行交互的统一接口。该 API 基于 OpenAI 兼容的聊天补全格式，支持文本对话、多模态输入（图像/视频）、流式输出、异步调用以及日志概率获取等高级功能。

在 together-python 架构中，`Together` 客户端类通过 `chat` 属性暴露聊天补全功能，底层由 `resources.Chat` 模块实现，具体逻辑封装在 `ChatCompletions` 类中。资料来源：[src/together/client.py:1-30](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)

## 核心组件架构

### 模块依赖关系

```mermaid
graph TD
    A[Together 客户端] --> B[resources.Chat]
    B --> C[ChatCompletions 类]
    C --> D[types/chat_completions.py]
    C --> E[requestor 请求模块]
    
    F[CLI chat 命令] --> C
```

### 客户端集成

`Together` 类在初始化时自动绑定所有资源端点，包括聊天补全功能：

| 属性 | 类型 | 说明 |
|------|------|------|
| `client.chat` | `resources.Chat` | 聊天补全 API 入口 |
| `client.completions` | `resources.Completions` | 文本补全 API |
| `client.embeddings` | `resources.Embeddings` | 向量嵌入 API |
| `client.images` | `resources.Images` | 图像生成 API |
| `client.fine_tuning` | `resources.FineTuning` | 微调 API |

资料来源：[src/together/client.py:10-22](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)

## 主要功能特性

### 1. 基础文本对话

聊天补全 API 支持最简单的文本消息交互，使用 `messages` 参数传递对话历史：

```python
from together import Together

client = Together()

response = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=[{"role": "user", "content": "tell me about new york"}],
)
print(response.choices[0].message.content)
```

资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)

### 2. 多模态消息支持

API 支持在同一请求中传递多种内容类型，包括文本、图像 URL 和视频 URL：

| 内容类型 | 类型标识 | 用途 |
|---------|---------|------|
| 纯文本 | `{"type": "text", "text": "..."}` | 普通文本消息 |
| 图像输入 | `{"type": "image_url", "image_url": {"url": "..."}}` | 视觉理解任务 |
| 视频输入 | `{"type": "video_url", "video_url": {"url": "..."}}` | 视频理解任务 |

#### 带图像的多模态示例

```python
response = client.chat.completions.create(
    model="meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "What's in this image?"
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png"
                }
            }
        ]
    }]
)
```

#### 带视频的多模态示例

```python
response = client.chat.completions.create(
    model="Qwen/Qwen2.5-VL-72B-Instruct",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "What's happening in this video?"
            },
            {
                "type": "video_url",
                "video_url": {
                    "url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4"
                }
            }
        ]
    }]
)
```

资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)

### 3. 流式输出

启用流式模式后，API 以增量方式返回生成的内容，适合需要实时展示的交互场景：

```python
stream = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=[{"role": "user", "content": "tell me about new york"}],
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)

### 4. 异步调用

通过 `AsyncTogether` 客户端实现并发请求处理：

```python
import asyncio
from together import AsyncTogether

async_client = AsyncTogether()

async def async_chat_completion(messages):
    tasks = [
        async_client.chat.completions.create(
            model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
            messages=[{"role": "user", "content": message}],
        )
        for message in messages
    ]
    responses = await asyncio.gather(*tasks)
    return responses
```

资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)

### 5. 日志概率（Logprobs）

Logprobs 功能允许获取 token 级别的生成概率，用于评估模型输出的置信度：

```python
response = client.chat.completions.create(
    model="meta-llama/Llama-3.2-3B-Instruct-Turbo",
    messages=[{"role": "user", "content": "tell me about new york"}],
    logprobs=1
)
```

日志概率的主要应用场景包括：

| 场景 | 说明 |
|-----|------|
| 置信度评估 | 判断模型对输出的自信程度 |
| 低置信度过滤 | 拒绝或重试概率较低的输出 |
| 模型集成 | 比较不同模型的概率分布 |

资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)

## API 参数详解

### 核心请求参数

| 参数名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `model` | `str` | 必填 | 模型标识符，如 `meta-llama/Llama-4-Scout-17B-16E-Instruct` |
| `messages` | `List[Dict]` | 必填 | 对话消息列表，每条包含 `role` 和 `content` |
| `max_tokens` | `int` | `None` | 最大生成 token 数 |
| `temperature` | `float` | `None` | 采样温度，控制随机性 |
| `top_p` | `float` | `None` | 核采样概率阈值 |
| `top_k` | `int` | `None` | Top-K 采样参数 |
| `stream` | `bool` | `False` | 是否启用流式输出 |
| `logprobs` | `int` | `None` | 返回 logprobs 的数量 |

资料来源：[src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)

### 惩罚参数

| 参数名 | 类型 | 说明 |
|--------|------|------|
| `repetition_penalty` | `float` | 重复惩罚系数 |
| `presence_penalty` | `float` | 存在惩罚（鼓励引入新话题） |
| `frequency_penalty` | `float` | 频率惩罚（降低高频词出现） |
| `min_p` | `float` | 最小概率阈值采样 |

资料来源：[src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)

### 高级参数

| 参数名 | 类型 | 说明 |
|--------|------|------|
| `echo` | `bool` | 是否回显输入 prompt |
| `n` | `int` | 生成数量 |
| `safety_model` | `str` | 安全审查模型标识 |
| `response_format` | `dict` | 响应格式约束（如 JSON mode） |
| `tools` | `List[Dict]` | 可用工具定义列表 |
| `tool_choice` | `str` | 工具选择策略 |
| `audio_url` | `List[str]` | 附加到用户消息的音频 URL |
| `multimodal_params` | `dict` | 多模态额外参数 |

资料来源：[src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)

## 请求处理流程

### 同步请求流程

```mermaid
sequenceDiagram
    participant Client as Together 客户端
    participant API as Chat Completions API
    participant Backend as Together 后端
    
    Client->>API: client.chat.completions.create(params)
    API->>API: 验证参数，构建请求
    API->>Backend: POST /chat/completions
    Backend-->>API: 返回 ChatCompletionResponse
    API-->>Client: 返回最终响应对象
    
    Note over API,Backend: stream=True 时
    API->>Backend: POST /chat/completions (stream=true)
    Backend-->>API: 流式事件流
    API-->>Client: 异步生成器 (AsyncGenerator)
```

### 响应对象结构

```python
ChatCompletionResponse {
    id: str                    # 请求唯一标识
    object: str                # 对象类型
    created: int               # 创建时间戳
    model: str                 # 实际使用的模型
    choices: List[Choice]      # 生成结果列表
    usage: Usage               # Token 使用统计
}

Choice {
    index: int                 # 结果索引
    message: Message           # 完整消息内容
    logprobs: Logprobs | None  # 日志概率（可选）
    finish_reason: str         # 结束原因
}
```

资料来源：[src/together/types/chat_completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/chat_completions.py)

## CLI 命令行接口

通过 `together` CLI 可以直接调用聊天补全功能：

```bash
together chat.completions \
  --message "What is machine learning?" \
  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --max-tokens 512
```

### CLI 可用选项

| CLI 选项 | 对应参数 | 说明 |
|---------|---------|------|
| `--message` | `messages` | 消息内容（可多次指定） |
| `--model` | `model` | 模型名称 |
| `--max-tokens` | `max_tokens` | 最大 token 数 |
| `--stop` | `stop` | 停止序列 |
| `--temperature` | `temperature` | 采样温度 |
| `--top-p` | `top_p` | 核采样概率 |
| `--top-k` | `top_k` | Top-K 采样 |
| `--no-stream` | `stream=False` | 禁用流式输出 |
| `--logprobs` | `logprobs` | 返回 logprobs |
| `--safety-model` | `safety_model` | 安全模型 |
| `--audio-url` | `audio_url` | 音频 URL |

资料来源：[src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)

## 完整使用示例

### 示例一：基础聊天

```python
from together import Together

client = Together(api_key="your-api-key")

response = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What are the top 3 things to do in San Francisco?"}
    ],
    temperature=0.7,
    max_tokens=256
)

print(response.choices[0].message.content)
```

### 示例二：多轮对话

```python
messages = [
    {"role": "system", "content": "You are a Python expert."},
    {"role": "user", "content": "Explain what a decorator is."},
    {"role": "assistant", "content": "A decorator in Python is a function that..."},
    {"role": "user", "content": "Give me an example."}
]

response = client.chat.completions.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    messages=messages
)
```

### 示例三：并发请求

```python
import asyncio
from together import AsyncTogether

async def batch_chat():
    async_client = AsyncTogether()
    
    queries = [
        "What is AI?",
        "What is ML?",
        "What is DL?"
    ]
    
    tasks = [
        async_client.chat.completions.create(
            model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
            messages=[{"role": "user", "content": q}]
        )
        for q in queries
    ]
    
    results = await asyncio.gather(*tasks)
    
    for i, response in enumerate(results):
        print(f"Q{i+1}: {queries[i]}")
        print(f"A{i+1}: {response.choices[0].message.content}\n")

asyncio.run(batch_chat())
```

## 错误处理

聊天补全 API 可能抛出的异常类型定义于 `src/together/error.py`：

| 异常类型 | 说明 |
|---------|------|
| `AuthenticationError` | API 密钥无效或缺失 |
| `RateLimitError` | 请求频率超限 |
| `APIConnectionError` | 网络连接错误 |
| `Timeout` | 请求超时 |
| `TogetherException` | 基础异常类 |

```python
from together import Together
from together.error import RateLimitError, AuthenticationError

client = Together()

try:
    response = client.chat.completions.create(
        model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
        messages=[{"role": "user", "content": "Hello"}]
    )
except AuthenticationError:
    print("请检查 API 密钥是否正确设置")
except RateLimitError:
    print("请求频率超限，请稍后重试")
except Exception as e:
    print(f"发生错误: {e}")
```

资料来源：[src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)

## 最佳实践

1. **环境变量配置**：将 API 密钥存储在环境变量 `TOGETHER_API_KEY` 中，避免硬编码
2. **流式响应处理**：对于长文本生成，使用流式模式提升用户体验
3. **错误重试**：结合指数退避策略处理临时性网络错误
4. **资源清理**：异步操作完成后确保正确关闭连接
5. **多模态优化**：图像输入时使用合理的分辨率以平衡质量和延迟

## 相关资源

- SDK 文档：[Together Python SDK](https://github.com/togethercomputer/together-python)
- API 平台：[api.together.xyz](https://api.together.xyz/)
- 模型列表：`together models list` 或 `client.models.list()`

---

<a id='page-completions'></a>

## 文本补全 API

### 相关页面

相关主题：[聊天补全 API](#page-chat-completions)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/together/resources/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)
- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)
- [src/together/cli/api/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/completions.py)
- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)
- [src/together/types/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/completions.py)
- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)
</details>

# 文本补全 API

## 概述

文本补全 API（Completions API）是 Together Python 客户端库的核心功能之一，提供对大型语言模型文本生成能力的访问。该 API 允许开发者通过简单的接口调用，向 Together 平台上的各种语言模型发送补全请求，并获取生成的文本内容。

## 核心组件架构

文本补全 API 的架构涉及多个协同工作的组件，从客户端入口到最终的 API 请求处理。

```mermaid
graph TD
    A[开发者代码] --> B[Together 客户端实例]
    B --> C[completions 资源对象]
    C --> D[Completions.create 方法]
    D --> E[请求参数构建]
    E --> F[API 请求发送]
    F --> G[Together API 服务器]
    G --> H[CompletionResponse]
    H --> I[开发者获取结果]
    
    style A fill:#e1f5fe
    style G fill:#fff3e0
    style I fill:#e8f5e9
```

### 主要组件说明

| 组件 | 文件位置 | 职责 |
|------|----------|------|
| Together 客户端 | `src/together/client.py` | 作为统一的 API 入口点 |
| Completions 资源 | `src/together/resources/completions.py` | 实现补全功能的核心逻辑 |
| CLI 命令 | `src/together/cli/api/completions.py` | 命令行接口实现 |
| 类型定义 | `src/together/types/completions.py` | 请求和响应数据模型 |

## 客户端集成

Together 主客户端类通过 `completions` 属性集成了文本补全功能。

```python
class Together:
    completions: resources.Completions
    # ... 其他资源
```

资料来源：[src/together/client.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)

### 初始化与认证

客户端支持通过多种方式配置 API 密钥：

```python
from together import Together

# 方式一：通过参数直接传入
client = Together(api_key="your-api-key")

# 方式二：通过环境变量自动读取
# 需要设置 TOGETHER_API_KEY 环境变量
client = Together()
```

## API 方法详解

### 创建补全请求

`completions.create()` 是文本补全 API 的核心方法，支持同步和流式两种模式。

#### 方法签名

```python
async def create(
    self,
    *,
    model: str,
    prompt: str,
    max_tokens: int | None = None,
    temperature: float | None = None,
    top_p: int | None = None,
    top_k: int | None = None,
    stop: str | list[str] | None = None,
    repetition_penalty: float | None = None,
    presence_penalty: float | None = None,
    frequency_penalty: float | None = None,
    min_p: float | None = None,
    stream: bool = False,
    logprobs: int | None = None,
    echo: bool = False,
    n: int | None = None,
    safety_model: str | None = None,
    response_format: dict | None = None,
    tools: list[dict] | None = None,
    tool_choice: str | dict | None = None,
    **kwargs,
) -> CompletionResponse | AsyncGenerator[CompletionChunk, None]
```

资料来源：[src/together/resources/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)

#### 参数说明

| 参数名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `model` | str | 必需 | 模型标识符，如 `meta-llama/Llama-4-Scout-17B-16E-Instruct` |
| `prompt` | str | 必需 | 输入提示文本 |
| `max_tokens` | int | None | 生成令牌的最大数量 |
| `temperature` | float | None | 采样温度，控制随机性 |
| `top_p` | int | None | Nucleus 采样阈值 |
| `top_k` | float | None | Top-K 采样参数 |
| `stop` | str \| list[str] | None | 停止生成的字符串或字符串列表 |
| `repetition_penalty` | float | None | 重复惩罚系数 |
| `presence_penalty` | float | None | 存在惩罚系数 |
| `frequency_penalty` | float | None | 频率惩罚系数 |
| `min_p` | float | None | 最小概率阈值 |
| `stream` | bool | False | 是否启用流式输出 |
| `logprobs` | int | None | 返回的对数概率数量 |
| `echo` | bool | False | 是否回显输入提示 |
| `n` | int | None | 生成数量 |
| `safety_model` | str | None | 安全模型标识 |
| `response_format` | dict | None | 响应格式规范 |
| `tools` | list[dict] | None | 可用工具列表 |
| `tool_choice` | str \| dict | None | 工具选择策略 |

## 使用模式

### 基础文本补全

最基本的文本补全调用，返回完整的补全结果：

```python
from together import Together

client = Together()

response = client.completions.create(
    model="codellama/CodeLlama-34b-Python-hf",
    prompt="Write a Next.js component with TailwindCSS for a header component.",
    max_tokens=512,
)

print(response.choices[0].text)
```

资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)

### 流式输出

流式模式允许实时获取生成的令牌，适合需要即时反馈的场景：

```python
from together import Together

client = Together()

stream = client.completions.create(
    model="codellama/CodeLlama-34b-Python-hf",
    prompt="Write a Next.js component with TailwindCSS for a header component.",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)

#### 流式输出流程图

```mermaid
sequenceDiagram
    participant 客户端
    participant API
    participant 模型
    
    客户端->>API: POST /completions (stream=True)
    API->>模型: 转发请求
    模型-->>API: 流式令牌 1
    API-->>客户端: CompletionChunk 1
    模型-->>API: 流式令牌 2
    API-->>客户端: CompletionChunk 2
    模型-->>API: 流式令牌 N
    API-->>客户端: CompletionChunk N
    模型-->>API: [DONE]
    API-->>客户端: 流结束信号
```

### 异步并发请求

对于需要同时处理多个补全请求的场景，可以使用异步客户端：

```python
import asyncio
from together import AsyncTogether

async_client = AsyncTogether()

prompts = [
    "Write a Next.js component with TailwindCSS for a header component.",
    "Write a python function for the fibonacci sequence",
]

async def async_completions(prompts):
    tasks = [
        async_client.completions.create(
            model="codellama/CodeLlama-34b-Python-hf",
            prompt=prompt,
        )
        for prompt in prompts
    ]
    responses = await asyncio.gather(*tasks)

    for response in responses:
        print(response.choices[0].text)

asyncio.run(async_completions(prompts))
```

资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)

## CLI 命令行接口

Together CLI 提供了命令行方式的文本补全功能：

```bash
together completions \
  "Large language models are " \
  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --max-tokens 512 \
  --stop "."
```

资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)

### CLI 参数选项

| CLI 选项 | 对应 API 参数 | 说明 |
|----------|---------------|------|
| `--model` | model | 模型名称 |
| `--max-tokens` | max_tokens | 最大令牌数 |
| `--stop` | stop | 停止序列 |
| `--temperature` | temperature | 采样温度 |
| `--top-p` | top_p | Nucleus 采样 |
| `--top-k` | top_k | Top-K 采样 |
| `--repetition-penalty` | repetition_penalty | 重复惩罚 |
| `--presence-penalty` | presence_penalty | 存在惩罚 |
| `--frequency-penalty` | frequency_penalty | 频率惩罚 |
| `--no-stream` | stream=False | 禁用流式输出 |
| `--logprobs` | logprobs | 返回对数概率 |
| `--echo` | echo | 回显提示 |
| `--n` | n | 生成数量 |
| `--safety-model` | safety_model | 安全模型 |
| `--raw` | - | 输出原始 JSON |

资料来源：[src/together/cli/api/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/completions.py)

## 响应数据结构

### 完整响应

当 `stream=False` 时，返回 `CompletionResponse` 对象：

```python
@dataclass
class CompletionResponse:
    id: str
    choices: List[CompletionChoice]
    model: str
    usage: CompletionUsage
    created: int
    object: str = "text_completion"
```

### 流式响应

当 `stream=True` 时，返回 `CompletionChunk` 对象的异步生成器：

```python
@dataclass
class CompletionChunk:
    id: str
    choices: List[CompletionChoicesChunk]
    model: str
    created: int
    object: str = "text_completion.chunk"
```

每个 `CompletionChoicesChunk` 包含 `delta` 字段，其中 `delta.content` 包含新生成的文本片段：

```python
for chunk in stream:
    assert isinstance(chunk, CompletionChunk)
    if chunk.choices and chunk.choices[0].delta:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

资料来源：[src/together/resources/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)

## 错误处理

文本补全 API 可能抛出多种异常类型，继承自 `TogetherException` 基类：

```mermaid
graph TD
    A[TogetherException] --> B[RateLimitError]
    A --> C[AuthenticationError]
    A --> D[APIConnectionError]
    A --> E[Timeout]
    A --> F[InvalidRequestError]
```

| 异常类型 | 说明 | 处理建议 |
|----------|------|----------|
| `RateLimitError` | 请求频率超限 | 实现退避重试机制 |
| `AuthenticationError` | 认证失败 | 检查 API 密钥配置 |
| `APIConnectionError` | 网络连接问题 | 检查网络状态 |
| `Timeout` | 请求超时 | 增加超时时间或重试 |
| `InvalidRequestError` | 请求参数错误 | 检查参数有效性 |

资料来源：[src/together/error.py:1-100](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)

### 错误处理示例

```python
from together import Together
from together.error import RateLimitError, APIConnectionError

client = Together()

try:
    response = client.completions.create(
        model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
        prompt="Hello, world!",
    )
except RateLimitError:
    print("请求频率超限，请稍后重试")
except APIConnectionError:
    print("网络连接失败，请检查网络")
except Exception as e:
    print(f"发生错误: {e}")
```

## 最佳实践

### 参数调优建议

| 使用场景 | 推荐参数配置 |
|----------|--------------|
| 代码生成 | `temperature=0.2`, `max_tokens=1024` |
| 创意写作 | `temperature=0.8-1.0`, `top_p=0.95` |
| 问答系统 | `temperature=0.3`, `max_tokens=256` |
| 摘要生成 | `temperature=0.3`, `presence_penalty=0.1` |

### 性能优化

1. **使用流式输出**：对于需要实时反馈的场景，启用 `stream=True`
2. **合理设置 max_tokens**：避免生成过长文本造成不必要的资源消耗
3. **使用异步客户端**：处理批量请求时使用 `AsyncTogether`
4. **缓存模型响应**：对于相同提示的重复请求考虑实现缓存机制

### 安全考虑

1. **设置 safety_model**：对敏感内容使用安全模型过滤
2. **限制输出长度**：通过 `max_tokens` 控制最大生成长度
3. **使用停止序列**：通过 `stop` 参数避免生成不期望的内容

---

<a id='page-multimodal'></a>

## 多模态功能

### 相关页面

相关主题：[聊天补全 API](#page-chat-completions)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/together/resources/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/images.py)
- [src/together/resources/code_interpreter.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/code_interpreter.py)
- [src/together/resources/videos.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/videos.py)
- [src/together/resources/audio/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/audio/__init__.py)
- [src/together/types/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/images.py)
- [examples/code_interpreter_demo.py](https://github.com/togethercomputer/together-python/blob/main/examples/code_interpreter_demo.py)
</details>

# 多模态功能

Together Python SDK 提供了丰富的多模态功能，支持文本、图像、视频和音频等多种模态的数据处理与生成。这些功能通过统一的客户端接口暴露，使开发者能够便捷地调用各种多模态 AI 能力。

## 功能概述

Together Python SDK 的多模态功能主要包括以下几个模块：

| 模块 | 功能描述 | 主要类/方法 |
|------|----------|-------------|
| 图像生成 | 根据文本描述生成图像 | `client.images.generate()` |
| 聊天多模态 | 支持文本+图像的对话 | `client.chat.completions.create()` |
| 代码解释器 | 执行多模态代码 | `client.code_interpreter` |
| 视频生成 | 生成视频内容 | `client.videos` |
| 音频处理 | 音频相关功能 | `client.audio` |

资料来源：[src/together/client.py:25-38](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)

## 架构设计

### 客户端架构

Together SDK 采用模块化架构，各个多模态功能通过独立的资源类实现：

```mermaid
graph TD
    A[Together 客户端] --> B[chat 聊天模块]
    A --> C[images 图像模块]
    A --> D[code_interpreter 代码解释器]
    A --> E[videos 视频模块]
    A --> F[audio 音频模块]
    
    B --> B1[文本处理]
    B --> B2[多图像处理]
    
    C --> C1[图像生成]
    C --> C2[参考图像支持]
```

## 图像生成功能

### 基本用法

图像生成模块允许通过文本提示词生成图像，支持自定义模型、尺寸、步数和数量等参数。

```python
from together import Together

client = Together()

response = client.images.generate(
    prompt="space robots",
    model="stabilityai/stable-diffusion-xl-base-1.0",
    steps=10,
    n=4,
)
print(response.data[0].b64_json)
```

资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)

### CLI 使用方式

通过命令行也可以调用图像生成功能：

```bash
together images generate \
  "space robots" \
  --model stabilityai/stable-diffusion-xl-base-1.0 \
  --n 4
```

### 图像生成参数

| 参数名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| prompt | str | 必需 | 图像生成提示词 |
| model | str | 必需 | 使用的模型名称 |
| steps | int | 20 | 生成步数 |
| seed | int | None | 随机种子，用于复现 |
| n | int | 1 | 生成图像数量 |
| height | int | 1024 | 图像高度 |
| width | int | 1024 | 图像宽度 |
| negative_prompt | str | None | 负面提示词 |
| response_format | str | None | 返回格式 |

资料来源：[src/together/resources/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/images.py)

### 请求处理流程

```mermaid
sequenceDiagram
    participant Client
    participant Images
    participant APIRequestor
    participant Together API
    
    Client->>Images: images.generate(prompt, model, ...)
    Images->>Images: 构建 ImageRequest
    Images->>APIRequestor: arequest(POST, images/generations)
    APIRequestor->>Together API: HTTP POST
    Together API-->>APIRequestor: ImageResponse
    APIRequestor-->>Images: TogetherResponse
    Images-->>Client: ImageResponse
```

## 聊天多模态功能

### 多模态消息格式

聊天模块支持多模态消息，消息内容可以是纯文本，也可以是包含文本和图像URL的列表结构。

```python
from together import Together

client = Together()

response = client.chat.completions.create(
    model="meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "What's in this image?"
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://example.com/image.png"
                }
            }
        ]
    }]
)
print(response.choices[0].message.content)
```

资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)

### 内容类型验证

系统对多模态内容有严格的验证规则：

| 规则 | 说明 |
|------|------|
| 类型限制 | `content` 字段支持字符串或字典列表 |
| 有效类型 | `text` 和 `image_url` 两种类型 |
| 图像位置 | 仅用户消息可包含图像 |
| 图像编码 | 图像必须为 base64 编码 |
| 大小限制 | base64 编码后小于 10MB |
| 数量限制 | 每条消息最多 3 张图像 |

资料来源：[src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)

### 数据格式示例

```python
# 单文本消息
{"role": "user", "content": "普通文本消息"}

# 多模态消息（文本+图像）
{
    "role": "user",
    "content": [
        {"type": "text", "text": "描述这张图片"},
        {"type": "image_url", "image_url": {"url": "https://..."}}
    ]
}
```

## 代码解释器

代码解释器模块支持执行包含多模态数据的代码，能够处理图像等多媒体内容。

```python
from together import Together

client = Together()

response = client.code_interpreter.run(
    input="分析这张图片并返回描述",
    images=[base64_image_data],
    model="codellama/CodeLlama-34b-Python-hf",
)
print(response)
```

资料来源：[examples/code_interpreter_demo.py](https://github.com/togethercomputer/together-python/blob/main/examples/code_interpreter_demo.py)

## 视频生成功能

视频生成模块提供视频内容创作能力：

```python
from together import Together

client = Together()

response = client.videos.generate(
    prompt="宇航员在太空站工作",
    model="some-video-model",
    duration=5,
)
```

资料来源：[src/together/resources/videos.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/videos.py)

## 音频功能

音频模块支持音频相关的数据处理：

```python
from together import Together

client = Together()

# 音频相关功能调用
response = client.audio.transcribe(
    file="audio.wav",
    model="whisper-model"
)
```

资料来源：[src/together/resources/audio/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/audio/__init__.py)

## 工作流程图

### 多模态请求处理流程

```mermaid
graph TD
    A[开始请求] --> B[验证 API Key]
    B --> C[构建请求参数]
    C --> D{请求类型}
    
    D -->|图像生成| E[调用 images.generate]
    D -->|聊天多模态| F[调用 chat.completions.create]
    D -->|代码解释| G[调用 code_interpreter.run]
    D -->|视频生成| H[调用 videos.generate]
    
    E --> I[POST /images/generations]
    F --> J[POST /chat/completions]
    G --> K[POST /code_interpreter]
    H --> L[POST /videos/generations]
    
    I --> M[返回 ImageResponse]
    J --> N[返回 ChatCompletionResponse]
    K --> O[返回执行结果]
    L --> P[返回 VideoResponse]
    
    M --> Q[结束]
    N --> Q
    O --> Q
    P --> Q
```

## 错误处理

SDK 提供了多层次的错误处理机制：

| 错误类型 | 说明 |
|----------|------|
| `RateLimitError` | 请求频率超限 |
| `FileTypeError` | 文件类型不支持 |
| `Timeout` | 请求超时 |
| `APIConnectionError` | API 连接错误 |
| `InvalidFileFormatError` | 文件格式无效 |

资料来源：[src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)

## 最佳实践

1. **图像大小优化**：在上传图像前进行压缩，避免超过 10MB 限制
2. **提示词编写**：使用清晰、具体的描述以获得更好的生成效果
3. **种子使用**：当需要复现结果时，设置固定的 seed 值
4. **批量处理**：利用 `n` 参数一次性生成多张图像，提高效率

## 总结

Together Python SDK 的多模态功能提供了统一、便捷的接口来访问各种生成式 AI 能力。通过模块化的设计，开发者可以根据需求灵活调用图像生成、多模态聊天、代码解释器、视频生成和音频处理等功能。所有功能都遵循一致的 API 设计规范，便于集成到各类应用场景中。

---

<a id='page-embeddings-rerank'></a>

## 嵌入与重排序

### 相关页面

相关主题：[文本补全 API](#page-completions)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)
- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)
- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)
</details>

# 嵌入与重排序

## 概述

嵌入（Embeddings）与重排序（Reranking）是 Together Python 库中用于增强检索能力的两大核心功能模块。它们共同构成了语义搜索和文档匹配的技术基础，使开发者能够将文本转换为高维向量表示，并通过相关性评分对候选结果进行排序优化。

Together Python 客户端通过统一的接口封装了这些功能，支持同步和异步两种调用方式，便于集成到各类应用场景中。嵌入功能主要用于将文本转换为稠密向量，而重排序功能则在此基础上对检索结果进行二次优化，提升最终结果的相关性。

## 架构设计

### 客户端集成

Together 客户端类在初始化时自动配置了嵌入和重排序资源。客户端采用模块化设计，将不同功能封装为独立的资源类，通过统一的方式对外提供服务。

```mermaid
graph TD
    A[Together 客户端] --> B[Embeddings 嵌入模块]
    A --> C[Rerank 重排序模块]
    B --> D[向量嵌入生成]
    C --> E[相关性评分计算]
    D --> F[语义相似度匹配]
    E --> G[结果重排序]
    F --> G
```

客户端类中声明了以下相关属性，用于支持嵌入和重排序功能：

| 模块 | 类型 | 用途 |
|------|------|------|
| embeddings | resources.Embeddings | 文本向量化嵌入生成 |
| rerank | resources.Rerank | 文档相关性评分与重排序 |

资料来源：[src/together/client.py:18-35]()

### 错误处理机制

嵌入与重排序模块共享统一的异常处理体系。所有自定义异常均继承自 `TogetherException` 基类，确保错误信息的一致性和可追溯性。

| 异常类型 | 适用场景 |
|----------|----------|
| TogetherException | 所有异常的基类 |
| RateLimitError | 请求频率超限时触发 |
| APIConnectionError | 网络连接异常时触发 |
| Timeout | 请求超时情况 |
| FileTypeError | 文件类型不匹配时触发 |

资料来源：[src/together/error.py:1-60]()

## 嵌入功能详解

### 功能概述

嵌入功能将文本转换为固定维度的稠密向量，这种向量表示能够捕捉文本的语义信息。在自然语言处理领域，向量嵌入是语义搜索、文本相似度计算、聚类分析等任务的基础。通过 Together 平台提供的嵌入模型，开发者可以将任意文本转换为可计算的数值向量。

### 使用方式

#### 基础用法

```python
from typing import List
from together import Together

client = Together()

def get_embeddings(texts: List[str], model: str) -> List[List[float]]:
    texts = [text.replace("\n", " ") for text in texts]
    outputs = client.embeddings.create(model=model, input=texts)
    return [outputs.data[i].embedding for i in range(len(texts))]

input_texts = ['Our solar system orbits the Milky Way galaxy at about 515,000 mph']
embeddings = get_embeddings(input_texts, model='togethercomputer/m2-bert-80M-8k-retrieval')
```

资料来源：[README.md:65-75]()

#### 核心参数说明

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| model | str | 是 | 嵌入模型标识符 |
| input | List[str] | 是 | 待编码的文本列表 |

#### 处理流程

嵌入处理流程包含以下关键步骤：

1. **文本预处理**：移除换行符等特殊字符，确保输入格式统一
2. **API 调用**：通过 `client.embeddings.create()` 发起请求
3. **响应解析**：从返回结果中提取 `embedding` 向量数据
4. **结果返回**：以浮点数列表形式输出向量

### 支持的模型

Together 平台提供多种嵌入模型，常见选择包括 `togethercomputer/m2-bert-80M-8k-retrieval` 等专门针对检索任务优化的模型。开发者可根据精度、速度和成本需求选择合适的模型。

## 重排序功能详解

### 功能概述

重排序（Reranking）是信息检索领域的重要技术。当初始检索返回多个候选文档后，重排序模型会对这些文档进行相关性评分，并按照评分高低重新排列，从而将最相关的文档优先展示给用户。

Together 平台集成了高质量的重排序模型（如 Salesforce/Llama-Rank-V1），能够显著提升检索系统的最终效果。重排序通常作为第二阶段处理，位于初步向量检索之后。

### 使用方式

```python
from typing import List
from together import Together

client = Together()

def get_reranked_documents(
    query: str, 
    documents: List[str], 
    model: str, 
    top_n: int = 3
) -> List[str]:
    outputs = client.rerank.create(
        model=model, 
        query=query, 
        documents=documents, 
        top_n=top_n
    )
    # sort by relevance score and returns the original docs
    return [
        documents[i] 
        for i in [x.index for x in sorted(
            outputs.results, 
            key=lambda x: x.relevance_score, 
            reverse=True
        )]
    ]

query = "What is the capital of the United States?"
documents = ["New York", "Washington, D.C.", "Los Angeles"]

reranked_documents = get_reranked_documents(
    query, 
    documents, 
    model='Salesforce/Llama-Rank-V1', 
    top_n=1
)
```

资料来源：[README.md:80-100]()

#### 核心参数说明

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| model | str | 是 | 重排序模型标识符 |
| query | str | 是 | 查询文本 |
| documents | List[str] | 是 | 待排序的文档列表 |
| top_n | int | 否 | 返回的最相关文档数量，默认返回全部 |

#### 返回结果结构

重排序结果包含每个文档的索引位置和相关性评分：

| 字段 | 类型 | 说明 |
|------|------|------|
| index | int | 原始文档列表中的位置 |
| relevance_score | float | 相关性评分，数值越高越相关 |

## 组合工作流

嵌入与重排序通常组合使用，形成完整的检索管道。这种两阶段检索架构能够兼顾召回率和精确率：

```mermaid
graph LR
    A[用户查询] --> B[嵌入阶段]
    B --> C[向量相似度检索]
    C --> D[候选文档集]
    D --> E[重排序阶段]
    E --> F[最终排序结果]
    
    G[文档库] --> H[文档嵌入]
    H --> C
```

### 典型应用场景

| 场景 | 嵌入作用 | 重排序作用 |
|------|----------|------------|
| 语义搜索 | 将查询和文档转为向量 | 对初步结果进行相关性优化 |
| 推荐系统 | 用户和物品向量化 | 精细化排序提升推荐准确度 |
| 问答系统 | 问题与答案片段编码 | 排序最相关的答案片段 |

## 异步调用支持

Together Python 库同时支持异步调用方式，便于在异步应用框架中集成使用。异步客户端 `AsyncTogether` 提供了与非异步版本相同的接口设计，确保开发体验的一致性。

```python
import asyncio
from together import AsyncTogether

async_client = AsyncTogether()

async def async_rerank_example(query: str, documents: List[str]):
    results = await async_client.rerank.create(
        model='Salesforce/Llama-Rank-V1',
        query=query,
        documents=documents,
        top_n=5
    )
    return results
```

## 最佳实践

### 文本预处理

在调用嵌入功能前，建议对输入文本进行标准化处理：

- 移除多余的换行符和空白字符
- 统一文本编码格式
- 限制单条文本的最大长度以符合模型要求

### 性能优化建议

| 优化方向 | 具体措施 |
|----------|----------|
| 批处理 | 批量提交嵌入请求以减少网络开销 |
| 缓存 | 对频繁查询的嵌入结果进行缓存 |
| 模型选择 | 根据精度需求选择合适的模型规格 |
| top_n 参数 | 仅获取必要的重排序结果数量 |

### 错误处理

集成时应妥善处理各类异常情况：

- 网络异常：实现重试机制
- 频率限制：遵守 API 调用频率约束
- 输入验证：确保文档列表非空且格式正确

## 相关资源

更多关于嵌入和重排序的详细文档，请参考 Together 官方文档：

- [嵌入功能概述](https://docs.together.ai/docs/rerank-overview)
- [微调功能与文件上传](https://docs.together.ai/docs/fine-tuning-python)

资料来源：[README.md:100-102]()

---

<a id='page-files-management'></a>

## 文件管理

### 相关页面

相关主题：[模型微调](#page-finetuning)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/together/resources/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/files.py)
- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)
- [src/together/types/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/files.py)
- [src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)
</details>

# 文件管理

Together Python SDK 提供了一套完整的文件管理功能，用于支持模型微调、数据上传、文件检索与删除等操作。该模块是整个 SDK 与 Together AI 平台进行数据交互的重要桥梁。

## 功能概述

Together AI 的文件管理 API 主要服务于以下核心场景：

1. **微调数据管理**：上传训练数据集以进行模型微调
2. **文件元数据查询**：查看已上传文件的详细信息
3. **文件内容检索**：获取已上传文件的具体内容
4. **存储空间管理**：删除不再需要的文件以释放空间

文件管理模块在整个 SDK 架构中属于基础资源层，被 `FineTuning`（微调）和 `Files`（文件）两个核心资源类所依赖。客户端通过 `Together` 类的 `files` 属性访问这些功能。

```mermaid
graph LR
    A[用户代码] --> B[Together 客户端]
    B --> C[Files 资源类]
    C --> D[Together API]
    D --> E[(远程存储)]
    
    F[CLI 命令] --> C
    G[微调模块] --> C
```

## 核心组件

### Files 资源类

`Files` 资源类封装了所有与文件操作相关的 API 方法。资料来源：[src/together/resources/files.py]()

| 方法名 | 功能描述 |
|--------|----------|
| `upload()` | 上传本地文件到 Together 服务器 |
| `list()` | 列出当前账户下的所有文件 |
| `retrieve()` | 获取指定文件的元数据 |
| `retrieve_content()` | 下载并返回文件内容 |
| `delete()` | 删除指定文件 |

### 文件类型定义

Together SDK 使用 `FilePurpose` 枚举定义文件的用途类别。资料来源：[src/together/types/files.py]()

| 枚举值 | 用途说明 |
|--------|----------|
| `fine-tunes` | 微调训练数据 |
| `batch` | 批量处理任务 |
| `evaluation` | 模型评估数据 |

### 错误处理

文件管理模块定义了专门的异常类用于处理各类错误情况。资料来源：[src/together/error.py]()

| 异常类 | 触发场景 |
|--------|----------|
| `FileTypeError` | 文件类型不符合要求 |
| `InvalidFileFormatError` | 文件格式验证失败 |
| `APIConnectionError` | API 连接异常 |

## Python API 使用

### 初始化客户端

```python
from together import Together

client = Together()
```

### 上传文件

使用 `files.upload()` 方法将本地文件上传至服务器：

```python
response = client.files.upload(
    file="somedata.jsonl",
    purpose="fine-tunes"  # 可选，默认为 fine-tunes
)
```

上传时系统会自动进行文件格式校验。资料来源：[README.md]() 和 [src/together/utils/files.py]()

### 列出文件

获取账户下所有已上传文件的列表：

```python
response = client.files.list()
```

返回结果包含每个文件的元数据信息，包括文件名、创建时间、文件大小等。

### 检索文件元数据

通过文件 ID 获取特定文件的详细信息：

```python
response = client.files.retrieve(
    id="file-d0d318cb-b7d9-493a-bd70-1cfe089d3815"
)
```

### 获取文件内容

下载并读取已上传文件的实际内容：

```python
content = client.files.retrieve_content(
    id="file-d0d318cb-b7d9-493a-bd70-1cfe089d3815"
)
```

### 删除文件

从服务器删除指定文件以释放存储空间：

```python
client.files.delete(
    id="file-d0d318cb-b7d9-493a-bd70-1cfe089d3815"
)
```

## CLI 命令行接口

Together SDK 提供了命令行工具用于文件管理操作。资料来源：[src/together/cli/api/files.py]()

### 基本命令结构

```bash
together files <子命令>
```

### 查看帮助

```bash
together files --help
```

### 检查文件

在上传前验证本地文件格式是否正确：

```bash
together files check example.jsonl
```

### 上传文件

将本地文件上传至 Together 服务器：

```bash
together files upload example.jsonl
```

支持指定文件用途：

```bash
together files upload example.jsonl --purpose fine-tunes
```

### 列出文件

显示账户下所有已上传文件：

```bash
together files list
```

### 检索文件元数据

获取特定文件的详细信息：

```bash
together files retrieve file-6f50f9d1-5b95-416c-9040-0799b2b4b894
```

### 检索文件内容

下载并显示文件内容：

```bash
together files retrieve-content file-6f50f9d1-5b95-416c-9040-0799b2b4b894
```

### 删除文件

从服务器删除指定文件：

```bash
together files delete file-6f50f9d1-5b95-416c-9040-0799b2b4b894
```

## 文件格式校验

Together SDK 在文件上传前会进行严格的格式验证，确保数据符合微调要求。资料来源：[src/together/utils/files.py]()

### JSONL 格式验证

上传的文件必须符合 JSONL（JSON Lines）格式规范：

- 每行必须是有效的 JSON 对象
- 文件扩展名应为 `.jsonl`
- 支持单行或多行 JSON 格式

### 多模态内容验证

对于包含多模态内容的文件，系统会进行以下校验：

| 校验项 | 说明 |
|--------|------|
| 内容类型 | 必须是 `text` 或 `image_url` |
| 图片数量 | 每个示例最多包含规定数量的图片 |
| Base64 长度 | Base64 编码的图片数据需小于 10MB |
| 角色限制 | 图片只能出现在 `user` 角色的消息中 |

### 错误处理机制

校验失败时会抛出 `InvalidFileFormatError` 异常，包含以下详细信息：

- 错误发生的行号
- 错误类型标识
- 具体的错误描述

## 与微调模块的集成

文件管理模块与微调功能紧密集成，是进行模型微调的前置步骤。资料来源：[src/together/resources/finetune.py]()

### 典型工作流程

```mermaid
graph TD
    A[准备训练数据] --> B[上传文件]
    B --> C[获取 file ID]
    C --> D[创建微调任务]
    D --> E[监控训练进度]
    E --> F[下载微调模型]
```

### 训练文件引用

在创建微调任务时，通过 `training_file` 参数引用已上传文件的 ID：

```python
client.fine_tuning.create(
    training_file="file-xxxxx",
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct"
)
```

## 配置与参数

### 客户端初始化参数

| 参数名 | 类型 | 说明 | 默认值 |
|--------|------|------|--------|
| `api_key` | str | API 密钥 | 环境变量 TOGETHER_API_KEY |
| `base_url` | str | API 基础地址 | 环境变量 TOGETHER_BASE_URL |
| `timeout` | float | 请求超时时间 | 600 秒 |
| `max_retries` | int | 最大重试次数 | 2 |

### 文件上传参数

| 参数名 | 类型 | 说明 | 必填 |
|--------|------|------|------|
| `file` | str/Path | 本地文件路径 | 是 |
| `purpose` | str | 文件用途 | 否 |
| `check` | bool | 是否校验文件格式 | 否（默认 True） |

## 最佳实践

### 数据准备

1. **文件格式**：使用标准 JSONL 格式，每行一个 JSON 对象
2. **数据清洗**：确保数据编码为 UTF-8，避免特殊字符问题
3. **文件大小**：建议单个文件不超过 100MB

### 上传策略

1. **预校验**：使用 `check` 参数在上传说进行格式验证
2. **分批处理**：大量数据建议分批上传
3. **错误处理**：捕获并处理 `InvalidFileFormatError` 异常

### 存储管理

1. **定期清理**：删除已完成微调的临时文件
2. **命名规范**：使用有意义的文件名便于识别
3. **记录追踪**：保存 file ID 以便后续引用

## 相关资源

- [微调文档](https://docs.together.ai/docs/fine-tuning-python)
- [Together API 文档](https://docs.together.ai/reference)
- [GitHub 仓库](https://github.com/togethercomputer/together-python)

---

<a id='page-finetuning'></a>

## 模型微调

### 相关页面

相关主题：[文件管理](#page-files-management)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/together/resources/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)
- [src/together/cli/api/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)
- [src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)
- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)
- [src/together/types/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/finetune.py)
</details>

# 模型微调

## 概述

模型微调（Fine-Tuning）是 Together Python SDK 中用于自定义预训练语言模型行为的核心功能模块。通过微调，用户可以使用自己的数据集对 Together 平台上托管的预训练模型进行定制化训练，使其更好地适应特定任务场景，如特定领域的问答、代码生成、内容分类等。

Together SDK 提供了完整的微调工作流支持，涵盖从训练任务提交、检查点管理到模型部署的全生命周期管理。

---

## 核心组件

### 主要类和方法

| 组件 | 位置 | 说明 |
|------|------|------|
| `FineTuning` | `src/together/resources/finetune.py` | 微调核心资源类，提供所有微调相关操作 |
| `_parse_raw_checkpoints` | `src/together/resources/finetune.py:78-97` | 解析检查点元数据的辅助函数 |
| `FinetuneCheckpoint` | `src/together/types/finetune.py` | 检查点数据模型 |

### 异常处理体系

微调过程中可能遇到的异常类型定义于 `src/together/error.py`：

| 异常类 | 说明 | 触发场景 |
|--------|------|----------|
| `TogetherException` | 基异常类 | 通用错误 |
| `RateLimitError` | 速率限制错误 | API 请求频率超限 |
| `FileTypeError` | 文件类型错误 | 上传文件格式不支持 |
| `APIConnectionError` | 连接错误 | 无法建立 API 连接 |
| `Timeout` | 超时错误 | 请求响应超时 |

---

## 微调参数配置

### 基础训练参数

```python
from together import Together

client = Together()

response = client.fine_tuning.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    training_file="file-xxx",
    validation_file="file-yyy",
    n_epochs=3,
    batch_size=4,
    learning_rate=1e-5,
    n_checkpoints=1
)
```

### 完整参数表

| 参数名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `model` | `str` | 必填 | 基础模型名称 |
| `training_file` | `str` | 必填 | 训练数据文件 ID |
| `validation_file` | `str` | 可选 | 验证数据文件 ID |
| `n_epochs` | `int` | - | 训练轮数 |
| `n_evals` | `int` | - | 评估频率 |
| `n_checkpoints` | `int` | - | 保存的检查点数量 |
| `batch_size` | `int` | - | 批处理大小 |
| `learning_rate` | `float` | - | 学习率 |
| `lr_scheduler_type` | `str` | - | 学习率调度器类型 |
| `min_lr_ratio` | `float` | - | 最小学习率比例 |
| `scheduler_num_cycles` | `int` | - | 调度器循环次数 |
| `warmup_ratio` | `float` | - | 预热比例 |
| `max_grad_norm` | `float` | - | 梯度裁剪最大值 |
| `weight_decay` | `float` | - | 权重衰减系数 |
| `suffix` | `str` | - | 输出模型名称后缀 |

*资料来源：[src/together/resources/finetune.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*

---

## LoRA 微调配置

Together SDK 支持 Low-Rank Adaptation（LoRA）高效微调方法，显著降低训练参数量和计算成本。

### LoRA 相关参数

| 参数名 | 类型 | 说明 |
|--------|------|------|
| `lora` | `bool` | 是否启用 LoRA |
| `lora_r` | `int` | LoRA 秩（rank） |
| `lora_dropout` | `float` | LoRA dropout 率 |
| `lora_alpha` | `float` | LoRA alpha 值 |
| `lora_trainable_modules` | `str` | 可训练的模块名称 |

### 配置示例

```python
response = client.fine_tuning.create(
    model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
    training_file="file-xxx",
    lora=True,
    lora_r=8,
    lora_alpha=16,
    lora_dropout=0.05
)
```

*资料来源：[src/together/resources/finetune.py:30-35](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*

---

## 高级训练配置

### DPO/RLHF 训练

Together 支持直接偏好优化（DPO）和相关强化学习方法：

| 参数名 | 说明 |
|--------|------|
| `training_method` | 训练方法（标准/DPO/SimPO/RPO 等） |
| `dpo_beta` | DPO 的 beta 参数 |
| `dpo_normalize_logratios_by_length` | 是否按长度归一化 |
| `rpo_alpha` | RPO alpha 参数 |
| `simpo_gamma` | SimPO gamma 参数 |

### 多模态训练

| 参数名 | 类型 | 说明 |
|--------|------|------|
| `train_vision` | `bool` | 是否训练视觉编码器 |
| `multimodal_params` | `dict` | 多模态相关参数 |

### Weights & Biases 集成

| 参数名 | 说明 |
|--------|------|
| `wandb_api_key` | W&B API 密钥 |
| `wandb_base_url` | W&B 基础 URL |
| `wandb_project_name` | W&B 项目名称 |
| `wandb_name` | W&B 运行名称 |

### 其他高级参数

| 参数名 | 说明 |
|--------|------|
| `train_on_inputs` | 是否在输入上训练（支持 auto 自动判断） |
| `from_checkpoint` | 从指定检查点继续训练 |
| `from_hf_model` | 从 Hugging Face 模型开始训练 |
| `hf_model_revision` | Hugging Face 模型版本 |
| `hf_api_token` | Hugging Face API 令牌 |
| `hf_output_repo_name` | Hugging Face 输出仓库名称 |

*资料来源：[src/together/resources/finetune.py:36-56](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*

---

## 检查点管理

### 检查点解析机制

`_parse_raw_checkpoints` 函数负责解析服务器返回的检查点元数据：

```python
def _parse_raw_checkpoints(
    checkpoints: List[Dict[str, str]], id: str
) -> List[FinetuneCheckpoint]:
    parsed_checkpoints = []
    for checkpoint in checkpoints:
        step = checkpoint["step"]
        checkpoint_type = checkpoint["checkpoint_type"]
        checkpoint_name = (
            f"{id}:{step}" if "intermediate" in checkpoint_type.lower() else id
        )

        parsed_checkpoints.append(
            FinetuneCheckpoint(
                type=checkpoint_type,
                timestamp=checkpoint["created_at"],
                name=checkpoint_name,
            )
        )

    parsed_checkpoints.sort(key=lambda x: x.timestamp, reverse=True)
    return parsed_checkpoints
```

检查点按时间戳降序排列，最新的检查点排在前面。

*资料来源：[src/together/resources/finetune.py:78-97](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*

### 检查点类型

| 类型 | 说明 | 适用场景 |
|------|------|----------|
| `default` | 默认检查点 | 标准训练 |
| `intermediate` | 中间检查点 | 定期保存 |
| `merged` | 合并检查点 | LoRA 适配器与基础模型合并 |
| `adapter` | 适配器检查点 | 仅 LoRA 权重 |

---

## CLI 微调命令

Together CLI 提供了完整的微调命令行接口。

### 查看帮助

```bash
together fine-tuning --help
```

### 下载微调检查点

```bash
together fine-tuning download <FINE_TUNE_ID> \
  --output_dir ./checkpoints \
  --checkpoint-step 1000 \
  --checkpoint-type merged
```

| CLI 参数 | 说明 |
|----------|------|
| `--output_dir` / `-o` | 输出目录路径 |
| `--checkpoint-step` / `-s` | 检查点步数（默认最新） |
| `--checkpoint-type` | 检查点类型 |

*资料来源：[src/together/cli/api/finetune.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)*

### 删除微调任务

```bash
together fine-tuning delete <FINE_TUNE_ID> --force
```

| CLI 参数 | 说明 |
|----------|------|
| `--force` | 强制删除，无需确认 |
| `--quiet` / `-y` | 静默模式，不提示确认 |

*资料来源：[src/together/cli/api/finetune.py:60-80](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)*

---

## 数据格式验证

Together SDK 在 `src/together/utils/files.py` 中实现了严格的数据格式验证机制。

### 支持的数据格式

微调数据必须符合特定的 JSON 格式要求：

1. **文本消息**
```json
{
  "type": "text",
  "text": "用户输入内容"
}
```

2. **多模态消息**（仅支持用户角色）
```json
{
  "type": "image_url",
  "image_url": {
    "url": "https://..."
  }
}
```

### 验证规则

| 规则 | 错误类型 | 说明 |
|------|----------|------|
| 内容必须为 dict | `InvalidFileFormatError` | JSON 结构错误 |
| 必须包含 `type` 字段 | `InvalidFileFormatError` | 缺少类型标识 |
| 文本内容必须为字符串 | `InvalidFileFormatError` | 文本格式错误 |
| 图片仅限用户消息 | `InvalidFileFormatError` | 角色限制 |
| 图片 URL 必须为字典 | `InvalidFileFormatError` | URL 格式错误 |
| Base64 图片最大 10MB | `InvalidFileFormatError` | 文件过大 |
| 每条消息最多 10 张图片 | `InvalidFileFormatError` | 图片数量超限 |

*资料来源：[src/together/utils/files.py:1-80](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)*

---

## 价格估算机制

在提交微调任务前，SDK 会自动进行价格估算：

```python
if from_checkpoint is None and from_hf_model is None:
    price_estimation_result = self.estimate_price(
        training_file=training_file,
        validation_file=validation_file,
        model=model_name,
        n_epochs=finetune_request.n_epochs,
        n_evals=finetune_request.n_evals,
        training_type="lora" if lora else "full",
        training_method=training_method,
    )
    price_limit_passed = price_estimation_result.allowed_to_proceed
else:
    price_limit_passed = True
```

价格估算基于以下因素：
- 训练文件大小
- 验证文件大小
- 模型类型
- 训练轮数
- 评估次数
- 训练类型（全量/LoRA）
- 训练方法

*资料来源：[src/together/resources/finetune.py:60-73](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*

---

## 异步操作支持

Together SDK 提供异步客户端用于并发微调任务管理：

```python
import asyncio
from together import AsyncTogether

async_client = AsyncTogether()

async def fine_tune_multiple():
    tasks = [
        async_client.fine_tuning.create(
            model="meta-llama/Llama-4-Scout-17B-16E-Instruct",
            training_file=file_id,
        )
        for file_id in training_files
    ]
    results = await asyncio.gather(*tasks)
```

---

## 工作流程图

```mermaid
graph TD
    A[准备训练数据] --> B[上传数据文件]
    B --> C{选择训练方式}
    C -->|全量微调| D[设置基础参数]
    C -->|LoRA| E[配置 LoRA 参数]
    C -->|DPO/SimPO| F[配置强化学习参数]
    D --> G[价格估算]
    E --> G
    F --> G
    G --> H{价格限制检查}
    H -->|通过| I[提交训练任务]
    H -->|超出| J[调整参数或确认]
    J --> G
    I --> K[监控训练进度]
    K --> L[生成检查点]
    L --> M{训练完成?}
    M -->|否| K
    M -->|是| N[下载最终模型]
    N --> O[部署使用]
```

---

## 最佳实践

### 1. 数据准备
- 确保训练数据格式正确，参考数据格式验证章节
- 使用验证集监控训练效果
- 数据量建议不少于 1000 条样本

### 2. 参数选择
- 首次尝试使用默认参数
- LoRA 微调时，`lora_r` 通常设置在 8-16 之间
- 学习率建议从 1e-5 开始，逐步调整

### 3. 检查点管理
- 设置合理的 `n_checkpoints` 值
- 定期保存中间检查点便于恢复
- 使用 `--checkpoint-type merged` 获取可直接部署的模型

### 4. 成本控制
- 充分利用价格估算功能
- 从检查点继续训练可节省成本
- 使用 `wandb` 监控训练过程

---

## 错误处理

微调过程中可能遇到的常见错误及解决方案：

| 错误类型 | 可能原因 | 解决方案 |
|----------|----------|----------|
| `FileTypeError` | 数据文件格式不支持 | 确保文件为 JSONL 格式 |
| `RateLimitError` | API 请求过于频繁 | 降低请求频率 |
| `Timeout` | 训练任务超时 | 减少训练数据量或轮数 |
| `APIConnectionError` | 网络连接问题 | 检查网络设置和 API 密钥 |

---

---

## Doramagic 踩坑日志

项目：togethercomputer/together-python

摘要：发现 12 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。

## 1. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作: 假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:624113979 | https://github.com/togethercomputer/together-python | README/documentation is current enough for a first validation pass.

## 2. 运行坑 · 来源证据：v.1.5.31

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.31
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ec69ff431b15448799cc64a826efd011 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 运行坑 · 来源证据：v.1.5.33

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.33
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8246897bffc548df9673fe0c390cb514 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 4. 运行坑 · 来源证据：v1.5.28

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v1.5.28
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_7e7977d7006e43939b5ceb03d0efad33 | https://github.com/togethercomputer/together-python/releases/tag/v1.5.28 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 5. 维护坑 · 来源证据：v.1.5.29

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v.1.5.29
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e91b0421f8fe42ac815a709d90dcca27 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 6. 维护坑 · 来源证据：v1.5.27

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v1.5.27
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_569e5bacb3584ae794141c49af91c5db | https://github.com/togethercomputer/together-python/releases/tag/v1.5.27 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 7. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作: 维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | last_activity_observed missing

## 8. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作: 下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium

## 9. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作: 评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium

## 10. 安全/权限坑 · 来源证据：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4b91e5a8164f4aa9910f3d9737f1995c | https://github.com/togethercomputer/together-python/issues/443 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 11. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作: issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | issue_or_pr_quality=unknown

## 12. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | release_recency=unknown

<!-- canonical_name: togethercomputer/together-python; human_manual_source: deepwiki_human_wiki -->
