{
  "canonical_name": "togethercomputer/together-python",
  "compilation_id": "pack_681354e095314331b25d65e0162e0351",
  "created_at": "2026-05-21T18:15:34.160010+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `pip install --upgrade together` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "pip install --upgrade together",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_8ce244b520ec47c1acdfe28cfb8d85a0"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_b67ba7b229507b688e60a55d4cef8f17",
    "canonical_name": "togethercomputer/together-python",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/togethercomputer/together-python",
    "slug": "together-python",
    "source_packet_id": "phit_b9b517287f514299a3551bc0cdd193d2",
    "source_validation_id": "dval_31d14fc791254a9b98e59b395f9c91c3"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 local_cli的用户",
    "github_forks": 24,
    "github_stars": 81,
    "one_liner_en": "<div align=\"center\">",
    "one_liner_zh": "<div align=\"center\">",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "medium",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:git, cli"
    },
    "target_user": "使用 local_cli 等宿主 AI 的用户",
    "title_en": "together-python",
    "title_zh": "together-python 能力包",
    "visible_tags": [
      {
        "label_en": "Knowledge Retrieval",
        "label_zh": "知识检索",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-knowledge-retrieval",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Retrieval Augmentation",
        "label_zh": "检索增强",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-retrieval-augmentation",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_b9b517287f514299a3551bc0cdd193d2",
  "page_model": {
    "artifacts": {
      "artifact_slug": "together-python",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "pip install --upgrade together",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/togethercomputer/together-python#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "知识检索",
        "知识库问答",
        "检索增强",
        "断点恢复流程",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 local_cli的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "<div align=\"center\">"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "local_cli",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:624113979 | https://github.com/togethercomputer/together-python | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.31",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_ec69ff431b15448799cc64a826efd011 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v.1.5.31",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.33",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_8246897bffc548df9673fe0c390cb514 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v.1.5.33",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v1.5.28",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_7e7977d7006e43939b5ceb03d0efad33 | https://github.com/togethercomputer/together-python/releases/tag/v1.5.28 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v1.5.28",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v.1.5.29",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_e91b0421f8fe42ac815a709d90dcca27 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v.1.5.29",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v1.5.27",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_569e5bacb3584ae794141c49af91c5db | https://github.com/togethercomputer/together-python/releases/tag/v1.5.27 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v1.5.27",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_4b91e5a8164f4aa9910f3d9737f1995c | https://github.com/togethercomputer/together-python/issues/443 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 12 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 45,
        "forks": 24,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 81
      },
      "source_url": "https://github.com/togethercomputer/together-python",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "<div align=\"center\">",
      "title": "together-python 能力包",
      "trial_prompt": "# together-python - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 together-python 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的软件开发与交付任务。\n我常用的宿主 AI：Local CLI\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 示例引导, 判断线索。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- 安装前能力预览: <div align=\"center\"> 输入：用户任务, 当前 AI 对话上下文；输出：示例引导, 判断线索。\n\n【必须安装后才可验证的能力】\n- 命令行启动或安装流程: 项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 输入：终端环境, 包管理器, 项目依赖；输出：安装结果, 列表/更新/运行结果。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. page-introduction：项目介绍。围绕“项目介绍”模拟一次用户任务，不展示安装或运行结果。\n2. page-installation：安装与配置。围绕“安装与配置”模拟一次用户任务，不展示安装或运行结果。\n3. page-client-architecture：客户端架构。围绕“客户端架构”模拟一次用户任务，不展示安装或运行结果。\n4. page-chat-completions：聊天补全 API。围绕“聊天补全 API”模拟一次用户任务，不展示安装或运行结果。\n5. page-completions：文本补全 API。围绕“文本补全 API”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. page-introduction\n输入：用户提供的“项目介绍”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. page-installation\n输入：用户提供的“安装与配置”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. page-client-architecture\n输入：用户提供的“客户端架构”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. page-chat-completions\n输入：用户提供的“聊天补全 API”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. page-completions\n输入：用户提供的“文本补全 API”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / page-introduction：Step 1 必须围绕“项目介绍”形成一个小中间产物，并等待用户确认。\n- Step 2 / page-installation：Step 2 必须围绕“安装与配置”形成一个小中间产物，并等待用户确认。\n- Step 3 / page-client-architecture：Step 3 必须围绕“客户端架构”形成一个小中间产物，并等待用户确认。\n- Step 4 / page-chat-completions：Step 4 必须围绕“聊天补全 API”形成一个小中间产物，并等待用户确认。\n- Step 5 / page-completions：Step 5 必须围绕“文本补全 API”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n- 涉及安装、插件加载、工具调用或外部服务的能力必须安装后验证。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/togethercomputer/together-python\n- https://github.com/togethercomputer/together-python#readme\n- README.md\n- src/together/__init__.py\n- src/together/version.py\n- pyproject.toml\n- src/together/constants.py\n- src/together/client.py\n- src/together/abstract/api_requestor.py\n- src/together/together_response.py\n- src/together/resources/__init__.py\n- src/together/resources/chat/__init__.py\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 together-python 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: `LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`（https://github.com/togethercomputer/together-python/issues/443）；github/github_release: v1.5.35（https://github.com/togethercomputer/together-python/releases/tag/v1.5.35）；github/github_release: v.1.5.33（https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33）；github/github_release: v.1.5.31（https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31）；github/github_release: v.1.5.29（https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29）；github/github_release: v1.5.28（https://github.com/togethercomputer/together-python/releases/tag/v1.5.28）；github/github_release: v1.5.27（https://github.com/togethercomputer/together-python/releases/tag/v1.5.27）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`",
              "url": "https://github.com/togethercomputer/together-python/issues/443"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v1.5.35",
              "url": "https://github.com/togethercomputer/together-python/releases/tag/v1.5.35"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v.1.5.33",
              "url": "https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v.1.5.31",
              "url": "https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v.1.5.29",
              "url": "https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v1.5.28",
              "url": "https://github.com/togethercomputer/together-python/releases/tag/v1.5.28"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v1.5.27",
              "url": "https://github.com/togethercomputer/together-python/releases/tag/v1.5.27"
            }
          ],
          "status": "已收录 7 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "<div align=\"center\">",
      "effort": "安装已验证",
      "forks": 24,
      "icon": "code",
      "name": "together-python 能力包",
      "risk": "可发布",
      "slug": "together-python",
      "stars": 81,
      "tags": [
        "知识检索",
        "知识库问答",
        "检索增强",
        "断点恢复流程",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/togethercomputer/together-python 项目说明书\n\n生成时间: 2026-05-21 18:14:28 UTC\n\n## 目录\n\n- [项目介绍](#page-introduction)\n- [安装与配置](#page-installation)\n- [客户端架构](#page-client-architecture)\n- [请求流程与抽象层](#page-request-flow)\n- [聊天补全 API](#page-chat-completions)\n- [文本补全 API](#page-completions)\n- [多模态功能](#page-multimodal)\n- [嵌入与重排序](#page-embeddings-rerank)\n- [文件管理](#page-files-management)\n- [模型微调](#page-finetuning)\n\n<a id='page-introduction'></a>\n\n## 项目介绍\n\n### 相关页面\n\n相关主题：[安装与配置](#page-installation), [客户端架构](#page-client-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n- [src/together/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/__init__.py)\n- [CONTRIBUTING.md](https://github.com/togethercomputer/together-python/blob/main/CONTRIBUTING.md)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/resources/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)\n- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n</details>\n\n# 项目介绍\n\nTogether Python 是一个开源的 Python 客户端库和命令行工具，用于与 Together AI 平台进行交互。该项目提供了对 Together AI 强大语言模型、嵌入模型、图像生成和微调服务的便捷访问能力。\n\n## 项目概述\n\nTogether Python 由 Together Computer 团队开发和维护，旨在为开发者提供一套完整、简洁的 API 接口，使其能够轻松地将 Together AI 平台的各种 AI 能力集成到自己的应用程序中。\n\n### 核心特性\n\n| 特性 | 说明 |\n|------|------|\n| **Python 客户端** | 面向对象的 Python API，简化与 Together AI 的交互 |\n| **CLI 工具** | 命令行界面，支持快速调用和脚本集成 |\n| **流式输出** | 支持实时流式 token 输出 |\n| **异步支持** | 提供异步客户端，支持并发请求处理 |\n| **多模态支持** | 支持文本、图像等多种输入类型 |\n| **微调服务** | 提供完整的模型微调工作流 |\n\n资料来源：[README.md:1-30]()\n\n## 项目架构\n\nTogether Python 采用模块化设计，主要包含以下几个核心组件：\n\n### 架构图\n\n```mermaid\ngraph TD\n    subgraph \"客户端层\"\n        Python[Python 客户端]\n        CLI[CLI 命令行工具]\n        Async[异步客户端]\n    end\n    \n    subgraph \"资源模块\"\n        Chat[Chat Completions]\n        Completions[Completions]\n        Embeddings[Embeddings]\n        Images[Images]\n        Rerank[Reranking]\n        FineTuning[Fine-Tuning]\n    end\n    \n    subgraph \"核心层\"\n        Requestor[API Requestor]\n        FileManager[文件管理器]\n        Error[错误处理]\n    end\n    \n    subgraph \"Together AI 平台\"\n        API[REST API]\n        Models[模型服务]\n    end\n    \n    Python --> Chat\n    Python --> Completions\n    Python --> Embeddings\n    Python --> Images\n    Python --> Rerank\n    Python --> FineTuning\n    \n    CLI --> Chat\n    CLI --> Completions\n    CLI --> FineTuning\n    \n    Async --> Chat\n    Async --> Completions\n    \n    Chat --> Requestor\n    Completions --> Requestor\n    Embeddings --> Requestor\n    Images --> Requestor\n    Rerank --> Requestor\n    FineTuning --> Requestor\n    \n    Requestor --> API\n    FineTuning --> FileManager\n    FileManager --> API\n    API --> Models\n```\n\n### 核心模块说明\n\n#### 异常处理模块\n\n项目定义了一套完整的异常类型体系，用于处理各种错误场景：\n\n| 异常类型 | 说明 |\n|---------|------|\n| `TogetherException` | 基础异常类 |\n| `RateLimitError` | 速率限制错误 |\n| `FileTypeError` | 文件类型错误 |\n| `APIConnectionError` | API 连接错误 |\n| `Timeout` | 超时错误 |\n\n资料来源：[src/together/error.py:1-60]()\n\n#### 聊天补全模块\n\n提供 Chat Completions API 接口，支持多种消息格式和工具调用：\n\n```python\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n)\n```\n\n资料来源：[README.md:30-40]()\n\n#### 微调模块\n\n提供完整的模型微调工作流程，包括价格估算、训练配置和检查点管理：\n\n| 参数 | 说明 |\n|------|------|\n| `n_epochs` | 训练轮数 |\n| `batch_size` | 批处理大小 |\n| `learning_rate` | 学习率 |\n| `lora` | 是否启用 LoRA |\n| `training_method` | 训练方法（DPO、SimPO 等）|\n\n资料来源：[src/together/resources/finetune.py:1-100]()\n\n## 主要功能\n\n### 1. 对话补全（Chat Completions）\n\n支持单轮和多轮对话，以及多模态输入（文本+图像）：\n\n```mermaid\ngraph LR\n    A[用户消息] --> B[构建消息列表]\n    B --> C[API 请求]\n    C --> D{流式?}\n    D -->|是| E[流式响应]\n    D -->|否| F[完整响应]\n    E --> G[逐块处理]\n    F --> H[返回完整结果]\n```\n\n资料来源：[src/together/resources/chat/completions.py:1-50]()\n\n### 2. 补全（Completions）\n\n提供传统的文本补全功能：\n\n```python\nresponse = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    max_tokens=200,\n)\n```\n\n资料来源：[README.md:80-90]()\n\n### 3. 嵌入（Embeddings）\n\n支持文本嵌入向量生成：\n\n```python\noutputs = client.embeddings.create(\n    model='togethercomputer/m2-bert-80M-8k-retrieval',\n    input=texts\n)\n```\n\n### 4. 图像生成（Image Generation）\n\n提供图像生成能力：\n\n```python\nresponse = client.images.generate(\n    prompt=\"space robots\",\n    model=\"stabilityai/stable-diffusion-xl-base-1.0\",\n    steps=10,\n    n=4,\n)\n```\n\n### 5. 重排序（Reranking）\n\n支持文档重排序功能：\n\n```python\noutputs = client.rerank.create(\n    model=model,\n    query=query,\n    documents=documents,\n    top_n=top_n\n)\n```\n\n### 6. 模型微调（Fine-Tuning）\n\n提供完整的微调工作流程：\n\n```bash\n# 启动微调任务\ntogether fine-tuning create \\\n  --training-file <FILE_ID> \\\n  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \\\n  --n-epochs 3\n```\n\n#### 支持的微调方法\n\n| 训练方法 | 说明 |\n|---------|------|\n| `full` | 全参数微调 |\n| `lora` | LoRA 低秩适配微调 |\n| `dpo` | 直接偏好优化 |\n| `simpo` | 简单偏好优化 |\n| `rpo` | 相对偏好优化 |\n\n资料来源：[src/together/resources/finetune.py:50-150]()\n\n## 安装与配置\n\n### 环境要求\n\n- Python 3.10+\n- Poetry 1.6.1+\n\n### 安装步骤\n\n1. **获取 API Key**：访问 [Together AI 注册页面](https://api.together.xyz/) 获取 API Key\n\n2. **设置环境变量**：\n\n```shell\nexport TOGETHER_API_KEY=xxxxx\n```\n\n3. **安装依赖**：\n\n```bash\npoetry install --with quality,tests\n```\n\n4. **设置 pre-commit**：\n\n```bash\npre-commit install\n```\n\n资料来源：[CONTRIBUTING.md:1-30]()\n\n## 使用方式\n\n### Python 客户端使用\n\n```python\nfrom together import Together\n\n# 初始化客户端\nclient = Together(api_key=\"xxxxx\")\n\n# 创建聊天请求\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"Hello, how are you?\"}]\n)\n\nprint(response.choices[0].message.content)\n```\n\n### 异步客户端使用\n\n```python\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\ntasks = [\n    async_client.completions.create(model=\"...\", prompt=\"...\"),\n    async_client.completions.create(model=\"...\", prompt=\"...\")\n]\n\nresponses = await asyncio.gather(*tasks)\n```\n\n### CLI 命令行使用\n\n```bash\n# 聊天补全\ntogether chat.completions --message \"Hello\" --model meta-llama/Llama-4-Scout-17B-16E-Instruct\n\n# 文本补全\ntogether completions \"Large language models are \" --model meta-llama/Llama-4-Scout-17B-16E-Instruct\n\n# 图像生成\ntogether images generate \"space robots\" --model stabilityai/stable-diffusion-xl-base-1.0\n\n# 文件操作\ntogether files upload example.jsonl\ntogether files list\ntogether files retrieve <FILE_ID>\n\n# 微调任务\ntogether fine-tuning create --training-file <FILE_ID> --model <MODEL>\ntogether fine-tuning list\ntogether fine-tuning events <FINE_TUNE_ID>\ntogether fine-tuning download <FINE_TUNE_ID>\n```\n\n## 错误处理\n\n项目实现了完善的错误处理机制：\n\n```mermaid\ngraph TD\n    A[API 请求] --> B{响应状态}\n    B -->|成功| C[返回结果]\n    B -->|4xx 错误| D[客户端错误]\n    B -->|5xx 错误| E[服务器错误]\n    B -->|速率限制| F[RateLimitError]\n    B -->|超时| G[Timeout]\n    \n    D --> H[TogetherException]\n    E --> H\n    F --> H\n    G --> H\n```\n\n## 开发指南\n\n### 本地开发设置\n\n```bash\n# 安装开发依赖\npoetry install --with quality,tests\n\n# 格式化和代码检查\nmake format\n\n# 运行测试\nmake tests\n```\n\n### 测试说明\n\n| 测试类型 | 说明 | 命令 |\n|---------|------|------|\n| 单元测试 | 不需要 API Key | `make tests` |\n| 集成测试 | 需要 API Key，会产生费用 | `make integration_tests` |\n\n资料来源：[CONTRIBUTING.md:30-60]()\n\n## 技术规格\n\n### 支持的模型类型\n\n| 类型 | 示例模型 |\n|------|---------|\n| 聊天模型 | Llama-4, Llama-3, Qwen, Gemma |\n| 代码模型 | CodeLlama, DeepSeek-Coder |\n| 嵌入模型 | M2-BERT, GTE |\n| 图像模型 | Stable Diffusion XL |\n| 视觉模型 | Llama-3.2-Vision |\n\n### API 特性支持\n\n| 功能 | 支持状态 |\n|------|---------|\n| 流式输出 | ✅ 支持 |\n| 工具/函数调用 | ✅ 支持 |\n| JSON 模式 | ✅ 支持 |\n| 多模态输入 | ✅ 支持 |\n| 并发请求 | ✅ 支持 |\n| 文件管理 | ✅ 支持 |\n| 微调训练 | ✅ 支持 |\n\n## 项目结构\n\n```\ntogether-python/\n├── src/together/\n│   ├── __init__.py          # 主入口\n│   ├── error.py             # 异常定义\n│   ├── version.py           # 版本信息\n│   ├── client.py            # 客户端实现\n│   ├── filemanager.py       # 文件管理器\n│   ├── resources/           # API 资源模块\n│   │   ├── chat/\n│   │   │   └── completions.py\n│   │   ├── completions.py\n│   │   ├── embeddings.py\n│   │   ├── images.py\n│   │   ├── rerank.py\n│   │   └── finetune.py\n│   ├── utils/\n│   │   └── files.py         # 文件处理工具\n│   └── cli/\n│       └── api/             # CLI 命令\n│           ├── chat.py\n│           ├── completions.py\n│           ├── finetune.py\n│           └── ...\n└── tests/                   # 测试文件\n```\n\n## 总结\n\nTogether Python 是一个功能全面、易于使用的 Python 客户端库，为开发者提供了与 Together AI 平台交互的便捷方式。通过统一的 Python API 和 CLI 工具，开发者可以轻松实现聊天补全、文本补全、嵌入生成、图像生成和模型微调等多种 AI 功能。项目采用模块化设计，具有良好的可扩展性和维护性，适合各类 AI 应用的开发和部署。\n\n---\n\n<a id='page-installation'></a>\n\n## 安装与配置\n\n### 相关页面\n\n相关主题：[项目介绍](#page-introduction), [客户端架构](#page-client-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/togethercomputer/together-python/blob/main/CONTRIBUTING.md)\n- [pyproject.toml](https://github.com/togethercomputer/together-python/blob/main/pyproject.toml)\n- [src/together/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/__init__.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n</details>\n\n# 安装与配置\n\n本文档详细说明 together-python 项目的安装方法、环境配置、依赖管理以及开发环境搭建流程。\n\n## 概述\n\ntogether-python 是 Together AI 提供的官方 Python SDK，提供了 Python 客户端库和 CLI 工具两种使用方式。该库支持多种核心功能，包括对话补全、文本补全、图像生成、嵌入向量生成以及模型微调等。资料来源：[README.md:1-10]()\n\n## 环境要求\n\n### 系统要求\n\n| 要求项 | 最低版本 | 推荐版本 |\n|--------|----------|----------|\n| Python | 3.10 | 3.10+ |\n| Poetry | 1.6.1 | 1.6.1+ |\n| pip | 21.0 | 最新版本 |\n\n### 依赖环境管理器说明\n\n该项目使用 [Poetry](https://python-poetry.org/) v1.6.1+ 作为依赖管理器。如果使用 Conda 或 Pyenv 作为环境或包管理器，安装 Poetry 后需要配置 Poetry 使用虚拟环境的 Python 解释器。资料来源：[CONTRIBUTING.md:60-70]()\n\n```bash\npoetry config virtualenvs.prefer-active-python true\n```\n\n## 安装方式\n\n### 方式一：通过 PyPI 安装（推荐）\n\n使用 pip 直接安装 together-python 包：\n\n```bash\npip install together\n```\n\n### 方式二：通过 Poetry 安装开发依赖\n\n克隆仓库后，使用 Poetry 安装本地开发环境：\n\n```bash\ngit clone https://github.com/togethercomputer/together-python.git\ncd together-python\npoetry install --with quality,tests\n```\n\n此命令会安装所有必要的依赖，包括：\n- **quality**: 代码格式化和静态检查工具\n- **tests**: 测试框架和测试依赖\n\n资料来源：[CONTRIBUTING.md:54-58]()\n\n### 方式三：从源码安装\n\n```bash\npip install git+https://github.com/togethercomputer/together-python.git\n```\n\n## 环境变量配置\n\n### 获取 API Key\n\n1. 访问 Together Playground: https://api.together.ai\n2. 在设置页面创建 API Key: https://api.together.xyz/settings/api-keys\n\n### 配置环境变量\n\n**Linux/macOS:**\n\n```bash\nexport TOGETHER_API_KEY=your_api_key_here\n```\n\n**Windows (PowerShell):**\n\n```powershell\n$env:TOGETHER_API_KEY=\"your_api_key_here\"\n```\n\n**永久配置：**\n\n将上述命令添加到 shell 配置文件（`~/.bashrc`、`~/.zshrc` 或 `~/.profile`）中。\n\n资料来源：[README.md:5-10]()\n\n## 客户端初始化\n\n### 基础客户端初始化\n\n在代码中使用 API Key 初始化客户端：\n\n```python\nfrom together import Together\n\n# 使用环境变量中的 API Key\nclient = Together()\n\n# 或显式传入 API Key\nclient = Together(api_key=\"your_api_key_here\")\n```\n\n资料来源：[README.md:13-18]()\n\n### 异步客户端\n\n对于需要异步处理的场景，使用 `AsyncTogether` 类：\n\n```python\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n```\n\n### CLI 客户端\n\nCLI 工具在安装包后自动可用，无需额外配置。确保 `TOGETHER_API_KEY` 环境变量已设置即可。\n\n## 开发环境配置\n\n### 安装预提交钩子\n\n项目使用 pre-commit 进行代码格式化和 linting 自动检查。安装开发依赖后，运行：\n\n```bash\npre-commit install\n```\n\n这会在每次提交前自动执行格式化和检查。\n\n资料来源：[CONTRIBUTING.md:58-60]()\n\n### 代码格式化和检查\n\n提交代码前手动运行检查：\n\n```bash\n# 格式化代码\nmake format\n\n# 运行测试\nmake tests\n\n# 运行集成测试（需要 API Key，会产生费用）\nmake integration_tests\n```\n\n资料来源：[CONTRIBUTING.md:40-50]()\n\n## 可选依赖管理\n\n项目采用可选依赖策略，大部分用户不会安装所有依赖。引入新依赖时应遵循以下流程：\n\n1. 将依赖添加到可选组：\n   ```bash\n   poetry add --optional [package_name]\n   ```\n\n2. 在 `pyproject.toml` 中将依赖添加到 `extended_testing` extra\n\n3. 重新锁定依赖：\n   ```bash\n   poetry lock --no-update\n   ```\n\n4. 添加至少导入该代码的单元测试\n\n5. 使用 `@pytest.mark.requires(package_name)` 装饰需要该依赖的测试\n\n资料来源：[CONTRIBUTING.md:18-35]()\n\n## 项目结构\n\n```\ntogether-python/\n├── pyproject.toml          # 项目配置和依赖定义\n├── src/\n│   └── together/\n│       ├── __init__.py     # 包初始化和导出\n│       ├── error.py        # 异常定义\n│       ├── constants.py    # 常量定义\n│       ├── resources/      # 功能资源模块\n│       │   ├── chat/       # 聊天补全\n│       │   ├── completions.py  # 文本补全\n│       │   ├── images.py   # 图像生成\n│       │   ├── embeddings.py   # 嵌入向量\n│       │   ├── rerank.py    # 重排序\n│       │   └── finetune.py  # 模型微调\n│       └── cli/            # CLI 工具实现\n│           └── api/        # CLI 命令\n└── tests/                  # 测试文件\n```\n\n## 配置验证\n\n### 验证安装\n\n```python\nimport together\n\n# 检查版本\nprint(together.__version__)\n\n# 验证连接\nclient = Together()\nmodels = client.models.list()\nprint(f\"可用模型数量: {len(models.data)}\")\n```\n\n### 常见配置错误\n\n| 错误类型 | 错误信息 | 解决方案 |\n|----------|----------|----------|\n| 缺少 API Key | `AuthenticationError` | 设置 `TOGETHER_API_KEY` 环境变量 |\n| API Key 无效 | `AuthenticationError` | 检查 API Key 是否正确，确认账户状态 |\n| 速率限制 | `RateLimitError` | 降低请求频率，等待冷却时间 |\n| 网络问题 | `APIConnectionError` | 检查网络连接，确认代理设置 |\n\n资料来源：[src/together/error.py:1-50]()\n\n## 工作流程图\n\n```mermaid\ngraph TD\n    A[开始] --> B{是否安装 SDK?}\n    B -->|否| C[安装 together-python]\n    C --> D{是否有 API Key?}\n    D -->|否| E[申请 API Key]\n    E --> F[配置环境变量]\n    D -->|是| F\n    F --> G[初始化客户端]\n    G --> H{使用场景}\n    H -->|同步| I[使用 Together 客户端]\n    H -->|异步| J[使用 AsyncTogether 客户端]\n    H -->|CLI| K[使用 together CLI]\n    I --> L[调用 API]\n    J --> L\n    K --> L\n```\n\n## 下一步\n\n- [快速开始指南](../quickstart) - 了解基本使用方法\n- [聊天补全](../chat-completions) - 对话功能详解\n- [模型微调](../fine-tuning) - 自定义模型训练\n- [CLI 参考](../cli-reference) - 命令行工具完整文档\n\n---\n\n<a id='page-client-architecture'></a>\n\n## 客户端架构\n\n### 相关页面\n\n相关主题：[项目介绍](#page-introduction), [请求流程与抽象层](#page-request-flow)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/abstract/api_requestor.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/api_requestor.py)\n- [src/together/together_response.py](https://github.com/togethercomputer/together-python/blob/main/src/together/together_response.py)\n- [src/together/resources/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/__init__.py)\n- [src/together/resources/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n</details>\n\n# 客户端架构\n\n## 概述\n\nTogether Python 客户端是一个轻量级且易于使用的 Python 库和命令行工具，为 Together AI 平台提供统一的 API 接口。该客户端架构采用分层设计，核心层负责 HTTP 通信和请求处理，资源层提供各类 AI 能力的抽象接口，CLI 层提供命令行交互能力。\n\n客户端的核心设计目标包括：\n\n- **简化 API 调用**：通过 Pythonic 的接口封装底层 HTTP 请求细节\n- **支持同步和异步操作**：提供 `Together` 和 `AsyncTogether` 两种客户端实现\n- **流式响应支持**：原生支持流式输出，便于实时展示生成结果\n- **完整的类型提示**：使用 Pydantic 模型进行请求参数和响应数据的验证\n\n资料来源：[src/together/client.py]()\n\n## 架构分层\n\n### 整体架构图\n\n```mermaid\ngraph TD\n    A[客户端入口] --> B[Together / AsyncTogether]\n    B --> C[资源层 Resources]\n    C --> D[Chat Completions]\n    C --> E[Completions]\n    C --> F[Embeddings]\n    C --> G[Images]\n    C --> H[Fine-tuning]\n    C --> I[Files]\n    C --> J[Rerank]\n    B --> K[APIRequestor]\n    K --> L[HTTP 请求处理]\n    L --> M[Together API]\n```\n\n### 核心组件\n\n| 组件名称 | 文件路径 | 职责描述 |\n|---------|---------|---------|\n| Together | client.py | 同步客户端入口，管理 API 密钥和资源实例 |\n| AsyncTogether | client.py | 异步客户端入口，支持 asyncio 并发操作 |\n| APIRequestor | abstract/api_requestor.py | HTTP 请求的实际执行者，处理认证、重试、超时 |\n| TogetherResponse | together_response.py | 统一响应数据结构定义 |\n| 资源类 | resources/*.py | 封装各类 AI 能力的业务逻辑 |\n\n资料来源：[src/together/client.py](), [src/together/abstract/api_requestor.py]()\n\n## 客户端初始化\n\n### 基本用法\n\n```python\nfrom together import Together\n\n# 使用环境变量中的 API Key\nclient = Together()\n\n# 直接指定 API Key\nclient = Together(api_key=\"your-api-key-here\")\n```\n\n客户端初始化时接受以下配置参数：\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|-------|------|-------|------|\n| api_key | str | None | Together API 密钥，默认从环境变量 `TOGETHER_API_KEY` 读取 |\n| base_url | str | api.together.xyz | API 基础 URL |\n| timeout | float | 600 | 请求超时时间（秒） |\n| max_retries | int | 2 | 失败重试次数 |\n| client | httpx.Client | None | 可自定义的 HTTP 客户端实例 |\n\n资料来源：[src/together/client.py]()\n\n### 异步客户端\n\n```python\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\n# 在 async 函数中使用\nasync def main():\n    response = await async_client.chat.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        messages=[{\"role\": \"user\", \"content\": \"Hello!\"}]\n    )\n```\n\n异步客户端继承自 `AsyncHTTPHandler`，支持使用 `asyncio.gather` 等工具进行并发请求。\n\n资料来源：[src/together/resources/__init__.py]()\n\n## 请求处理流程\n\n### 同步请求流程\n\n```mermaid\nsequenceDiagram\n    participant C as Together 客户端\n    participant R as Resources\n    participant A as APIRequestor\n    participant H as HTTP Handler\n    \n    C->>R: 调用 .chat.completions.create()\n    R->>A: 创建 TogetherRequest\n    A->>H: request_raw() / request()\n    H->>H: 添加认证头\n    H->>H: 处理重试逻辑\n    H->>Together API: 发送 HTTP 请求\n    Together API-->>H: 返回响应\n    H-->>A: 解析响应数据\n    A-->>R: 返回 TogetherResponse\n    R-->>C: 转换为 Pydantic 模型\n```\n\n### 流式响应处理\n\n```python\nstream = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component\",\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n流式响应使用生成器模式，逐块返回数据。每个 chunk 都是一个 `CompletionChunk` 或 `ChatCompletionChunk` 对象。\n\n资料来源：[src/together/resources/completions.py](), [src/together/resources/chat/completions.py]()\n\n## API 请求器\n\n### APIRequestor 职责\n\n`APIRequestor` 是底层的 HTTP 请求处理器，封装了所有与 Together API 的通信逻辑：\n\n| 功能 | 说明 |\n|-----|------|\n| 认证处理 | 自动添加 Authorization 头和 Together-Version 头 |\n| 重试机制 | 基于指数退避的自动重试 |\n| 超时控制 | 支持可配置的总超时和连接超时 |\n| 错误处理 | 将 HTTP 错误转换为 Python 异常 |\n| 流式支持 | 处理 Server-Sent Events (SSE) 流 |\n\n### 请求方法\n\n```python\n# 同步请求\nresponse, status_code, duration = requestor.request(\n    options=TogetherRequest(\n        method=\"POST\",\n        url=\"chat/completions\",\n        params=payload,\n    ),\n)\n\n# 原始响应（用于文件下载等场景）\nraw_response = requestor.request_raw(\n    options=TogetherRequest(\n        method=\"GET\",\n        url=file_url,\n        headers={\"Range\": \"bytes=0-1\"},\n    ),\n)\n```\n\n资料来源：[src/together/abstract/api_requestor.py]()\n\n## 响应模型\n\n### 统一响应结构\n\n```mermaid\nclassDiagram\n    class TogetherResponse {\n        +Any data\n        +int status_code\n    }\n    \n    class ChatCompletionResponse {\n        +str id\n        +str object\n        +int created\n        +str model\n        +list choices\n        +Usage usage\n    }\n    \n    class CompletionResponse {\n        +str id\n        +str object\n        +int created\n        +str model\n        +list choices\n        +Usage usage\n    }\n    \n    TogetherResponse <|-- ChatCompletionResponse\n    TogetherResponse <|-- CompletionResponse\n```\n\n### 响应模型字段\n\n| 模型类 | 主要字段 | 说明 |\n|-------|---------|------|\n| ChatCompletionResponse | id, model, choices, usage | 聊天完成响应 |\n| CompletionResponse | id, model, choices, usage | 文本补全响应 |\n| EmbeddingResponse | data, model, usage | 向量嵌入响应 |\n| ImageResponse | data | 图像生成响应 |\n| Usage | prompt_tokens, completion_tokens, total_tokens | Token 使用统计 |\n\n资料来源：[src/together/together_response.py]()\n\n## 资源层设计\n\n### 资源模块概览\n\n```mermaid\ngraph TD\n    Resources --> Chat\n    Resources --> Completions\n    Resources --> Embeddings\n    Resources --> Images\n    Resources --> Files\n    Resources --> FineTuning\n    Resources --> Rerank\n    Resources --> Models\n```\n\n| 资源类 | 功能 | 核心方法 |\n|-------|-----|---------|\n| Chat | 聊天完成 | `create()`, `create_async()` |\n| Completions | 文本补全 | `create()`, `create_async()` |\n| Embeddings | 向量嵌入 | `create()` |\n| Images | 图像生成 | `generate()` |\n| Files | 文件管理 | `upload()`, `download()`, `list()`, `retrieve()`, `delete()` |\n| FineTuning | 模型微调 | `create()`, `submit()`, `estimate_price()` |\n| Rerank | 文档重排序 | `create()` |\n\n资料来源：[src/together/resources/__init__.py]()\n\n### 聊天完成资源\n\n聊天完成是最常用的功能之一，支持多种消息格式和工具调用：\n\n```python\n# 简单文本消息\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n)\n\n# 多模态消息（文本+图像）\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\"type\": \"text\", \"text\": \"What's in this image?\"},\n            {\"type\": \"image_url\", \"image_url\": {\"url\": \"https://example.com/image.png\"}}\n        ]\n    }]\n)\n```\n\n资料来源：[src/together/resources/chat/completions.py]()\n\n### 文件管理\n\n文件管理模块提供完整的上传、下载、列表查询等功能：\n\n```python\n# 上传文件\nresponse = client.files.upload(file=open(\"data.jsonl\", \"rb\"))\n\n# 检查文件\nclient.files.check(file_id)\n\n# 下载文件内容\ncontent = client.files.retrieve_content(file_id)\n\n# 列出文件\nfiles = client.files.list()\n```\n\n资料来源：[src/together/filemanager.py]()\n\n## 错误处理\n\n### 异常层次结构\n\n```mermaid\nclassDiagram\n    class TogetherException {\n        +str message\n        +Any http_status\n        +Any body\n    }\n    \n    class AuthenticationError {\n        <<extends TogetherException>>\n    }\n    \n    class RateLimitError {\n        <<extends TogetherException>>\n    }\n    \n    class APIConnectionError {\n        <<extends TogetherException>>\n    }\n    \n    class Timeout {\n        <<extends TogetherException>>\n    }\n    \n    class APIError {\n        <<extends TogetherException>>\n    }\n```\n\n### 异常类型说明\n\n| 异常类 | HTTP 状态码 | 说明 |\n|-------|------------|------|\n| TogetherException | - | 所有异常的基类 |\n| AuthenticationError | 401 | API 密钥无效或缺失 |\n| RateLimitError | 429 | 请求频率超限 |\n| APIConnectionError | - | 网络连接问题 |\n| Timeout | - | 请求超时 |\n| APIError | 4xx/5xx | 其他 API 错误 |\n\n```python\nfrom together.error import RateLimitError, AuthenticationError\n\ntry:\n    response = client.chat.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        messages=[{\"role\": \"user\", \"content\": \"Hello\"}],\n    )\nexcept AuthenticationError as e:\n    print(\"Invalid API key\")\nexcept RateLimitError as e:\n    print(\"Rate limit exceeded, please wait\")\n```\n\n资料来源：[src/together/error.py]()\n\n## 配置管理\n\n### 环境变量\n\n| 环境变量 | 说明 | 必需 |\n|---------|-----|-----|\n| TOGETHER_API_KEY | Together AI API 密钥 | 是 |\n| TOGETHER_BASE_URL | API 基础 URL（可选） | 否 |\n\n### 客户端配置示例\n\n```python\nfrom together import Together\nimport os\n\n# 方式一：环境变量\nclient = Together()  # 自动读取 TOGETHER_API_KEY\n\n# 方式二：直接传入\nclient = Together(api_key=os.environ.get(\"TOGETHER_API_KEY\"))\n\n# 方式三：自定义配置\nclient = Together(\n    api_key=\"your-key\",\n    base_url=\"https://api.together.xyz\",\n    timeout=120,\n    max_retries=3\n)\n```\n\n资料来源：[src/together/client.py]()\n\n## 最佳实践\n\n### 1. 异步并发请求\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def batch_requests():\n    tasks = [\n        async_client.chat.completions.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            messages=[{\"role\": \"user\", \"content\": prompt}],\n        )\n        for prompt in prompts\n    ]\n    responses = await asyncio.gather(*tasks)\n    return responses\n```\n\n### 2. 流式响应处理\n\n```python\nstream = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component\",\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n### 3. 错误重试机制\n\n客户端内置自动重试机制，支持指数退避策略。默认配置：\n\n- 最大重试次数：2\n- 超时时间：600 秒\n- 可通过自定义 httpx.Client 调整\n\n资料来源：[src/together/abstract/api_requestor.py]()\n\n## 扩展性\n\n### 自定义 HTTP 客户端\n\n```python\nimport httpx\nfrom together import Together\n\n# 使用自定义配置的 HTTP 客户端\ncustom_client = httpx.Client(\n    timeout=httpx.Timeout(60.0, connect=10.0),\n    proxies={\"http://\": \"http://proxy.example.com:8080\"},\n)\n\nclient = Together(client=custom_client)\n```\n\n### 资源扩展\n\n新功能可以通过扩展资源类来实现，所有资源类都遵循统一的接口模式：\n\n```python\nclass BaseResource:\n    def __init__(self, client: TogetherClient) -> None:\n        self._client = client\n```\n\n资料来源：[src/together/resources/__init__.py]()\n\n## 总结\n\nTogether Python 客户端采用清晰的分层架构设计，将 API 通信细节封装在 `APIRequestor` 中，对外提供直观的资源接口。核心设计原则包括：\n\n1. **简洁易用**：通过高级抽象简化 API 调用复杂度\n2. **类型安全**：使用 Pydantic 模型确保请求参数和响应数据的正确性\n3. **灵活扩展**：分层设计便于添加新功能和自定义行为\n4. **完善的错误处理**：层次化的异常体系便于精准捕获和处理错误\n\n该架构既适合快速原型开发，也能满足生产环境对稳定性和性能的要求。\n\n---\n\n<a id='page-request-flow'></a>\n\n## 请求流程与抽象层\n\n### 相关页面\n\n相关主题：[客户端架构](#page-client-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/abstract/api_requestor.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/api_requestor.py)\n- [src/together/abstract/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/__init__.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/together_response.py](https://github.com/togethercomputer/together-python/blob/main/src/together/together_response.py)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)\n</details>\n\n# 请求流程与抽象层\n\n## 概述\n\nTogether Python SDK 的请求流程与抽象层是整个库的核心架构部分，负责处理所有与 Together API 的通信交互。该层通过分层设计实现了请求的发送、响应的处理、错误的捕获与转换，以及同步/异步操作的支持。开发者通过 `Together` 客户端实例发起各类请求（如聊天补全、文生图、嵌入等），而底层的抽象层则负责将高层 API 调用转换为底层的 HTTP 请求，并与 Together 服务器进行交互。\n\n该架构的核心价值在于**解耦**与**统一**：上层资源（如 `Completions`、`Chat`、`Embeddings` 等）无需关心具体的网络通信细节，只需专注于业务逻辑参数的准备和响应数据的解析。所有底层网络通信、认证、超时重试等机制都由抽象层统一处理，确保了整个 SDK 的一致性与可维护性。\n\n从架构层面看，Together SDK 采用了典型的**客户端-请求者-响应**三层模型。`Together` 客户端作为入口点，提供各类资源对象；资源对象负责构建请求参数并调用请求者；`APIRequestor` 则处理底层的 HTTP 通信，包括认证头的生成、请求发送、超时控制以及错误处理。最终，响应数据通过 `TogetherResponse` 和具体的响应模型类（如 `ChatCompletionResponse`、`CompletionResponse`）返回给调用者。\n\n## 核心组件架构\n\nTogether SDK 的请求流程涉及多个核心组件，它们各司其职、协同工作。下表列出了主要组件及其职责：\n\n| 组件 | 文件位置 | 职责描述 |\n|------|----------|----------|\n| `Together` | `client.py` | 主客户端入口，管理所有资源实例 |\n| `APIRequestor` | `abstract/api_requestor.py` | 底层 HTTP 请求处理 |\n| `TogetherResponse` | `together_response.py` | 原始响应包装器 |\n| `TogetherRequest` | `abstract/` | 请求配置（URL、方法、参数） |\n| 资源类 | `resources/*.py` | 各业务功能的参数构建与响应解析 |\n\n`Together` 主类定义了所有支持的资源类型，包括 `completions`、`chat`、`embeddings`、`files`、`images`、`models`、`fine_tuning`、`rerank`、`audio`、`batches`、`code_interpreter`、`evaluation` 和 `videos`。每个资源都持有对底层客户端的引用，可以直接调用 `APIRequestor` 发起请求。这种设计使得添加新的 API 功能只需扩展资源类，而无需修改底层通信机制。\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[资源层<br/>Completions/Chat/Embeddings...]\n    B --> C[请求构建<br/>参数序列化]\n    C --> D[APIRequestor<br/>抽象请求者]\n    D --> E[HTTP 通信层<br/>requests/httpx]\n    E --> F[Together API 服务器]\n    F --> G[TogetherResponse<br/>原始响应]\n    G --> H[响应解析<br/>Pydantic 模型]\n    H --> I[业务响应对象<br/>ChatCompletion/Completion...]\n```\n\n## 请求流程详解\n\n### 同步请求流程\n\n同步请求是最基本的请求模式，适用于大多数使用场景。请求从客户端发起，经过资源层、请求构建层，最终由 `APIRequestor` 发送 HTTP 请求。以聊天补全为例，完整的请求流程如下：\n\n1. **客户端实例化**：用户创建 `Together` 客户端实例，可传入 `api_key`、`base_url`、`timeout` 等配置参数。若未显式提供，`api_key` 会自动从环境变量 `TOGETHER_API_KEY` 获取。\n2. **资源调用**：用户通过 `client.chat.completions.create()` 发起聊天补全请求，传入模型名称、消息列表等参数。\n3. **参数构建**：资源类将用户参数转换为 API 所需的格式，包括默认值填充、参数校验和序列化。\n4. **请求发送**：`APIRequestor` 接收 `TogetherRequest` 对象，构建完整的 HTTP 请求，包括认证头、内容类型等。\n5. **响应处理**：服务器响应后，`APIRequestor` 将原始响应包装为 `TogetherResponse` 对象返回。\n6. **结果解析**：资源类将 `TogetherResponse` 中的数据解析为具体的响应模型（如 `ChatCompletionResponse`），返回给用户。\n\n在 `client.py` 中，`Together` 类的初始化逻辑展示了配置参数的优先级处理：\n\n```python\ndef __init__(\n    self,\n    *,\n    api_key: str | None = None,\n    base_url: str | None = None,\n    timeout: float | None = None,\n    max_retries: int | None = None,\n    supplied_headers: Dict[str, str] | None = None,\n) -> None:\n```\n\n配置参数按照以下优先级获取：显式传入的参数 > 环境变量 > 默认值。这种设计既提供了灵活性，又保证了向后兼容性。\n\n### 异步请求流程\n\nTogether SDK 完全支持异步操作，通过 `AsyncTogether` 类提供异步版本的客户端。异步请求在处理大量并发请求时具有显著优势，能够有效利用系统资源并提高吞吐量。\n\n异步请求的核心差异在于 `APIRequestor` 使用 `arequest` 方法而非 `request` 方法。在 `resources/chat/completions.py` 中可以看到异步请求的实现模式：\n\n```python\nresponse, _, _ = await requestor.arequest(\n    options=TogetherRequest(\n        method=\"POST\",\n        url=\"chat/completions\",\n        params=parameter_payload,\n    ),\n    stream=stream,\n)\n```\n\n异步方法返回协程对象，配合 `asyncio` 或 `aiohttp` 等异步框架使用。资源类可以将异步请求封装为异步生成器，便于处理流式响应。流式响应通过异步生成器实现，每次迭代返回一个新的响应块，直到所有数据发送完毕。\n\n```mermaid\nsequenceDiagram\n    participant User as 用户代码\n    participant Client as AsyncTogether\n    participant Resource as 资源类\n    participant Requestor as APIRequestor\n    participant Server as Together API\n    \n    User->>Client: 异步调用\n    Client->>Resource: create()\n    Resource->>Resource: 构建参数\n    Resource->>Requestor: arequest()\n    Requestor->>Server: async HTTP POST\n    Server-->>Requestor: 流式响应\n    loop 流式处理\n        Requestor-->>Resource: 异步生成器\n        Resource-->>User: ChatCompletionChunk\n    end\n```\n\n### 流式响应处理\n\n流式响应是 Together API 的重要特性，特别适用于需要实时展示生成内容的场景，如聊天机器人和代码补全。SDK 对流式响应的处理采用了异步生成器模式，既保证了实时性，又提供了良好的编程接口。\n\n在 `resources/completions.py` 中，流式响应的处理逻辑展示了响应类型的动态判断：\n\n```python\nif stream:\n    # must be an iterator\n    assert not isinstance(response, TogetherResponse)\n    return (CompletionChunk(**line.data) async for line in response)\nassert isinstance(response, TogetherResponse)\nreturn CompletionResponse(**response.data)\n```\n\n当启用流式传输时，响应对象不再是单一的 `TogetherResponse`，而是变成了一个异步迭代器。每次迭代从服务器接收一个数据块，解析为对应的 Chunk 类型（如 `CompletionChunk` 或 `ChatCompletionChunk`）。这种设计允许用户实时处理响应数据，无需等待完整响应生成。\n\n## 抽象层设计\n\n### APIRequestor 职责\n\n`APIRequestor` 是请求流程抽象层的核心组件，负责所有底层的 HTTP 通信逻辑。它封装了认证、请求发送、超时控制、重试机制和错误处理等复杂逻辑，为上层资源类提供简洁统一的接口。\n\n`APIRequestor` 的主要职责包括：\n\n- **认证管理**：自动从环境变量或客户端配置获取 API 密钥，生成符合 Together API 规范的认证头。在 `filemanager.py` 中可以看到认证头的生成方式：`together.utils.get_headers(method, requestor.api_key)`\n- **请求发送**：支持同步的 `request` 方法和异步的 `arequest` 方法，处理不同类型的 HTTP 请求（GET、POST 等）\n- **参数传递**：接收 `TogetherRequest` 对象作为请求配置，包含 URL、HTTP 方法、查询参数、请求体等\n- **响应包装**：将原始 HTTP 响应转换为 `TogetherResponse` 对象，统一响应处理流程\n- **错误转换**：捕获 HTTP 错误和业务错误，转换为合适的异常类型抛出\n\n`APIRequestor` 的设计遵循了**单一职责原则**，将网络通信的复杂性隔离在抽象层内部。上层代码只需关注业务逻辑，无需直接处理 HTTP 协议的细节。这种设计也便于单元测试，因为可以使用 Mock 对象替代真实的网络请求。\n\n### TogetherRequest 配置对象\n\n`TogetherRequest` 是请求配置的数据类，封装了发起 HTTP 请求所需的所有信息。它是连接上层业务逻辑与底层网络通信的桥梁，确保了请求参数的完整性和一致性。\n\n`TogetherRequest` 通常包含以下字段：\n\n| 字段 | 类型 | 描述 |\n|------|------|------|\n| `method` | `str` | HTTP 方法（GET、POST、DELETE 等） |\n| `url` | `str` | API 端点路径 |\n| `params` | `Dict` | 查询参数或请求体数据 |\n| `headers` | `Dict` | 自定义请求头 |\n| `stream` | `bool` | 是否启用流式响应 |\n| `override_headers` | `bool` | 是否覆盖默认头 |\n| `allow_redirects` | `bool` | 是否允许重定向 |\n\n通过使用 `model_dump(exclude_none=True)` 方法，可以方便地将请求配置序列化为字典，去除 `None` 值，保持请求体的简洁。\n\n### TogetherResponse 响应包装\n\n`TogetherResponse` 是对原始 HTTP 响应的封装类，它将底层的响应状态码、响应头和响应体统一包装在一起。这种设计简化了响应数据的访问方式，并提供了类型安全的数据访问接口。\n\n`TogetherResponse` 的主要属性包括：\n\n- **status_code**：HTTP 状态码，用于判断请求是否成功\n- **headers**：响应头信息，包含内容类型、字符编码等元数据\n- **data**：响应体数据，已经过 JSON 解析的字典或列表\n\n在非流式响应场景下，资源类通过 `TogetherResponse.data` 访问响应内容，并使用 Pydantic 模型进行数据验证和解析。这种模式确保了响应数据的结构符合预期，提供了自动的类型转换和验证功能。\n\n## 错误处理机制\n\n### 异常层次结构\n\nTogether SDK 定义了一套完整的异常层次结构，从基类 `TogetherException` 派生出各类具体异常。这种设计允许调用者采用**宽捕获**或**精确捕获**的方式处理错误，既可以捕获所有 Together 相关错误，也可以针对特定错误类型进行处理。\n\n在 `error.py` 中定义的主要异常类型包括：\n\n| 异常类型 | 描述 | 典型场景 |\n|----------|------|----------|\n| `TogetherException` | 基类异常 | 所有异常的父类 |\n| `AuthenticationError` | 认证错误 | API 密钥无效或缺失 |\n| `RateLimitError` | 速率限制错误 | 请求频率超出限制 |\n| `FileTypeError` | 文件类型错误 | 上传了不支持的文件格式 |\n| `APIConnectionError` | 连接错误 | 网络连接失败 |\n| `Timeout` | 超时错误 | 请求超时 |\n| `APIError` | 通用 API 错误 | 服务器返回的错误响应 |\n\n异常类的构造函数接收多种类型的消息参数，包括 `TogetherErrorResponse`（服务器返回的错误响应结构）、`Exception`（原始异常对象）、字符串消息或 `RequestException`。这种灵活性使得错误信息可以来自不同的来源，便于调试和日志记录。\n\n### 错误处理流程\n\n错误处理贯穿整个请求流程，在多个层面进行：\n\n1. **HTTP 层错误捕获**：`APIRequestor` 捕获底层 HTTP 异常（如连接超时、DNS 解析失败等），转换为 `APIConnectionError` 或 `Timeout`。\n2. **HTTP 状态码检查**：响应返回后检查状态码，非 2xx 状态码会触发异常。在 `filemanager.py` 中可以看到：`response.raise_for_status()` 用于触发 HTTP 状态码异常。\n3. **业务错误解析**：Together API 返回的错误响应会解析为结构化的错误信息，便于调用者理解错误原因。\n4. **重试机制**：`APIRequestor` 实现了一定的重试逻辑，对于临时性错误（如 503 Service Unavailable）会自动重试。\n\n```mermaid\ngraph TD\n    A[发起请求] --> B{网络正常?}\n    B -->|否| C[APIConnectionError]\n    B -->|是| D{状态码 2xx?}\n    D -->|否| E{可重试状态码?}\n    D -->|是| F{流式响应?}\n    F -->|否| G[TogetherResponse]\n    F -->|是| H[异步生成器]\n    E -->|是| I[重试请求]\n    E -->|否| J[APIError]\n    I --> A\n```\n\n## 文件管理中的请求流程\n\n文件管理模块展示了请求流程的另一个应用场景，包括文件上传、下载和元数据获取等操作。该模块使用了重定向机制来处理大文件上传，这是标准的 multipart/form-data 上传模式。\n\n### 上传流程\n\n文件上传采用了**重定向模式**：首先向 API 发起初始化请求，获取预签名的上传 URL；然后直接向该 URL 上传文件内容；最后确认上传完成。这种模式可以将大文件上传的负载分散到对象存储服务，减轻 API 服务器的压力。\n\n在 `filemanager.py` 中，`get_upload_url` 方法展示了重定向流程的实现：\n\n```python\nresponse = requestor.request_raw(\n    options=TogetherRequest(\n        method=method,\n        url=url,\n        params=data,\n        allow_redirects=False,\n        override_headers=True,\n        headers=headers,\n    ),\n    remaining_retries=MAX_RETRIES,\n)\n```\n\n设置 `allow_redirects=False` 使得响应返回重定向头而非自动跟随，SDK 可以获取 `Location` 头获取实际的 upload URL 和文件 ID。\n\n### 下载流程\n\n文件下载支持断点续传和并发控制。通过发送 Range 请求获取文件大小信息，然后使用 `FileLock` 防止同一文件的并发下载。下载过程中使用临时文件，写入完成后原子性地重命名，确保文件完整性。\n\n## 参数构建与序列化\n\n资源类在发起请求前，需要将用户友好的参数转换为 API 所需的格式。这一过程包括默认值填充、参数校验、类型转换和序列化。\n\n以聊天补全为例，参数构建在资源类中完成：\n\n```python\nparameter_payload = ChatCompletionCreateParams(\n    model=model,\n    messages=messages,\n    temperature=temperature,\n    max_tokens=max_tokens,\n    top_p=top_p,\n    ...\n).model_dump(exclude_none=True)\n```\n\n使用 Pydantic 的 `model_dump(exclude_none=True)` 方法可以方便地生成 API 兼容的 JSON 字典，自动排除值为 `None` 的可选参数。这种模式既保证了参数的规范性，又提供了灵活的默认值处理。\n\n## 总结\n\nTogether Python SDK 的请求流程与抽象层通过分层设计实现了优雅的架构：主客户端提供统一入口，资源类封装业务逻辑，请求者抽象处理底层通信细节。这种设计既保证了代码的可读性和可维护性，又为扩展新功能提供了清晰的方向。\n\n核心的抽象包括 `APIRequestor` 负责 HTTP 通信、`TogetherRequest` 封装请求配置、`TogetherResponse` 包装响应数据、`TogetherException` 及其子类处理错误。这些组件协同工作，为开发者提供了简洁而强大的 API 调用体验。开发者无需关心网络通信的复杂性，只需关注业务逻辑的实现，通过高层 API 即可完成与 Together 平台的所有交互。\n\n---\n\n<a id='page-chat-completions'></a>\n\n## 聊天补全 API\n\n### 相关页面\n\n相关主题：[文本补全 API](#page-completions), [多模态功能](#page-multimodal)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/chat/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/__init__.py)\n- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n- [src/together/types/chat_completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/chat_completions.py)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)\n</details>\n\n# 聊天补全 API\n\n## 概述\n\n聊天补全 API（Chat Completions API）是 together-python 客户端库的核心功能之一，提供与 Together 平台上的大语言模型进行交互的统一接口。该 API 基于 OpenAI 兼容的聊天补全格式，支持文本对话、多模态输入（图像/视频）、流式输出、异步调用以及日志概率获取等高级功能。\n\n在 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)\n\n## 核心组件架构\n\n### 模块依赖关系\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[resources.Chat]\n    B --> C[ChatCompletions 类]\n    C --> D[types/chat_completions.py]\n    C --> E[requestor 请求模块]\n    \n    F[CLI chat 命令] --> C\n```\n\n### 客户端集成\n\n`Together` 类在初始化时自动绑定所有资源端点，包括聊天补全功能：\n\n| 属性 | 类型 | 说明 |\n|------|------|------|\n| `client.chat` | `resources.Chat` | 聊天补全 API 入口 |\n| `client.completions` | `resources.Completions` | 文本补全 API |\n| `client.embeddings` | `resources.Embeddings` | 向量嵌入 API |\n| `client.images` | `resources.Images` | 图像生成 API |\n| `client.fine_tuning` | `resources.FineTuning` | 微调 API |\n\n资料来源：[src/together/client.py:10-22](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n\n## 主要功能特性\n\n### 1. 基础文本对话\n\n聊天补全 API 支持最简单的文本消息交互，使用 `messages` 参数传递对话历史：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n)\nprint(response.choices[0].message.content)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 2. 多模态消息支持\n\nAPI 支持在同一请求中传递多种内容类型，包括文本、图像 URL 和视频 URL：\n\n| 内容类型 | 类型标识 | 用途 |\n|---------|---------|------|\n| 纯文本 | `{\"type\": \"text\", \"text\": \"...\"}` | 普通文本消息 |\n| 图像输入 | `{\"type\": \"image_url\", \"image_url\": {\"url\": \"...\"}}` | 视觉理解任务 |\n| 视频输入 | `{\"type\": \"video_url\", \"video_url\": {\"url\": \"...\"}}` | 视频理解任务 |\n\n#### 带图像的多模态示例\n\n```python\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": \"What's in this image?\"\n            },\n            {\n                \"type\": \"image_url\",\n                \"image_url\": {\n                    \"url\": \"https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png\"\n                }\n            }\n        ]\n    }]\n)\n```\n\n#### 带视频的多模态示例\n\n```python\nresponse = client.chat.completions.create(\n    model=\"Qwen/Qwen2.5-VL-72B-Instruct\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": \"What's happening in this video?\"\n            },\n            {\n                \"type\": \"video_url\",\n                \"video_url\": {\n                    \"url\": \"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4\"\n                }\n            }\n        ]\n    }]\n)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 3. 流式输出\n\n启用流式模式后，API 以增量方式返回生成的内容，适合需要实时展示的交互场景：\n\n```python\nstream = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 4. 异步调用\n\n通过 `AsyncTogether` 客户端实现并发请求处理：\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def async_chat_completion(messages):\n    tasks = [\n        async_client.chat.completions.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            messages=[{\"role\": \"user\", \"content\": message}],\n        )\n        for message in messages\n    ]\n    responses = await asyncio.gather(*tasks)\n    return responses\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 5. 日志概率（Logprobs）\n\nLogprobs 功能允许获取 token 级别的生成概率，用于评估模型输出的置信度：\n\n```python\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-3B-Instruct-Turbo\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n    logprobs=1\n)\n```\n\n日志概率的主要应用场景包括：\n\n| 场景 | 说明 |\n|-----|------|\n| 置信度评估 | 判断模型对输出的自信程度 |\n| 低置信度过滤 | 拒绝或重试概率较低的输出 |\n| 模型集成 | 比较不同模型的概率分布 |\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n## API 参数详解\n\n### 核心请求参数\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| `model` | `str` | 必填 | 模型标识符，如 `meta-llama/Llama-4-Scout-17B-16E-Instruct` |\n| `messages` | `List[Dict]` | 必填 | 对话消息列表，每条包含 `role` 和 `content` |\n| `max_tokens` | `int` | `None` | 最大生成 token 数 |\n| `temperature` | `float` | `None` | 采样温度，控制随机性 |\n| `top_p` | `float` | `None` | 核采样概率阈值 |\n| `top_k` | `int` | `None` | Top-K 采样参数 |\n| `stream` | `bool` | `False` | 是否启用流式输出 |\n| `logprobs` | `int` | `None` | 返回 logprobs 的数量 |\n\n资料来源：[src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n\n### 惩罚参数\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `repetition_penalty` | `float` | 重复惩罚系数 |\n| `presence_penalty` | `float` | 存在惩罚（鼓励引入新话题） |\n| `frequency_penalty` | `float` | 频率惩罚（降低高频词出现） |\n| `min_p` | `float` | 最小概率阈值采样 |\n\n资料来源：[src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)\n\n### 高级参数\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `echo` | `bool` | 是否回显输入 prompt |\n| `n` | `int` | 生成数量 |\n| `safety_model` | `str` | 安全审查模型标识 |\n| `response_format` | `dict` | 响应格式约束（如 JSON mode） |\n| `tools` | `List[Dict]` | 可用工具定义列表 |\n| `tool_choice` | `str` | 工具选择策略 |\n| `audio_url` | `List[str]` | 附加到用户消息的音频 URL |\n| `multimodal_params` | `dict` | 多模态额外参数 |\n\n资料来源：[src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n\n## 请求处理流程\n\n### 同步请求流程\n\n```mermaid\nsequenceDiagram\n    participant Client as Together 客户端\n    participant API as Chat Completions API\n    participant Backend as Together 后端\n    \n    Client->>API: client.chat.completions.create(params)\n    API->>API: 验证参数，构建请求\n    API->>Backend: POST /chat/completions\n    Backend-->>API: 返回 ChatCompletionResponse\n    API-->>Client: 返回最终响应对象\n    \n    Note over API,Backend: stream=True 时\n    API->>Backend: POST /chat/completions (stream=true)\n    Backend-->>API: 流式事件流\n    API-->>Client: 异步生成器 (AsyncGenerator)\n```\n\n### 响应对象结构\n\n```python\nChatCompletionResponse {\n    id: str                    # 请求唯一标识\n    object: str                # 对象类型\n    created: int               # 创建时间戳\n    model: str                 # 实际使用的模型\n    choices: List[Choice]      # 生成结果列表\n    usage: Usage               # Token 使用统计\n}\n\nChoice {\n    index: int                 # 结果索引\n    message: Message           # 完整消息内容\n    logprobs: Logprobs | None  # 日志概率（可选）\n    finish_reason: str         # 结束原因\n}\n```\n\n资料来源：[src/together/types/chat_completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/chat_completions.py)\n\n## CLI 命令行接口\n\n通过 `together` CLI 可以直接调用聊天补全功能：\n\n```bash\ntogether chat.completions \\\n  --message \"What is machine learning?\" \\\n  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \\\n  --max-tokens 512\n```\n\n### CLI 可用选项\n\n| CLI 选项 | 对应参数 | 说明 |\n|---------|---------|------|\n| `--message` | `messages` | 消息内容（可多次指定） |\n| `--model` | `model` | 模型名称 |\n| `--max-tokens` | `max_tokens` | 最大 token 数 |\n| `--stop` | `stop` | 停止序列 |\n| `--temperature` | `temperature` | 采样温度 |\n| `--top-p` | `top_p` | 核采样概率 |\n| `--top-k` | `top_k` | Top-K 采样 |\n| `--no-stream` | `stream=False` | 禁用流式输出 |\n| `--logprobs` | `logprobs` | 返回 logprobs |\n| `--safety-model` | `safety_model` | 安全模型 |\n| `--audio-url` | `audio_url` | 音频 URL |\n\n资料来源：[src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)\n\n## 完整使用示例\n\n### 示例一：基础聊天\n\n```python\nfrom together import Together\n\nclient = Together(api_key=\"your-api-key\")\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[\n        {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n        {\"role\": \"user\", \"content\": \"What are the top 3 things to do in San Francisco?\"}\n    ],\n    temperature=0.7,\n    max_tokens=256\n)\n\nprint(response.choices[0].message.content)\n```\n\n### 示例二：多轮对话\n\n```python\nmessages = [\n    {\"role\": \"system\", \"content\": \"You are a Python expert.\"},\n    {\"role\": \"user\", \"content\": \"Explain what a decorator is.\"},\n    {\"role\": \"assistant\", \"content\": \"A decorator in Python is a function that...\"},\n    {\"role\": \"user\", \"content\": \"Give me an example.\"}\n]\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=messages\n)\n```\n\n### 示例三：并发请求\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync def batch_chat():\n    async_client = AsyncTogether()\n    \n    queries = [\n        \"What is AI?\",\n        \"What is ML?\",\n        \"What is DL?\"\n    ]\n    \n    tasks = [\n        async_client.chat.completions.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            messages=[{\"role\": \"user\", \"content\": q}]\n        )\n        for q in queries\n    ]\n    \n    results = await asyncio.gather(*tasks)\n    \n    for i, response in enumerate(results):\n        print(f\"Q{i+1}: {queries[i]}\")\n        print(f\"A{i+1}: {response.choices[0].message.content}\\n\")\n\nasyncio.run(batch_chat())\n```\n\n## 错误处理\n\n聊天补全 API 可能抛出的异常类型定义于 `src/together/error.py`：\n\n| 异常类型 | 说明 |\n|---------|------|\n| `AuthenticationError` | API 密钥无效或缺失 |\n| `RateLimitError` | 请求频率超限 |\n| `APIConnectionError` | 网络连接错误 |\n| `Timeout` | 请求超时 |\n| `TogetherException` | 基础异常类 |\n\n```python\nfrom together import Together\nfrom together.error import RateLimitError, AuthenticationError\n\nclient = Together()\n\ntry:\n    response = client.chat.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        messages=[{\"role\": \"user\", \"content\": \"Hello\"}]\n    )\nexcept AuthenticationError:\n    print(\"请检查 API 密钥是否正确设置\")\nexcept RateLimitError:\n    print(\"请求频率超限，请稍后重试\")\nexcept Exception as e:\n    print(f\"发生错误: {e}\")\n```\n\n资料来源：[src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n## 最佳实践\n\n1. **环境变量配置**：将 API 密钥存储在环境变量 `TOGETHER_API_KEY` 中，避免硬编码\n2. **流式响应处理**：对于长文本生成，使用流式模式提升用户体验\n3. **错误重试**：结合指数退避策略处理临时性网络错误\n4. **资源清理**：异步操作完成后确保正确关闭连接\n5. **多模态优化**：图像输入时使用合理的分辨率以平衡质量和延迟\n\n## 相关资源\n\n- SDK 文档：[Together Python SDK](https://github.com/togethercomputer/together-python)\n- API 平台：[api.together.xyz](https://api.together.xyz/)\n- 模型列表：`together models list` 或 `client.models.list()`\n\n---\n\n<a id='page-completions'></a>\n\n## 文本补全 API\n\n### 相关页面\n\n相关主题：[聊天补全 API](#page-chat-completions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/cli/api/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/completions.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/types/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/completions.py)\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n</details>\n\n# 文本补全 API\n\n## 概述\n\n文本补全 API（Completions API）是 Together Python 客户端库的核心功能之一，提供对大型语言模型文本生成能力的访问。该 API 允许开发者通过简单的接口调用，向 Together 平台上的各种语言模型发送补全请求，并获取生成的文本内容。\n\n## 核心组件架构\n\n文本补全 API 的架构涉及多个协同工作的组件，从客户端入口到最终的 API 请求处理。\n\n```mermaid\ngraph TD\n    A[开发者代码] --> B[Together 客户端实例]\n    B --> C[completions 资源对象]\n    C --> D[Completions.create 方法]\n    D --> E[请求参数构建]\n    E --> F[API 请求发送]\n    F --> G[Together API 服务器]\n    G --> H[CompletionResponse]\n    H --> I[开发者获取结果]\n    \n    style A fill:#e1f5fe\n    style G fill:#fff3e0\n    style I fill:#e8f5e9\n```\n\n### 主要组件说明\n\n| 组件 | 文件位置 | 职责 |\n|------|----------|------|\n| Together 客户端 | `src/together/client.py` | 作为统一的 API 入口点 |\n| Completions 资源 | `src/together/resources/completions.py` | 实现补全功能的核心逻辑 |\n| CLI 命令 | `src/together/cli/api/completions.py` | 命令行接口实现 |\n| 类型定义 | `src/together/types/completions.py` | 请求和响应数据模型 |\n\n## 客户端集成\n\nTogether 主客户端类通过 `completions` 属性集成了文本补全功能。\n\n```python\nclass Together:\n    completions: resources.Completions\n    # ... 其他资源\n```\n\n资料来源：[src/together/client.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n\n### 初始化与认证\n\n客户端支持通过多种方式配置 API 密钥：\n\n```python\nfrom together import Together\n\n# 方式一：通过参数直接传入\nclient = Together(api_key=\"your-api-key\")\n\n# 方式二：通过环境变量自动读取\n# 需要设置 TOGETHER_API_KEY 环境变量\nclient = Together()\n```\n\n## API 方法详解\n\n### 创建补全请求\n\n`completions.create()` 是文本补全 API 的核心方法，支持同步和流式两种模式。\n\n#### 方法签名\n\n```python\nasync def create(\n    self,\n    *,\n    model: str,\n    prompt: str,\n    max_tokens: int | None = None,\n    temperature: float | None = None,\n    top_p: int | None = None,\n    top_k: int | None = None,\n    stop: str | list[str] | None = None,\n    repetition_penalty: float | None = None,\n    presence_penalty: float | None = None,\n    frequency_penalty: float | None = None,\n    min_p: float | None = None,\n    stream: bool = False,\n    logprobs: int | None = None,\n    echo: bool = False,\n    n: int | None = None,\n    safety_model: str | None = None,\n    response_format: dict | None = None,\n    tools: list[dict] | None = None,\n    tool_choice: str | dict | None = None,\n    **kwargs,\n) -> CompletionResponse | AsyncGenerator[CompletionChunk, None]\n```\n\n资料来源：[src/together/resources/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n\n#### 参数说明\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| `model` | str | 必需 | 模型标识符，如 `meta-llama/Llama-4-Scout-17B-16E-Instruct` |\n| `prompt` | str | 必需 | 输入提示文本 |\n| `max_tokens` | int | None | 生成令牌的最大数量 |\n| `temperature` | float | None | 采样温度，控制随机性 |\n| `top_p` | int | None | Nucleus 采样阈值 |\n| `top_k` | float | None | Top-K 采样参数 |\n| `stop` | str \\| list[str] | None | 停止生成的字符串或字符串列表 |\n| `repetition_penalty` | float | None | 重复惩罚系数 |\n| `presence_penalty` | float | None | 存在惩罚系数 |\n| `frequency_penalty` | float | None | 频率惩罚系数 |\n| `min_p` | float | None | 最小概率阈值 |\n| `stream` | bool | False | 是否启用流式输出 |\n| `logprobs` | int | None | 返回的对数概率数量 |\n| `echo` | bool | False | 是否回显输入提示 |\n| `n` | int | None | 生成数量 |\n| `safety_model` | str | None | 安全模型标识 |\n| `response_format` | dict | None | 响应格式规范 |\n| `tools` | list[dict] | None | 可用工具列表 |\n| `tool_choice` | str \\| dict | None | 工具选择策略 |\n\n## 使用模式\n\n### 基础文本补全\n\n最基本的文本补全调用，返回完整的补全结果：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    max_tokens=512,\n)\n\nprint(response.choices[0].text)\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 流式输出\n\n流式模式允许实时获取生成的令牌，适合需要即时反馈的场景：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nstream = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n#### 流式输出流程图\n\n```mermaid\nsequenceDiagram\n    participant 客户端\n    participant API\n    participant 模型\n    \n    客户端->>API: POST /completions (stream=True)\n    API->>模型: 转发请求\n    模型-->>API: 流式令牌 1\n    API-->>客户端: CompletionChunk 1\n    模型-->>API: 流式令牌 2\n    API-->>客户端: CompletionChunk 2\n    模型-->>API: 流式令牌 N\n    API-->>客户端: CompletionChunk N\n    模型-->>API: [DONE]\n    API-->>客户端: 流结束信号\n```\n\n### 异步并发请求\n\n对于需要同时处理多个补全请求的场景，可以使用异步客户端：\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nprompts = [\n    \"Write a Next.js component with TailwindCSS for a header component.\",\n    \"Write a python function for the fibonacci sequence\",\n]\n\nasync def async_completions(prompts):\n    tasks = [\n        async_client.completions.create(\n            model=\"codellama/CodeLlama-34b-Python-hf\",\n            prompt=prompt,\n        )\n        for prompt in prompts\n    ]\n    responses = await asyncio.gather(*tasks)\n\n    for response in responses:\n        print(response.choices[0].text)\n\nasyncio.run(async_completions(prompts))\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n## CLI 命令行接口\n\nTogether CLI 提供了命令行方式的文本补全功能：\n\n```bash\ntogether completions \\\n  \"Large language models are \" \\\n  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \\\n  --max-tokens 512 \\\n  --stop \".\"\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### CLI 参数选项\n\n| CLI 选项 | 对应 API 参数 | 说明 |\n|----------|---------------|------|\n| `--model` | model | 模型名称 |\n| `--max-tokens` | max_tokens | 最大令牌数 |\n| `--stop` | stop | 停止序列 |\n| `--temperature` | temperature | 采样温度 |\n| `--top-p` | top_p | Nucleus 采样 |\n| `--top-k` | top_k | Top-K 采样 |\n| `--repetition-penalty` | repetition_penalty | 重复惩罚 |\n| `--presence-penalty` | presence_penalty | 存在惩罚 |\n| `--frequency-penalty` | frequency_penalty | 频率惩罚 |\n| `--no-stream` | stream=False | 禁用流式输出 |\n| `--logprobs` | logprobs | 返回对数概率 |\n| `--echo` | echo | 回显提示 |\n| `--n` | n | 生成数量 |\n| `--safety-model` | safety_model | 安全模型 |\n| `--raw` | - | 输出原始 JSON |\n\n资料来源：[src/together/cli/api/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/completions.py)\n\n## 响应数据结构\n\n### 完整响应\n\n当 `stream=False` 时，返回 `CompletionResponse` 对象：\n\n```python\n@dataclass\nclass CompletionResponse:\n    id: str\n    choices: List[CompletionChoice]\n    model: str\n    usage: CompletionUsage\n    created: int\n    object: str = \"text_completion\"\n```\n\n### 流式响应\n\n当 `stream=True` 时，返回 `CompletionChunk` 对象的异步生成器：\n\n```python\n@dataclass\nclass CompletionChunk:\n    id: str\n    choices: List[CompletionChoicesChunk]\n    model: str\n    created: int\n    object: str = \"text_completion.chunk\"\n```\n\n每个 `CompletionChoicesChunk` 包含 `delta` 字段，其中 `delta.content` 包含新生成的文本片段：\n\n```python\nfor chunk in stream:\n    assert isinstance(chunk, CompletionChunk)\n    if chunk.choices and chunk.choices[0].delta:\n        print(chunk.choices[0].delta.content, end=\"\", flush=True)\n```\n\n资料来源：[src/together/resources/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n\n## 错误处理\n\n文本补全 API 可能抛出多种异常类型，继承自 `TogetherException` 基类：\n\n```mermaid\ngraph TD\n    A[TogetherException] --> B[RateLimitError]\n    A --> C[AuthenticationError]\n    A --> D[APIConnectionError]\n    A --> E[Timeout]\n    A --> F[InvalidRequestError]\n```\n\n| 异常类型 | 说明 | 处理建议 |\n|----------|------|----------|\n| `RateLimitError` | 请求频率超限 | 实现退避重试机制 |\n| `AuthenticationError` | 认证失败 | 检查 API 密钥配置 |\n| `APIConnectionError` | 网络连接问题 | 检查网络状态 |\n| `Timeout` | 请求超时 | 增加超时时间或重试 |\n| `InvalidRequestError` | 请求参数错误 | 检查参数有效性 |\n\n资料来源：[src/together/error.py:1-100](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n### 错误处理示例\n\n```python\nfrom together import Together\nfrom together.error import RateLimitError, APIConnectionError\n\nclient = Together()\n\ntry:\n    response = client.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        prompt=\"Hello, world!\",\n    )\nexcept RateLimitError:\n    print(\"请求频率超限，请稍后重试\")\nexcept APIConnectionError:\n    print(\"网络连接失败，请检查网络\")\nexcept Exception as e:\n    print(f\"发生错误: {e}\")\n```\n\n## 最佳实践\n\n### 参数调优建议\n\n| 使用场景 | 推荐参数配置 |\n|----------|--------------|\n| 代码生成 | `temperature=0.2`, `max_tokens=1024` |\n| 创意写作 | `temperature=0.8-1.0`, `top_p=0.95` |\n| 问答系统 | `temperature=0.3`, `max_tokens=256` |\n| 摘要生成 | `temperature=0.3`, `presence_penalty=0.1` |\n\n### 性能优化\n\n1. **使用流式输出**：对于需要实时反馈的场景，启用 `stream=True`\n2. **合理设置 max_tokens**：避免生成过长文本造成不必要的资源消耗\n3. **使用异步客户端**：处理批量请求时使用 `AsyncTogether`\n4. **缓存模型响应**：对于相同提示的重复请求考虑实现缓存机制\n\n### 安全考虑\n\n1. **设置 safety_model**：对敏感内容使用安全模型过滤\n2. **限制输出长度**：通过 `max_tokens` 控制最大生成长度\n3. **使用停止序列**：通过 `stop` 参数避免生成不期望的内容\n\n---\n\n<a id='page-multimodal'></a>\n\n## 多模态功能\n\n### 相关页面\n\n相关主题：[聊天补全 API](#page-chat-completions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/images.py)\n- [src/together/resources/code_interpreter.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/code_interpreter.py)\n- [src/together/resources/videos.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/videos.py)\n- [src/together/resources/audio/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/audio/__init__.py)\n- [src/together/types/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/images.py)\n- [examples/code_interpreter_demo.py](https://github.com/togethercomputer/together-python/blob/main/examples/code_interpreter_demo.py)\n</details>\n\n# 多模态功能\n\nTogether Python SDK 提供了丰富的多模态功能，支持文本、图像、视频和音频等多种模态的数据处理与生成。这些功能通过统一的客户端接口暴露，使开发者能够便捷地调用各种多模态 AI 能力。\n\n## 功能概述\n\nTogether Python SDK 的多模态功能主要包括以下几个模块：\n\n| 模块 | 功能描述 | 主要类/方法 |\n|------|----------|-------------|\n| 图像生成 | 根据文本描述生成图像 | `client.images.generate()` |\n| 聊天多模态 | 支持文本+图像的对话 | `client.chat.completions.create()` |\n| 代码解释器 | 执行多模态代码 | `client.code_interpreter` |\n| 视频生成 | 生成视频内容 | `client.videos` |\n| 音频处理 | 音频相关功能 | `client.audio` |\n\n资料来源：[src/together/client.py:25-38](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n\n## 架构设计\n\n### 客户端架构\n\nTogether SDK 采用模块化架构，各个多模态功能通过独立的资源类实现：\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[chat 聊天模块]\n    A --> C[images 图像模块]\n    A --> D[code_interpreter 代码解释器]\n    A --> E[videos 视频模块]\n    A --> F[audio 音频模块]\n    \n    B --> B1[文本处理]\n    B --> B2[多图像处理]\n    \n    C --> C1[图像生成]\n    C --> C2[参考图像支持]\n```\n\n## 图像生成功能\n\n### 基本用法\n\n图像生成模块允许通过文本提示词生成图像，支持自定义模型、尺寸、步数和数量等参数。\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.images.generate(\n    prompt=\"space robots\",\n    model=\"stabilityai/stable-diffusion-xl-base-1.0\",\n    steps=10,\n    n=4,\n)\nprint(response.data[0].b64_json)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### CLI 使用方式\n\n通过命令行也可以调用图像生成功能：\n\n```bash\ntogether images generate \\\n  \"space robots\" \\\n  --model stabilityai/stable-diffusion-xl-base-1.0 \\\n  --n 4\n```\n\n### 图像生成参数\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| prompt | str | 必需 | 图像生成提示词 |\n| model | str | 必需 | 使用的模型名称 |\n| steps | int | 20 | 生成步数 |\n| seed | int | None | 随机种子，用于复现 |\n| n | int | 1 | 生成图像数量 |\n| height | int | 1024 | 图像高度 |\n| width | int | 1024 | 图像宽度 |\n| negative_prompt | str | None | 负面提示词 |\n| response_format | str | None | 返回格式 |\n\n资料来源：[src/together/resources/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/images.py)\n\n### 请求处理流程\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Images\n    participant APIRequestor\n    participant Together API\n    \n    Client->>Images: images.generate(prompt, model, ...)\n    Images->>Images: 构建 ImageRequest\n    Images->>APIRequestor: arequest(POST, images/generations)\n    APIRequestor->>Together API: HTTP POST\n    Together API-->>APIRequestor: ImageResponse\n    APIRequestor-->>Images: TogetherResponse\n    Images-->>Client: ImageResponse\n```\n\n## 聊天多模态功能\n\n### 多模态消息格式\n\n聊天模块支持多模态消息，消息内容可以是纯文本，也可以是包含文本和图像URL的列表结构。\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": \"What's in this image?\"\n            },\n            {\n                \"type\": \"image_url\",\n                \"image_url\": {\n                    \"url\": \"https://example.com/image.png\"\n                }\n            }\n        ]\n    }]\n)\nprint(response.choices[0].message.content)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 内容类型验证\n\n系统对多模态内容有严格的验证规则：\n\n| 规则 | 说明 |\n|------|------|\n| 类型限制 | `content` 字段支持字符串或字典列表 |\n| 有效类型 | `text` 和 `image_url` 两种类型 |\n| 图像位置 | 仅用户消息可包含图像 |\n| 图像编码 | 图像必须为 base64 编码 |\n| 大小限制 | base64 编码后小于 10MB |\n| 数量限制 | 每条消息最多 3 张图像 |\n\n资料来源：[src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)\n\n### 数据格式示例\n\n```python\n# 单文本消息\n{\"role\": \"user\", \"content\": \"普通文本消息\"}\n\n# 多模态消息（文本+图像）\n{\n    \"role\": \"user\",\n    \"content\": [\n        {\"type\": \"text\", \"text\": \"描述这张图片\"},\n        {\"type\": \"image_url\", \"image_url\": {\"url\": \"https://...\"}}\n    ]\n}\n```\n\n## 代码解释器\n\n代码解释器模块支持执行包含多模态数据的代码，能够处理图像等多媒体内容。\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.code_interpreter.run(\n    input=\"分析这张图片并返回描述\",\n    images=[base64_image_data],\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n)\nprint(response)\n```\n\n资料来源：[examples/code_interpreter_demo.py](https://github.com/togethercomputer/together-python/blob/main/examples/code_interpreter_demo.py)\n\n## 视频生成功能\n\n视频生成模块提供视频内容创作能力：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.videos.generate(\n    prompt=\"宇航员在太空站工作\",\n    model=\"some-video-model\",\n    duration=5,\n)\n```\n\n资料来源：[src/together/resources/videos.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/videos.py)\n\n## 音频功能\n\n音频模块支持音频相关的数据处理：\n\n```python\nfrom together import Together\n\nclient = Together()\n\n# 音频相关功能调用\nresponse = client.audio.transcribe(\n    file=\"audio.wav\",\n    model=\"whisper-model\"\n)\n```\n\n资料来源：[src/together/resources/audio/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/audio/__init__.py)\n\n## 工作流程图\n\n### 多模态请求处理流程\n\n```mermaid\ngraph TD\n    A[开始请求] --> B[验证 API Key]\n    B --> C[构建请求参数]\n    C --> D{请求类型}\n    \n    D -->|图像生成| E[调用 images.generate]\n    D -->|聊天多模态| F[调用 chat.completions.create]\n    D -->|代码解释| G[调用 code_interpreter.run]\n    D -->|视频生成| H[调用 videos.generate]\n    \n    E --> I[POST /images/generations]\n    F --> J[POST /chat/completions]\n    G --> K[POST /code_interpreter]\n    H --> L[POST /videos/generations]\n    \n    I --> M[返回 ImageResponse]\n    J --> N[返回 ChatCompletionResponse]\n    K --> O[返回执行结果]\n    L --> P[返回 VideoResponse]\n    \n    M --> Q[结束]\n    N --> Q\n    O --> Q\n    P --> Q\n```\n\n## 错误处理\n\nSDK 提供了多层次的错误处理机制：\n\n| 错误类型 | 说明 |\n|----------|------|\n| `RateLimitError` | 请求频率超限 |\n| `FileTypeError` | 文件类型不支持 |\n| `Timeout` | 请求超时 |\n| `APIConnectionError` | API 连接错误 |\n| `InvalidFileFormatError` | 文件格式无效 |\n\n资料来源：[src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n## 最佳实践\n\n1. **图像大小优化**：在上传图像前进行压缩，避免超过 10MB 限制\n2. **提示词编写**：使用清晰、具体的描述以获得更好的生成效果\n3. **种子使用**：当需要复现结果时，设置固定的 seed 值\n4. **批量处理**：利用 `n` 参数一次性生成多张图像，提高效率\n\n## 总结\n\nTogether Python SDK 的多模态功能提供了统一、便捷的接口来访问各种生成式 AI 能力。通过模块化的设计，开发者可以根据需求灵活调用图像生成、多模态聊天、代码解释器、视频生成和音频处理等功能。所有功能都遵循一致的 API 设计规范，便于集成到各类应用场景中。\n\n---\n\n<a id='page-embeddings-rerank'></a>\n\n## 嵌入与重排序\n\n### 相关页面\n\n相关主题：[文本补全 API](#page-completions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n</details>\n\n# 嵌入与重排序\n\n## 概述\n\n嵌入（Embeddings）与重排序（Reranking）是 Together Python 库中用于增强检索能力的两大核心功能模块。它们共同构成了语义搜索和文档匹配的技术基础，使开发者能够将文本转换为高维向量表示，并通过相关性评分对候选结果进行排序优化。\n\nTogether Python 客户端通过统一的接口封装了这些功能，支持同步和异步两种调用方式，便于集成到各类应用场景中。嵌入功能主要用于将文本转换为稠密向量，而重排序功能则在此基础上对检索结果进行二次优化，提升最终结果的相关性。\n\n## 架构设计\n\n### 客户端集成\n\nTogether 客户端类在初始化时自动配置了嵌入和重排序资源。客户端采用模块化设计，将不同功能封装为独立的资源类，通过统一的方式对外提供服务。\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[Embeddings 嵌入模块]\n    A --> C[Rerank 重排序模块]\n    B --> D[向量嵌入生成]\n    C --> E[相关性评分计算]\n    D --> F[语义相似度匹配]\n    E --> G[结果重排序]\n    F --> G\n```\n\n客户端类中声明了以下相关属性，用于支持嵌入和重排序功能：\n\n| 模块 | 类型 | 用途 |\n|------|------|------|\n| embeddings | resources.Embeddings | 文本向量化嵌入生成 |\n| rerank | resources.Rerank | 文档相关性评分与重排序 |\n\n资料来源：[src/together/client.py:18-35]()\n\n### 错误处理机制\n\n嵌入与重排序模块共享统一的异常处理体系。所有自定义异常均继承自 `TogetherException` 基类，确保错误信息的一致性和可追溯性。\n\n| 异常类型 | 适用场景 |\n|----------|----------|\n| TogetherException | 所有异常的基类 |\n| RateLimitError | 请求频率超限时触发 |\n| APIConnectionError | 网络连接异常时触发 |\n| Timeout | 请求超时情况 |\n| FileTypeError | 文件类型不匹配时触发 |\n\n资料来源：[src/together/error.py:1-60]()\n\n## 嵌入功能详解\n\n### 功能概述\n\n嵌入功能将文本转换为固定维度的稠密向量，这种向量表示能够捕捉文本的语义信息。在自然语言处理领域，向量嵌入是语义搜索、文本相似度计算、聚类分析等任务的基础。通过 Together 平台提供的嵌入模型，开发者可以将任意文本转换为可计算的数值向量。\n\n### 使用方式\n\n#### 基础用法\n\n```python\nfrom typing import List\nfrom together import Together\n\nclient = Together()\n\ndef get_embeddings(texts: List[str], model: str) -> List[List[float]]:\n    texts = [text.replace(\"\\n\", \" \") for text in texts]\n    outputs = client.embeddings.create(model=model, input=texts)\n    return [outputs.data[i].embedding for i in range(len(texts))]\n\ninput_texts = ['Our solar system orbits the Milky Way galaxy at about 515,000 mph']\nembeddings = get_embeddings(input_texts, model='togethercomputer/m2-bert-80M-8k-retrieval')\n```\n\n资料来源：[README.md:65-75]()\n\n#### 核心参数说明\n\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| model | str | 是 | 嵌入模型标识符 |\n| input | List[str] | 是 | 待编码的文本列表 |\n\n#### 处理流程\n\n嵌入处理流程包含以下关键步骤：\n\n1. **文本预处理**：移除换行符等特殊字符，确保输入格式统一\n2. **API 调用**：通过 `client.embeddings.create()` 发起请求\n3. **响应解析**：从返回结果中提取 `embedding` 向量数据\n4. **结果返回**：以浮点数列表形式输出向量\n\n### 支持的模型\n\nTogether 平台提供多种嵌入模型，常见选择包括 `togethercomputer/m2-bert-80M-8k-retrieval` 等专门针对检索任务优化的模型。开发者可根据精度、速度和成本需求选择合适的模型。\n\n## 重排序功能详解\n\n### 功能概述\n\n重排序（Reranking）是信息检索领域的重要技术。当初始检索返回多个候选文档后，重排序模型会对这些文档进行相关性评分，并按照评分高低重新排列，从而将最相关的文档优先展示给用户。\n\nTogether 平台集成了高质量的重排序模型（如 Salesforce/Llama-Rank-V1），能够显著提升检索系统的最终效果。重排序通常作为第二阶段处理，位于初步向量检索之后。\n\n### 使用方式\n\n```python\nfrom typing import List\nfrom together import Together\n\nclient = Together()\n\ndef get_reranked_documents(\n    query: str, \n    documents: List[str], \n    model: str, \n    top_n: int = 3\n) -> List[str]:\n    outputs = client.rerank.create(\n        model=model, \n        query=query, \n        documents=documents, \n        top_n=top_n\n    )\n    # sort by relevance score and returns the original docs\n    return [\n        documents[i] \n        for i in [x.index for x in sorted(\n            outputs.results, \n            key=lambda x: x.relevance_score, \n            reverse=True\n        )]\n    ]\n\nquery = \"What is the capital of the United States?\"\ndocuments = [\"New York\", \"Washington, D.C.\", \"Los Angeles\"]\n\nreranked_documents = get_reranked_documents(\n    query, \n    documents, \n    model='Salesforce/Llama-Rank-V1', \n    top_n=1\n)\n```\n\n资料来源：[README.md:80-100]()\n\n#### 核心参数说明\n\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| model | str | 是 | 重排序模型标识符 |\n| query | str | 是 | 查询文本 |\n| documents | List[str] | 是 | 待排序的文档列表 |\n| top_n | int | 否 | 返回的最相关文档数量，默认返回全部 |\n\n#### 返回结果结构\n\n重排序结果包含每个文档的索引位置和相关性评分：\n\n| 字段 | 类型 | 说明 |\n|------|------|------|\n| index | int | 原始文档列表中的位置 |\n| relevance_score | float | 相关性评分，数值越高越相关 |\n\n## 组合工作流\n\n嵌入与重排序通常组合使用，形成完整的检索管道。这种两阶段检索架构能够兼顾召回率和精确率：\n\n```mermaid\ngraph LR\n    A[用户查询] --> B[嵌入阶段]\n    B --> C[向量相似度检索]\n    C --> D[候选文档集]\n    D --> E[重排序阶段]\n    E --> F[最终排序结果]\n    \n    G[文档库] --> H[文档嵌入]\n    H --> C\n```\n\n### 典型应用场景\n\n| 场景 | 嵌入作用 | 重排序作用 |\n|------|----------|------------|\n| 语义搜索 | 将查询和文档转为向量 | 对初步结果进行相关性优化 |\n| 推荐系统 | 用户和物品向量化 | 精细化排序提升推荐准确度 |\n| 问答系统 | 问题与答案片段编码 | 排序最相关的答案片段 |\n\n## 异步调用支持\n\nTogether Python 库同时支持异步调用方式，便于在异步应用框架中集成使用。异步客户端 `AsyncTogether` 提供了与非异步版本相同的接口设计，确保开发体验的一致性。\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def async_rerank_example(query: str, documents: List[str]):\n    results = await async_client.rerank.create(\n        model='Salesforce/Llama-Rank-V1',\n        query=query,\n        documents=documents,\n        top_n=5\n    )\n    return results\n```\n\n## 最佳实践\n\n### 文本预处理\n\n在调用嵌入功能前，建议对输入文本进行标准化处理：\n\n- 移除多余的换行符和空白字符\n- 统一文本编码格式\n- 限制单条文本的最大长度以符合模型要求\n\n### 性能优化建议\n\n| 优化方向 | 具体措施 |\n|----------|----------|\n| 批处理 | 批量提交嵌入请求以减少网络开销 |\n| 缓存 | 对频繁查询的嵌入结果进行缓存 |\n| 模型选择 | 根据精度需求选择合适的模型规格 |\n| top_n 参数 | 仅获取必要的重排序结果数量 |\n\n### 错误处理\n\n集成时应妥善处理各类异常情况：\n\n- 网络异常：实现重试机制\n- 频率限制：遵守 API 调用频率约束\n- 输入验证：确保文档列表非空且格式正确\n\n## 相关资源\n\n更多关于嵌入和重排序的详细文档，请参考 Together 官方文档：\n\n- [嵌入功能概述](https://docs.together.ai/docs/rerank-overview)\n- [微调功能与文件上传](https://docs.together.ai/docs/fine-tuning-python)\n\n资料来源：[README.md:100-102]()\n\n---\n\n<a id='page-files-management'></a>\n\n## 文件管理\n\n### 相关页面\n\n相关主题：[模型微调](#page-finetuning)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/files.py)\n- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)\n- [src/together/types/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/files.py)\n- [src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)\n</details>\n\n# 文件管理\n\nTogether Python SDK 提供了一套完整的文件管理功能，用于支持模型微调、数据上传、文件检索与删除等操作。该模块是整个 SDK 与 Together AI 平台进行数据交互的重要桥梁。\n\n## 功能概述\n\nTogether AI 的文件管理 API 主要服务于以下核心场景：\n\n1. **微调数据管理**：上传训练数据集以进行模型微调\n2. **文件元数据查询**：查看已上传文件的详细信息\n3. **文件内容检索**：获取已上传文件的具体内容\n4. **存储空间管理**：删除不再需要的文件以释放空间\n\n文件管理模块在整个 SDK 架构中属于基础资源层，被 `FineTuning`（微调）和 `Files`（文件）两个核心资源类所依赖。客户端通过 `Together` 类的 `files` 属性访问这些功能。\n\n```mermaid\ngraph LR\n    A[用户代码] --> B[Together 客户端]\n    B --> C[Files 资源类]\n    C --> D[Together API]\n    D --> E[(远程存储)]\n    \n    F[CLI 命令] --> C\n    G[微调模块] --> C\n```\n\n## 核心组件\n\n### Files 资源类\n\n`Files` 资源类封装了所有与文件操作相关的 API 方法。资料来源：[src/together/resources/files.py]()\n\n| 方法名 | 功能描述 |\n|--------|----------|\n| `upload()` | 上传本地文件到 Together 服务器 |\n| `list()` | 列出当前账户下的所有文件 |\n| `retrieve()` | 获取指定文件的元数据 |\n| `retrieve_content()` | 下载并返回文件内容 |\n| `delete()` | 删除指定文件 |\n\n### 文件类型定义\n\nTogether SDK 使用 `FilePurpose` 枚举定义文件的用途类别。资料来源：[src/together/types/files.py]()\n\n| 枚举值 | 用途说明 |\n|--------|----------|\n| `fine-tunes` | 微调训练数据 |\n| `batch` | 批量处理任务 |\n| `evaluation` | 模型评估数据 |\n\n### 错误处理\n\n文件管理模块定义了专门的异常类用于处理各类错误情况。资料来源：[src/together/error.py]()\n\n| 异常类 | 触发场景 |\n|--------|----------|\n| `FileTypeError` | 文件类型不符合要求 |\n| `InvalidFileFormatError` | 文件格式验证失败 |\n| `APIConnectionError` | API 连接异常 |\n\n## Python API 使用\n\n### 初始化客户端\n\n```python\nfrom together import Together\n\nclient = Together()\n```\n\n### 上传文件\n\n使用 `files.upload()` 方法将本地文件上传至服务器：\n\n```python\nresponse = client.files.upload(\n    file=\"somedata.jsonl\",\n    purpose=\"fine-tunes\"  # 可选，默认为 fine-tunes\n)\n```\n\n上传时系统会自动进行文件格式校验。资料来源：[README.md]() 和 [src/together/utils/files.py]()\n\n### 列出文件\n\n获取账户下所有已上传文件的列表：\n\n```python\nresponse = client.files.list()\n```\n\n返回结果包含每个文件的元数据信息，包括文件名、创建时间、文件大小等。\n\n### 检索文件元数据\n\n通过文件 ID 获取特定文件的详细信息：\n\n```python\nresponse = client.files.retrieve(\n    id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\"\n)\n```\n\n### 获取文件内容\n\n下载并读取已上传文件的实际内容：\n\n```python\ncontent = client.files.retrieve_content(\n    id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\"\n)\n```\n\n### 删除文件\n\n从服务器删除指定文件以释放存储空间：\n\n```python\nclient.files.delete(\n    id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\"\n)\n```\n\n## CLI 命令行接口\n\nTogether SDK 提供了命令行工具用于文件管理操作。资料来源：[src/together/cli/api/files.py]()\n\n### 基本命令结构\n\n```bash\ntogether files <子命令>\n```\n\n### 查看帮助\n\n```bash\ntogether files --help\n```\n\n### 检查文件\n\n在上传前验证本地文件格式是否正确：\n\n```bash\ntogether files check example.jsonl\n```\n\n### 上传文件\n\n将本地文件上传至 Together 服务器：\n\n```bash\ntogether files upload example.jsonl\n```\n\n支持指定文件用途：\n\n```bash\ntogether files upload example.jsonl --purpose fine-tunes\n```\n\n### 列出文件\n\n显示账户下所有已上传文件：\n\n```bash\ntogether files list\n```\n\n### 检索文件元数据\n\n获取特定文件的详细信息：\n\n```bash\ntogether files retrieve file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n```\n\n### 检索文件内容\n\n下载并显示文件内容：\n\n```bash\ntogether files retrieve-content file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n```\n\n### 删除文件\n\n从服务器删除指定文件：\n\n```bash\ntogether files delete file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n```\n\n## 文件格式校验\n\nTogether SDK 在文件上传前会进行严格的格式验证，确保数据符合微调要求。资料来源：[src/together/utils/files.py]()\n\n### JSONL 格式验证\n\n上传的文件必须符合 JSONL（JSON Lines）格式规范：\n\n- 每行必须是有效的 JSON 对象\n- 文件扩展名应为 `.jsonl`\n- 支持单行或多行 JSON 格式\n\n### 多模态内容验证\n\n对于包含多模态内容的文件，系统会进行以下校验：\n\n| 校验项 | 说明 |\n|--------|------|\n| 内容类型 | 必须是 `text` 或 `image_url` |\n| 图片数量 | 每个示例最多包含规定数量的图片 |\n| Base64 长度 | Base64 编码的图片数据需小于 10MB |\n| 角色限制 | 图片只能出现在 `user` 角色的消息中 |\n\n### 错误处理机制\n\n校验失败时会抛出 `InvalidFileFormatError` 异常，包含以下详细信息：\n\n- 错误发生的行号\n- 错误类型标识\n- 具体的错误描述\n\n## 与微调模块的集成\n\n文件管理模块与微调功能紧密集成，是进行模型微调的前置步骤。资料来源：[src/together/resources/finetune.py]()\n\n### 典型工作流程\n\n```mermaid\ngraph TD\n    A[准备训练数据] --> B[上传文件]\n    B --> C[获取 file ID]\n    C --> D[创建微调任务]\n    D --> E[监控训练进度]\n    E --> F[下载微调模型]\n```\n\n### 训练文件引用\n\n在创建微调任务时，通过 `training_file` 参数引用已上传文件的 ID：\n\n```python\nclient.fine_tuning.create(\n    training_file=\"file-xxxxx\",\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\"\n)\n```\n\n## 配置与参数\n\n### 客户端初始化参数\n\n| 参数名 | 类型 | 说明 | 默认值 |\n|--------|------|------|--------|\n| `api_key` | str | API 密钥 | 环境变量 TOGETHER_API_KEY |\n| `base_url` | str | API 基础地址 | 环境变量 TOGETHER_BASE_URL |\n| `timeout` | float | 请求超时时间 | 600 秒 |\n| `max_retries` | int | 最大重试次数 | 2 |\n\n### 文件上传参数\n\n| 参数名 | 类型 | 说明 | 必填 |\n|--------|------|------|------|\n| `file` | str/Path | 本地文件路径 | 是 |\n| `purpose` | str | 文件用途 | 否 |\n| `check` | bool | 是否校验文件格式 | 否（默认 True） |\n\n## 最佳实践\n\n### 数据准备\n\n1. **文件格式**：使用标准 JSONL 格式，每行一个 JSON 对象\n2. **数据清洗**：确保数据编码为 UTF-8，避免特殊字符问题\n3. **文件大小**：建议单个文件不超过 100MB\n\n### 上传策略\n\n1. **预校验**：使用 `check` 参数在上传说进行格式验证\n2. **分批处理**：大量数据建议分批上传\n3. **错误处理**：捕获并处理 `InvalidFileFormatError` 异常\n\n### 存储管理\n\n1. **定期清理**：删除已完成微调的临时文件\n2. **命名规范**：使用有意义的文件名便于识别\n3. **记录追踪**：保存 file ID 以便后续引用\n\n## 相关资源\n\n- [微调文档](https://docs.together.ai/docs/fine-tuning-python)\n- [Together API 文档](https://docs.together.ai/reference)\n- [GitHub 仓库](https://github.com/togethercomputer/together-python)\n\n---\n\n<a id='page-finetuning'></a>\n\n## 模型微调\n\n### 相关页面\n\n相关主题：[文件管理](#page-files-management)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)\n- [src/together/cli/api/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)\n- [src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/types/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/finetune.py)\n</details>\n\n# 模型微调\n\n## 概述\n\n模型微调（Fine-Tuning）是 Together Python SDK 中用于自定义预训练语言模型行为的核心功能模块。通过微调，用户可以使用自己的数据集对 Together 平台上托管的预训练模型进行定制化训练，使其更好地适应特定任务场景，如特定领域的问答、代码生成、内容分类等。\n\nTogether SDK 提供了完整的微调工作流支持，涵盖从训练任务提交、检查点管理到模型部署的全生命周期管理。\n\n---\n\n## 核心组件\n\n### 主要类和方法\n\n| 组件 | 位置 | 说明 |\n|------|------|------|\n| `FineTuning` | `src/together/resources/finetune.py` | 微调核心资源类，提供所有微调相关操作 |\n| `_parse_raw_checkpoints` | `src/together/resources/finetune.py:78-97` | 解析检查点元数据的辅助函数 |\n| `FinetuneCheckpoint` | `src/together/types/finetune.py` | 检查点数据模型 |\n\n### 异常处理体系\n\n微调过程中可能遇到的异常类型定义于 `src/together/error.py`：\n\n| 异常类 | 说明 | 触发场景 |\n|--------|------|----------|\n| `TogetherException` | 基异常类 | 通用错误 |\n| `RateLimitError` | 速率限制错误 | API 请求频率超限 |\n| `FileTypeError` | 文件类型错误 | 上传文件格式不支持 |\n| `APIConnectionError` | 连接错误 | 无法建立 API 连接 |\n| `Timeout` | 超时错误 | 请求响应超时 |\n\n---\n\n## 微调参数配置\n\n### 基础训练参数\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.fine_tuning.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    training_file=\"file-xxx\",\n    validation_file=\"file-yyy\",\n    n_epochs=3,\n    batch_size=4,\n    learning_rate=1e-5,\n    n_checkpoints=1\n)\n```\n\n### 完整参数表\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| `model` | `str` | 必填 | 基础模型名称 |\n| `training_file` | `str` | 必填 | 训练数据文件 ID |\n| `validation_file` | `str` | 可选 | 验证数据文件 ID |\n| `n_epochs` | `int` | - | 训练轮数 |\n| `n_evals` | `int` | - | 评估频率 |\n| `n_checkpoints` | `int` | - | 保存的检查点数量 |\n| `batch_size` | `int` | - | 批处理大小 |\n| `learning_rate` | `float` | - | 学习率 |\n| `lr_scheduler_type` | `str` | - | 学习率调度器类型 |\n| `min_lr_ratio` | `float` | - | 最小学习率比例 |\n| `scheduler_num_cycles` | `int` | - | 调度器循环次数 |\n| `warmup_ratio` | `float` | - | 预热比例 |\n| `max_grad_norm` | `float` | - | 梯度裁剪最大值 |\n| `weight_decay` | `float` | - | 权重衰减系数 |\n| `suffix` | `str` | - | 输出模型名称后缀 |\n\n*资料来源：[src/together/resources/finetune.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## LoRA 微调配置\n\nTogether SDK 支持 Low-Rank Adaptation（LoRA）高效微调方法，显著降低训练参数量和计算成本。\n\n### LoRA 相关参数\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `lora` | `bool` | 是否启用 LoRA |\n| `lora_r` | `int` | LoRA 秩（rank） |\n| `lora_dropout` | `float` | LoRA dropout 率 |\n| `lora_alpha` | `float` | LoRA alpha 值 |\n| `lora_trainable_modules` | `str` | 可训练的模块名称 |\n\n### 配置示例\n\n```python\nresponse = client.fine_tuning.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    training_file=\"file-xxx\",\n    lora=True,\n    lora_r=8,\n    lora_alpha=16,\n    lora_dropout=0.05\n)\n```\n\n*资料来源：[src/together/resources/finetune.py:30-35](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## 高级训练配置\n\n### DPO/RLHF 训练\n\nTogether 支持直接偏好优化（DPO）和相关强化学习方法：\n\n| 参数名 | 说明 |\n|--------|------|\n| `training_method` | 训练方法（标准/DPO/SimPO/RPO 等） |\n| `dpo_beta` | DPO 的 beta 参数 |\n| `dpo_normalize_logratios_by_length` | 是否按长度归一化 |\n| `rpo_alpha` | RPO alpha 参数 |\n| `simpo_gamma` | SimPO gamma 参数 |\n\n### 多模态训练\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `train_vision` | `bool` | 是否训练视觉编码器 |\n| `multimodal_params` | `dict` | 多模态相关参数 |\n\n### Weights & Biases 集成\n\n| 参数名 | 说明 |\n|--------|------|\n| `wandb_api_key` | W&B API 密钥 |\n| `wandb_base_url` | W&B 基础 URL |\n| `wandb_project_name` | W&B 项目名称 |\n| `wandb_name` | W&B 运行名称 |\n\n### 其他高级参数\n\n| 参数名 | 说明 |\n|--------|------|\n| `train_on_inputs` | 是否在输入上训练（支持 auto 自动判断） |\n| `from_checkpoint` | 从指定检查点继续训练 |\n| `from_hf_model` | 从 Hugging Face 模型开始训练 |\n| `hf_model_revision` | Hugging Face 模型版本 |\n| `hf_api_token` | Hugging Face API 令牌 |\n| `hf_output_repo_name` | Hugging Face 输出仓库名称 |\n\n*资料来源：[src/together/resources/finetune.py:36-56](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## 检查点管理\n\n### 检查点解析机制\n\n`_parse_raw_checkpoints` 函数负责解析服务器返回的检查点元数据：\n\n```python\ndef _parse_raw_checkpoints(\n    checkpoints: List[Dict[str, str]], id: str\n) -> List[FinetuneCheckpoint]:\n    parsed_checkpoints = []\n    for checkpoint in checkpoints:\n        step = checkpoint[\"step\"]\n        checkpoint_type = checkpoint[\"checkpoint_type\"]\n        checkpoint_name = (\n            f\"{id}:{step}\" if \"intermediate\" in checkpoint_type.lower() else id\n        )\n\n        parsed_checkpoints.append(\n            FinetuneCheckpoint(\n                type=checkpoint_type,\n                timestamp=checkpoint[\"created_at\"],\n                name=checkpoint_name,\n            )\n        )\n\n    parsed_checkpoints.sort(key=lambda x: x.timestamp, reverse=True)\n    return parsed_checkpoints\n```\n\n检查点按时间戳降序排列，最新的检查点排在前面。\n\n*资料来源：[src/together/resources/finetune.py:78-97](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n### 检查点类型\n\n| 类型 | 说明 | 适用场景 |\n|------|------|----------|\n| `default` | 默认检查点 | 标准训练 |\n| `intermediate` | 中间检查点 | 定期保存 |\n| `merged` | 合并检查点 | LoRA 适配器与基础模型合并 |\n| `adapter` | 适配器检查点 | 仅 LoRA 权重 |\n\n---\n\n## CLI 微调命令\n\nTogether CLI 提供了完整的微调命令行接口。\n\n### 查看帮助\n\n```bash\ntogether fine-tuning --help\n```\n\n### 下载微调检查点\n\n```bash\ntogether fine-tuning download <FINE_TUNE_ID> \\\n  --output_dir ./checkpoints \\\n  --checkpoint-step 1000 \\\n  --checkpoint-type merged\n```\n\n| CLI 参数 | 说明 |\n|----------|------|\n| `--output_dir` / `-o` | 输出目录路径 |\n| `--checkpoint-step` / `-s` | 检查点步数（默认最新） |\n| `--checkpoint-type` | 检查点类型 |\n\n*资料来源：[src/together/cli/api/finetune.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)*\n\n### 删除微调任务\n\n```bash\ntogether fine-tuning delete <FINE_TUNE_ID> --force\n```\n\n| CLI 参数 | 说明 |\n|----------|------|\n| `--force` | 强制删除，无需确认 |\n| `--quiet` / `-y` | 静默模式，不提示确认 |\n\n*资料来源：[src/together/cli/api/finetune.py:60-80](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)*\n\n---\n\n## 数据格式验证\n\nTogether SDK 在 `src/together/utils/files.py` 中实现了严格的数据格式验证机制。\n\n### 支持的数据格式\n\n微调数据必须符合特定的 JSON 格式要求：\n\n1. **文本消息**\n```json\n{\n  \"type\": \"text\",\n  \"text\": \"用户输入内容\"\n}\n```\n\n2. **多模态消息**（仅支持用户角色）\n```json\n{\n  \"type\": \"image_url\",\n  \"image_url\": {\n    \"url\": \"https://...\"\n  }\n}\n```\n\n### 验证规则\n\n| 规则 | 错误类型 | 说明 |\n|------|----------|------|\n| 内容必须为 dict | `InvalidFileFormatError` | JSON 结构错误 |\n| 必须包含 `type` 字段 | `InvalidFileFormatError` | 缺少类型标识 |\n| 文本内容必须为字符串 | `InvalidFileFormatError` | 文本格式错误 |\n| 图片仅限用户消息 | `InvalidFileFormatError` | 角色限制 |\n| 图片 URL 必须为字典 | `InvalidFileFormatError` | URL 格式错误 |\n| Base64 图片最大 10MB | `InvalidFileFormatError` | 文件过大 |\n| 每条消息最多 10 张图片 | `InvalidFileFormatError` | 图片数量超限 |\n\n*资料来源：[src/together/utils/files.py:1-80](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)*\n\n---\n\n## 价格估算机制\n\n在提交微调任务前，SDK 会自动进行价格估算：\n\n```python\nif from_checkpoint is None and from_hf_model is None:\n    price_estimation_result = self.estimate_price(\n        training_file=training_file,\n        validation_file=validation_file,\n        model=model_name,\n        n_epochs=finetune_request.n_epochs,\n        n_evals=finetune_request.n_evals,\n        training_type=\"lora\" if lora else \"full\",\n        training_method=training_method,\n    )\n    price_limit_passed = price_estimation_result.allowed_to_proceed\nelse:\n    price_limit_passed = True\n```\n\n价格估算基于以下因素：\n- 训练文件大小\n- 验证文件大小\n- 模型类型\n- 训练轮数\n- 评估次数\n- 训练类型（全量/LoRA）\n- 训练方法\n\n*资料来源：[src/together/resources/finetune.py:60-73](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## 异步操作支持\n\nTogether SDK 提供异步客户端用于并发微调任务管理：\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def fine_tune_multiple():\n    tasks = [\n        async_client.fine_tuning.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            training_file=file_id,\n        )\n        for file_id in training_files\n    ]\n    results = await asyncio.gather(*tasks)\n```\n\n---\n\n## 工作流程图\n\n```mermaid\ngraph TD\n    A[准备训练数据] --> B[上传数据文件]\n    B --> C{选择训练方式}\n    C -->|全量微调| D[设置基础参数]\n    C -->|LoRA| E[配置 LoRA 参数]\n    C -->|DPO/SimPO| F[配置强化学习参数]\n    D --> G[价格估算]\n    E --> G\n    F --> G\n    G --> H{价格限制检查}\n    H -->|通过| I[提交训练任务]\n    H -->|超出| J[调整参数或确认]\n    J --> G\n    I --> K[监控训练进度]\n    K --> L[生成检查点]\n    L --> M{训练完成?}\n    M -->|否| K\n    M -->|是| N[下载最终模型]\n    N --> O[部署使用]\n```\n\n---\n\n## 最佳实践\n\n### 1. 数据准备\n- 确保训练数据格式正确，参考数据格式验证章节\n- 使用验证集监控训练效果\n- 数据量建议不少于 1000 条样本\n\n### 2. 参数选择\n- 首次尝试使用默认参数\n- LoRA 微调时，`lora_r` 通常设置在 8-16 之间\n- 学习率建议从 1e-5 开始，逐步调整\n\n### 3. 检查点管理\n- 设置合理的 `n_checkpoints` 值\n- 定期保存中间检查点便于恢复\n- 使用 `--checkpoint-type merged` 获取可直接部署的模型\n\n### 4. 成本控制\n- 充分利用价格估算功能\n- 从检查点继续训练可节省成本\n- 使用 `wandb` 监控训练过程\n\n---\n\n## 错误处理\n\n微调过程中可能遇到的常见错误及解决方案：\n\n| 错误类型 | 可能原因 | 解决方案 |\n|----------|----------|----------|\n| `FileTypeError` | 数据文件格式不支持 | 确保文件为 JSONL 格式 |\n| `RateLimitError` | API 请求过于频繁 | 降低请求频率 |\n| `Timeout` | 训练任务超时 | 减少训练数据量或轮数 |\n| `APIConnectionError` | 网络连接问题 | 检查网络设置和 API 密钥 |\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：togethercomputer/together-python\n\n摘要：发现 12 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。\n\n## 1. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作: 假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:624113979 | https://github.com/togethercomputer/together-python | README/documentation is current enough for a first validation pass.\n\n## 2. 运行坑 · 来源证据：v.1.5.31\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.31\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ec69ff431b15448799cc64a826efd011 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. 运行坑 · 来源证据：v.1.5.33\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.33\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8246897bffc548df9673fe0c390cb514 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. 运行坑 · 来源证据：v1.5.28\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v1.5.28\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7e7977d7006e43939b5ceb03d0efad33 | https://github.com/togethercomputer/together-python/releases/tag/v1.5.28 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. 维护坑 · 来源证据：v.1.5.29\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v.1.5.29\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e91b0421f8fe42ac815a709d90dcca27 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 维护坑 · 来源证据：v1.5.27\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v1.5.27\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_569e5bacb3584ae794141c49af91c5db | https://github.com/togethercomputer/together-python/releases/tag/v1.5.27 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作: 维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | last_activity_observed missing\n\n## 8. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作: 下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n\n## 9. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作: 评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 来源证据：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4b91e5a8164f4aa9910f3d9737f1995c | https://github.com/togethercomputer/together-python/issues/443 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作: issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | issue_or_pr_quality=unknown\n\n## 12. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | release_recency=unknown\n\n<!-- canonical_name: togethercomputer/together-python; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "together-python",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:624113979",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/togethercomputer/together-python"
        },
        {
          "evidence_id": "art_66466be6154f4cc4b9633d5187fc3147",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/togethercomputer/together-python#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "together-python 说明书",
      "toc": [
        "https://github.com/togethercomputer/together-python 项目说明书",
        "目录",
        "项目介绍",
        "项目概述",
        "项目架构",
        "主要功能",
        "启动微调任务",
        "安装与配置",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "cc9f25369987e73bcd037be955833c37ac8a9109",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "README.md",
      "examples/code_interpreter_demo.py",
      "examples/tokenize_data.py",
      "src/together/version.py",
      "src/together/together_response.py",
      "src/together/client.py",
      "src/together/constants.py",
      "src/together/filemanager.py",
      "src/together/error.py",
      "src/together/__init__.py",
      "src/together/cli/cli.py",
      "src/together/cli/__init__.py",
      "src/together/abstract/api_requestor.py",
      "src/together/abstract/__init__.py",
      "src/together/utils/tools.py",
      "src/together/utils/api_helpers.py",
      "src/together/utils/_log.py",
      "src/together/utils/__init__.py",
      "src/together/utils/files.py",
      "src/together/resources/batch.py",
      "src/together/resources/endpoints.py",
      "src/together/resources/embeddings.py",
      "src/together/resources/models.py",
      "src/together/resources/finetune.py",
      "src/together/resources/completions.py",
      "src/together/resources/images.py",
      "src/together/resources/rerank.py",
      "src/together/resources/code_interpreter.py",
      "src/together/resources/__init__.py",
      "src/together/resources/evaluation.py",
      "src/together/resources/videos.py",
      "src/together/resources/files.py",
      "src/together/legacy/embeddings.py",
      "src/together/legacy/models.py",
      "src/together/legacy/finetune.py",
      "src/together/legacy/complete.py",
      "src/together/legacy/images.py",
      "src/together/legacy/__init__.py",
      "src/together/legacy/base.py"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# together-python - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 together-python 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `pip install together` 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：真实输出质量不能在安装前相信。\n- **继续会触碰**：命令执行、本地环境或项目文件、环境变量 / API Key\n\n### 现在可以相信\n\n- **适合人群线索：想在安装前理解开源项目价值和边界的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`, `src/together/cli/cli.py`, `src/together/client.py`, `src/together/constants.py` 等\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0004` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0005` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：116\n- 重要文件覆盖：18/116\n- 证据索引条目：18\n- 角色 / Skill 条目：6\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 together-python 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 together-python 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 together-python 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 6 个角色 / Skill / 项目文档条目。\n\n- **Together V1**（project_doc）：!NOTE 🚀 Together Python SDK 2.0 is now available! V1 is now considered deprecated and will be maintained in maintanence mode. All new features and development will occur in the 2.0 SDK. Check out the new SDK: together-py https://github.com/togethercomputer/together-py 📖 Migration Guide: https://docs.together.ai/docs/pythonv2-migration-guide https://docs.together.ai/docs/pythonv2-migration-guide Upgrade Using uv Reco… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **Contributing Guidelines**（project_doc）：Pull requests, bug reports, and all other forms of contribution are welcomed and highly encouraged! :octocat: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Describe your changes**（project_doc）：Have you read the Contributing Guidelines https://github.com/togethercomputer/together/blob/main/CONTRIBUTING.md ? 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/PULL_REQUEST_TEMPLATE.md`\n- **Contributor Covenant Code of Conduct**（project_doc）：Contributor Covenant Code of Conduct 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CODE_OF_CONDUCT.md`\n- **Bug report**（project_doc）：Describe the bug A clear and concise description of what the bug is. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **Feature request**（project_doc）：Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when ... 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n\n## 证据索引\n\n- 共索引 18 条证据。\n\n- **Together V1**（documentation）：!NOTE 🚀 Together Python SDK 2.0 is now available! V1 is now considered deprecated and will be maintained in maintanence mode. All new features and development will occur in the 2.0 SDK. Check out the new SDK: together-py https://github.com/togethercomputer/together-py 📖 Migration Guide: https://docs.together.ai/docs/pythonv2-migration-guide https://docs.together.ai/docs/pythonv2-migration-guide Upgrade Using uv Recommended : Using pip: 证据：`README.md`\n- **Contributing Guidelines**（documentation）：Pull requests, bug reports, and all other forms of contribution are welcomed and highly encouraged! :octocat: 证据：`CONTRIBUTING.md`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`\n- **Describe your changes**（documentation）：Have you read the Contributing Guidelines https://github.com/togethercomputer/together/blob/main/CONTRIBUTING.md ? 证据：`.github/PULL_REQUEST_TEMPLATE.md`\n- **Contributor Covenant Code of Conduct**（documentation）：Contributor Covenant Code of Conduct 证据：`CODE_OF_CONDUCT.md`\n- **Bug Report**（documentation）：Describe the bug A clear and concise description of what the bug is. 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **Feature Request**（documentation）：Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when ... 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n- **Devcontainer**（structured_config）：{ \"name\": \"Together Python Development\", \"build\": { \"dockerfile\": \"Dockerfile\" }, \"features\": { \"ghcr.io/devcontainers/features/git:1\": {}, \"ghcr.io/devcontainers/features/node:1\": {}, \"ghcr.io/devcontainers/features/java:1\": { \"version\": \"17\", \"installMaven\": false, \"installGradle\": false } }, \"customizations\": { \"vscode\": { \"extensions\": \"ms-python.python\", \"ms-python.vscode-pylance\", \"ms-python.isort\", \"charliermarsh.ruff\", \"ms-python.mypy-type-checker\", \"eamodio.gitlens\" , \"settings\": { \" python \": { \"editor.defaultFormatter\": \"charliermarsh.ruff\" }, \"editor.formatOnSave\": true, \"editor.codeActionsOnSave\": { \"source.fixAll\": \"explicit\", \"source.organizeImports\": \"explicit\" }, \"ruff.line… 证据：`.devcontainer/devcontainer.json`\n- **Install pre-commit**（source_file）：FROM mcr.microsoft.com/devcontainers/python:3.10 证据：`.devcontainer/Dockerfile`\n- **To get started with Dependabot version updates, you'll need to specify which**（source_file）：To get started with Dependabot version updates, you'll need to specify which package ecosystems to update and where the package manifests are located. Please see the documentation for all configuration options: https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 证据：`.github/dependabot.yml`\n- **Byte-compiled / optimized / DLL files**（source_file）：Byte-compiled / optimized / DLL files pycache / .py cod $py.class 证据：`.gitignore`\n- **.Pre Commit Config**（source_file）：repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - id: check-docstring-first - id: check-merge-conflict - id: check-toml - repo: https://github.com/psf/black rev: 24.3.0 hooks: - id: black - repo: https://github.com/pre-commit/mirrors-mypy rev: 'v1.8.0' hooks: - id: mypy args: --strict additional dependencies: types-requests, types-tqdm, types-tabulate, types-click, types-filelock, types-Pillow, rich, pyarrow-stubs, pydantic, aiohttp exclude: ^tests/ 证据：`.pre-commit-config.yaml`\n- **Default target executed when no arguments are given to make.**（source_file）：.PHONY: all format lint test tests test watch integration tests docker tests help extended tests 证据：`Makefile`\n- **Create a code interpreter instance**（source_file）：Create a code interpreter instance code interpreter = client.code interpreter 证据：`examples/code_interpreter_demo.py`\n- **see default of ignore index**（source_file）：import argparse import logging from functools import partial from multiprocessing import cpu count from typing import Dict, List 证据：`examples/tokenize_data.py`\n- **Mypy**（source_file）：mypy plugins = pydantic.mypy 证据：`mypy.ini`\n- **Starting with NumPy 1.25, NumPy is by default as far back compatible**（source_file）：build-system requires = \"poetry\", Starting with NumPy 1.25, NumPy is by default as far back compatible as oldest-support-numpy was customizable with a NPY TARGET VERSION define . For older Python versions where NumPy 1.25 is not yet avaiable continue using oldest-support-numpy. \"oldest-supported-numpy =0.14; python version =1.25; python version ='3.9'\", build-backend = \"poetry.masonry.api\" 证据：`pyproject.toml`\n- **Tox**（source_file）：tox envlist = py38, py39, py310, py311 证据：`tox.ini`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `CONTRIBUTING.md`, `LICENSE`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `CONTRIBUTING.md`, `LICENSE`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **项目介绍**：importance `high`\n  - source_paths: README.md, src/together/__init__.py, src/together/version.py\n- **安装与配置**：importance `high`\n  - source_paths: pyproject.toml, src/together/__init__.py, src/together/constants.py\n- **客户端架构**：importance `high`\n  - source_paths: src/together/client.py, src/together/abstract/api_requestor.py, src/together/together_response.py, src/together/resources/__init__.py\n- **请求流程与抽象层**：importance `medium`\n  - source_paths: src/together/abstract/api_requestor.py, src/together/abstract/__init__.py, src/together/error.py, src/together/together_response.py\n- **聊天补全 API**：importance `high`\n  - source_paths: src/together/resources/chat/__init__.py, src/together/resources/chat/completions.py, src/together/types/chat_completions.py\n- **文本补全 API**：importance `high`\n  - source_paths: src/together/resources/completions.py, src/together/types/completions.py\n- **多模态功能**：importance `medium`\n  - source_paths: src/together/resources/images.py, src/together/resources/code_interpreter.py, src/together/resources/videos.py, src/together/resources/audio/__init__.py, src/together/types/images.py\n- **嵌入与重排序**：importance `medium`\n  - source_paths: src/together/resources/embeddings.py, src/together/resources/rerank.py, src/together/types/embeddings.py, src/together/types/rerank.py\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `cc9f25369987e73bcd037be955833c37ac8a9109`\n- inspected_files: `pyproject.toml`, `README.md`, `examples/code_interpreter_demo.py`, `examples/tokenize_data.py`, `src/together/version.py`, `src/together/together_response.py`, `src/together/client.py`, `src/together/constants.py`, `src/together/filemanager.py`, `src/together/error.py`, `src/together/__init__.py`, `src/together/cli/cli.py`, `src/together/cli/__init__.py`, `src/together/abstract/api_requestor.py`, `src/together/abstract/__init__.py`, `src/together/utils/tools.py`, `src/together/utils/api_helpers.py`, `src/together/utils/_log.py`, `src/together/utils/__init__.py`, `src/together/utils/files.py`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:624113979 | https://github.com/togethercomputer/together-python | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：v.1.5.31\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.31\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_ec69ff431b15448799cc64a826efd011 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：v.1.5.33\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.33\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_8246897bffc548df9673fe0c390cb514 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：v1.5.28\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v1.5.28\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_7e7977d7006e43939b5ceb03d0efad33 | https://github.com/togethercomputer/together-python/releases/tag/v1.5.28 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：v.1.5.29\n\n- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v.1.5.29\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_e91b0421f8fe42ac815a709d90dcca27 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：v1.5.27\n\n- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v1.5.27\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_569e5bacb3584ae794141c49af91c5db | https://github.com/togethercomputer/together-python/releases/tag/v1.5.27 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 来源证据：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_4b91e5a8164f4aa9910f3d9737f1995c | https://github.com/togethercomputer/together-python/issues/443 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：togethercomputer/together-python\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：local_cli\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 能力判断依赖假设（medium）：假设不成立时，用户拿不到承诺的能力。 建议检查：将假设转成下游验证清单。\n- 来源证据：v.1.5.31（medium）：可能阻塞安装或首次运行。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v.1.5.33（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v1.5.28（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v.1.5.29（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/togethercomputer/together-python 项目说明书\n\n生成时间: 2026-05-21 18:14:28 UTC\n\n## 目录\n\n- [项目介绍](#page-introduction)\n- [安装与配置](#page-installation)\n- [客户端架构](#page-client-architecture)\n- [请求流程与抽象层](#page-request-flow)\n- [聊天补全 API](#page-chat-completions)\n- [文本补全 API](#page-completions)\n- [多模态功能](#page-multimodal)\n- [嵌入与重排序](#page-embeddings-rerank)\n- [文件管理](#page-files-management)\n- [模型微调](#page-finetuning)\n\n<a id='page-introduction'></a>\n\n## 项目介绍\n\n### 相关页面\n\n相关主题：[安装与配置](#page-installation), [客户端架构](#page-client-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n- [src/together/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/__init__.py)\n- [CONTRIBUTING.md](https://github.com/togethercomputer/together-python/blob/main/CONTRIBUTING.md)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/resources/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)\n- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n</details>\n\n# 项目介绍\n\nTogether Python 是一个开源的 Python 客户端库和命令行工具，用于与 Together AI 平台进行交互。该项目提供了对 Together AI 强大语言模型、嵌入模型、图像生成和微调服务的便捷访问能力。\n\n## 项目概述\n\nTogether Python 由 Together Computer 团队开发和维护，旨在为开发者提供一套完整、简洁的 API 接口，使其能够轻松地将 Together AI 平台的各种 AI 能力集成到自己的应用程序中。\n\n### 核心特性\n\n| 特性 | 说明 |\n|------|------|\n| **Python 客户端** | 面向对象的 Python API，简化与 Together AI 的交互 |\n| **CLI 工具** | 命令行界面，支持快速调用和脚本集成 |\n| **流式输出** | 支持实时流式 token 输出 |\n| **异步支持** | 提供异步客户端，支持并发请求处理 |\n| **多模态支持** | 支持文本、图像等多种输入类型 |\n| **微调服务** | 提供完整的模型微调工作流 |\n\n资料来源：[README.md:1-30]()\n\n## 项目架构\n\nTogether Python 采用模块化设计，主要包含以下几个核心组件：\n\n### 架构图\n\n```mermaid\ngraph TD\n    subgraph \"客户端层\"\n        Python[Python 客户端]\n        CLI[CLI 命令行工具]\n        Async[异步客户端]\n    end\n    \n    subgraph \"资源模块\"\n        Chat[Chat Completions]\n        Completions[Completions]\n        Embeddings[Embeddings]\n        Images[Images]\n        Rerank[Reranking]\n        FineTuning[Fine-Tuning]\n    end\n    \n    subgraph \"核心层\"\n        Requestor[API Requestor]\n        FileManager[文件管理器]\n        Error[错误处理]\n    end\n    \n    subgraph \"Together AI 平台\"\n        API[REST API]\n        Models[模型服务]\n    end\n    \n    Python --> Chat\n    Python --> Completions\n    Python --> Embeddings\n    Python --> Images\n    Python --> Rerank\n    Python --> FineTuning\n    \n    CLI --> Chat\n    CLI --> Completions\n    CLI --> FineTuning\n    \n    Async --> Chat\n    Async --> Completions\n    \n    Chat --> Requestor\n    Completions --> Requestor\n    Embeddings --> Requestor\n    Images --> Requestor\n    Rerank --> Requestor\n    FineTuning --> Requestor\n    \n    Requestor --> API\n    FineTuning --> FileManager\n    FileManager --> API\n    API --> Models\n```\n\n### 核心模块说明\n\n#### 异常处理模块\n\n项目定义了一套完整的异常类型体系，用于处理各种错误场景：\n\n| 异常类型 | 说明 |\n|---------|------|\n| `TogetherException` | 基础异常类 |\n| `RateLimitError` | 速率限制错误 |\n| `FileTypeError` | 文件类型错误 |\n| `APIConnectionError` | API 连接错误 |\n| `Timeout` | 超时错误 |\n\n资料来源：[src/together/error.py:1-60]()\n\n#### 聊天补全模块\n\n提供 Chat Completions API 接口，支持多种消息格式和工具调用：\n\n```python\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n)\n```\n\n资料来源：[README.md:30-40]()\n\n#### 微调模块\n\n提供完整的模型微调工作流程，包括价格估算、训练配置和检查点管理：\n\n| 参数 | 说明 |\n|------|------|\n| `n_epochs` | 训练轮数 |\n| `batch_size` | 批处理大小 |\n| `learning_rate` | 学习率 |\n| `lora` | 是否启用 LoRA |\n| `training_method` | 训练方法（DPO、SimPO 等）|\n\n资料来源：[src/together/resources/finetune.py:1-100]()\n\n## 主要功能\n\n### 1. 对话补全（Chat Completions）\n\n支持单轮和多轮对话，以及多模态输入（文本+图像）：\n\n```mermaid\ngraph LR\n    A[用户消息] --> B[构建消息列表]\n    B --> C[API 请求]\n    C --> D{流式?}\n    D -->|是| E[流式响应]\n    D -->|否| F[完整响应]\n    E --> G[逐块处理]\n    F --> H[返回完整结果]\n```\n\n资料来源：[src/together/resources/chat/completions.py:1-50]()\n\n### 2. 补全（Completions）\n\n提供传统的文本补全功能：\n\n```python\nresponse = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    max_tokens=200,\n)\n```\n\n资料来源：[README.md:80-90]()\n\n### 3. 嵌入（Embeddings）\n\n支持文本嵌入向量生成：\n\n```python\noutputs = client.embeddings.create(\n    model='togethercomputer/m2-bert-80M-8k-retrieval',\n    input=texts\n)\n```\n\n### 4. 图像生成（Image Generation）\n\n提供图像生成能力：\n\n```python\nresponse = client.images.generate(\n    prompt=\"space robots\",\n    model=\"stabilityai/stable-diffusion-xl-base-1.0\",\n    steps=10,\n    n=4,\n)\n```\n\n### 5. 重排序（Reranking）\n\n支持文档重排序功能：\n\n```python\noutputs = client.rerank.create(\n    model=model,\n    query=query,\n    documents=documents,\n    top_n=top_n\n)\n```\n\n### 6. 模型微调（Fine-Tuning）\n\n提供完整的微调工作流程：\n\n```bash\n# 启动微调任务\ntogether fine-tuning create \\\n  --training-file <FILE_ID> \\\n  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \\\n  --n-epochs 3\n```\n\n#### 支持的微调方法\n\n| 训练方法 | 说明 |\n|---------|------|\n| `full` | 全参数微调 |\n| `lora` | LoRA 低秩适配微调 |\n| `dpo` | 直接偏好优化 |\n| `simpo` | 简单偏好优化 |\n| `rpo` | 相对偏好优化 |\n\n资料来源：[src/together/resources/finetune.py:50-150]()\n\n## 安装与配置\n\n### 环境要求\n\n- Python 3.10+\n- Poetry 1.6.1+\n\n### 安装步骤\n\n1. **获取 API Key**：访问 [Together AI 注册页面](https://api.together.xyz/) 获取 API Key\n\n2. **设置环境变量**：\n\n```shell\nexport TOGETHER_API_KEY=xxxxx\n```\n\n3. **安装依赖**：\n\n```bash\npoetry install --with quality,tests\n```\n\n4. **设置 pre-commit**：\n\n```bash\npre-commit install\n```\n\n资料来源：[CONTRIBUTING.md:1-30]()\n\n## 使用方式\n\n### Python 客户端使用\n\n```python\nfrom together import Together\n\n# 初始化客户端\nclient = Together(api_key=\"xxxxx\")\n\n# 创建聊天请求\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"Hello, how are you?\"}]\n)\n\nprint(response.choices[0].message.content)\n```\n\n### 异步客户端使用\n\n```python\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\ntasks = [\n    async_client.completions.create(model=\"...\", prompt=\"...\"),\n    async_client.completions.create(model=\"...\", prompt=\"...\")\n]\n\nresponses = await asyncio.gather(*tasks)\n```\n\n### CLI 命令行使用\n\n```bash\n# 聊天补全\ntogether chat.completions --message \"Hello\" --model meta-llama/Llama-4-Scout-17B-16E-Instruct\n\n# 文本补全\ntogether completions \"Large language models are \" --model meta-llama/Llama-4-Scout-17B-16E-Instruct\n\n# 图像生成\ntogether images generate \"space robots\" --model stabilityai/stable-diffusion-xl-base-1.0\n\n# 文件操作\ntogether files upload example.jsonl\ntogether files list\ntogether files retrieve <FILE_ID>\n\n# 微调任务\ntogether fine-tuning create --training-file <FILE_ID> --model <MODEL>\ntogether fine-tuning list\ntogether fine-tuning events <FINE_TUNE_ID>\ntogether fine-tuning download <FINE_TUNE_ID>\n```\n\n## 错误处理\n\n项目实现了完善的错误处理机制：\n\n```mermaid\ngraph TD\n    A[API 请求] --> B{响应状态}\n    B -->|成功| C[返回结果]\n    B -->|4xx 错误| D[客户端错误]\n    B -->|5xx 错误| E[服务器错误]\n    B -->|速率限制| F[RateLimitError]\n    B -->|超时| G[Timeout]\n    \n    D --> H[TogetherException]\n    E --> H\n    F --> H\n    G --> H\n```\n\n## 开发指南\n\n### 本地开发设置\n\n```bash\n# 安装开发依赖\npoetry install --with quality,tests\n\n# 格式化和代码检查\nmake format\n\n# 运行测试\nmake tests\n```\n\n### 测试说明\n\n| 测试类型 | 说明 | 命令 |\n|---------|------|------|\n| 单元测试 | 不需要 API Key | `make tests` |\n| 集成测试 | 需要 API Key，会产生费用 | `make integration_tests` |\n\n资料来源：[CONTRIBUTING.md:30-60]()\n\n## 技术规格\n\n### 支持的模型类型\n\n| 类型 | 示例模型 |\n|------|---------|\n| 聊天模型 | Llama-4, Llama-3, Qwen, Gemma |\n| 代码模型 | CodeLlama, DeepSeek-Coder |\n| 嵌入模型 | M2-BERT, GTE |\n| 图像模型 | Stable Diffusion XL |\n| 视觉模型 | Llama-3.2-Vision |\n\n### API 特性支持\n\n| 功能 | 支持状态 |\n|------|---------|\n| 流式输出 | ✅ 支持 |\n| 工具/函数调用 | ✅ 支持 |\n| JSON 模式 | ✅ 支持 |\n| 多模态输入 | ✅ 支持 |\n| 并发请求 | ✅ 支持 |\n| 文件管理 | ✅ 支持 |\n| 微调训练 | ✅ 支持 |\n\n## 项目结构\n\n```\ntogether-python/\n├── src/together/\n│   ├── __init__.py          # 主入口\n│   ├── error.py             # 异常定义\n│   ├── version.py           # 版本信息\n│   ├── client.py            # 客户端实现\n│   ├── filemanager.py       # 文件管理器\n│   ├── resources/           # API 资源模块\n│   │   ├── chat/\n│   │   │   └── completions.py\n│   │   ├── completions.py\n│   │   ├── embeddings.py\n│   │   ├── images.py\n│   │   ├── rerank.py\n│   │   └── finetune.py\n│   ├── utils/\n│   │   └── files.py         # 文件处理工具\n│   └── cli/\n│       └── api/             # CLI 命令\n│           ├── chat.py\n│           ├── completions.py\n│           ├── finetune.py\n│           └── ...\n└── tests/                   # 测试文件\n```\n\n## 总结\n\nTogether Python 是一个功能全面、易于使用的 Python 客户端库，为开发者提供了与 Together AI 平台交互的便捷方式。通过统一的 Python API 和 CLI 工具，开发者可以轻松实现聊天补全、文本补全、嵌入生成、图像生成和模型微调等多种 AI 功能。项目采用模块化设计，具有良好的可扩展性和维护性，适合各类 AI 应用的开发和部署。\n\n---\n\n<a id='page-installation'></a>\n\n## 安装与配置\n\n### 相关页面\n\n相关主题：[项目介绍](#page-introduction), [客户端架构](#page-client-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n- [CONTRIBUTING.md](https://github.com/togethercomputer/together-python/blob/main/CONTRIBUTING.md)\n- [pyproject.toml](https://github.com/togethercomputer/together-python/blob/main/pyproject.toml)\n- [src/together/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/__init__.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n</details>\n\n# 安装与配置\n\n本文档详细说明 together-python 项目的安装方法、环境配置、依赖管理以及开发环境搭建流程。\n\n## 概述\n\ntogether-python 是 Together AI 提供的官方 Python SDK，提供了 Python 客户端库和 CLI 工具两种使用方式。该库支持多种核心功能，包括对话补全、文本补全、图像生成、嵌入向量生成以及模型微调等。资料来源：[README.md:1-10]()\n\n## 环境要求\n\n### 系统要求\n\n| 要求项 | 最低版本 | 推荐版本 |\n|--------|----------|----------|\n| Python | 3.10 | 3.10+ |\n| Poetry | 1.6.1 | 1.6.1+ |\n| pip | 21.0 | 最新版本 |\n\n### 依赖环境管理器说明\n\n该项目使用 [Poetry](https://python-poetry.org/) v1.6.1+ 作为依赖管理器。如果使用 Conda 或 Pyenv 作为环境或包管理器，安装 Poetry 后需要配置 Poetry 使用虚拟环境的 Python 解释器。资料来源：[CONTRIBUTING.md:60-70]()\n\n```bash\npoetry config virtualenvs.prefer-active-python true\n```\n\n## 安装方式\n\n### 方式一：通过 PyPI 安装（推荐）\n\n使用 pip 直接安装 together-python 包：\n\n```bash\npip install together\n```\n\n### 方式二：通过 Poetry 安装开发依赖\n\n克隆仓库后，使用 Poetry 安装本地开发环境：\n\n```bash\ngit clone https://github.com/togethercomputer/together-python.git\ncd together-python\npoetry install --with quality,tests\n```\n\n此命令会安装所有必要的依赖，包括：\n- **quality**: 代码格式化和静态检查工具\n- **tests**: 测试框架和测试依赖\n\n资料来源：[CONTRIBUTING.md:54-58]()\n\n### 方式三：从源码安装\n\n```bash\npip install git+https://github.com/togethercomputer/together-python.git\n```\n\n## 环境变量配置\n\n### 获取 API Key\n\n1. 访问 Together Playground: https://api.together.ai\n2. 在设置页面创建 API Key: https://api.together.xyz/settings/api-keys\n\n### 配置环境变量\n\n**Linux/macOS:**\n\n```bash\nexport TOGETHER_API_KEY=your_api_key_here\n```\n\n**Windows (PowerShell):**\n\n```powershell\n$env:TOGETHER_API_KEY=\"your_api_key_here\"\n```\n\n**永久配置：**\n\n将上述命令添加到 shell 配置文件（`~/.bashrc`、`~/.zshrc` 或 `~/.profile`）中。\n\n资料来源：[README.md:5-10]()\n\n## 客户端初始化\n\n### 基础客户端初始化\n\n在代码中使用 API Key 初始化客户端：\n\n```python\nfrom together import Together\n\n# 使用环境变量中的 API Key\nclient = Together()\n\n# 或显式传入 API Key\nclient = Together(api_key=\"your_api_key_here\")\n```\n\n资料来源：[README.md:13-18]()\n\n### 异步客户端\n\n对于需要异步处理的场景，使用 `AsyncTogether` 类：\n\n```python\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n```\n\n### CLI 客户端\n\nCLI 工具在安装包后自动可用，无需额外配置。确保 `TOGETHER_API_KEY` 环境变量已设置即可。\n\n## 开发环境配置\n\n### 安装预提交钩子\n\n项目使用 pre-commit 进行代码格式化和 linting 自动检查。安装开发依赖后，运行：\n\n```bash\npre-commit install\n```\n\n这会在每次提交前自动执行格式化和检查。\n\n资料来源：[CONTRIBUTING.md:58-60]()\n\n### 代码格式化和检查\n\n提交代码前手动运行检查：\n\n```bash\n# 格式化代码\nmake format\n\n# 运行测试\nmake tests\n\n# 运行集成测试（需要 API Key，会产生费用）\nmake integration_tests\n```\n\n资料来源：[CONTRIBUTING.md:40-50]()\n\n## 可选依赖管理\n\n项目采用可选依赖策略，大部分用户不会安装所有依赖。引入新依赖时应遵循以下流程：\n\n1. 将依赖添加到可选组：\n   ```bash\n   poetry add --optional [package_name]\n   ```\n\n2. 在 `pyproject.toml` 中将依赖添加到 `extended_testing` extra\n\n3. 重新锁定依赖：\n   ```bash\n   poetry lock --no-update\n   ```\n\n4. 添加至少导入该代码的单元测试\n\n5. 使用 `@pytest.mark.requires(package_name)` 装饰需要该依赖的测试\n\n资料来源：[CONTRIBUTING.md:18-35]()\n\n## 项目结构\n\n```\ntogether-python/\n├── pyproject.toml          # 项目配置和依赖定义\n├── src/\n│   └── together/\n│       ├── __init__.py     # 包初始化和导出\n│       ├── error.py        # 异常定义\n│       ├── constants.py    # 常量定义\n│       ├── resources/      # 功能资源模块\n│       │   ├── chat/       # 聊天补全\n│       │   ├── completions.py  # 文本补全\n│       │   ├── images.py   # 图像生成\n│       │   ├── embeddings.py   # 嵌入向量\n│       │   ├── rerank.py    # 重排序\n│       │   └── finetune.py  # 模型微调\n│       └── cli/            # CLI 工具实现\n│           └── api/        # CLI 命令\n└── tests/                  # 测试文件\n```\n\n## 配置验证\n\n### 验证安装\n\n```python\nimport together\n\n# 检查版本\nprint(together.__version__)\n\n# 验证连接\nclient = Together()\nmodels = client.models.list()\nprint(f\"可用模型数量: {len(models.data)}\")\n```\n\n### 常见配置错误\n\n| 错误类型 | 错误信息 | 解决方案 |\n|----------|----------|----------|\n| 缺少 API Key | `AuthenticationError` | 设置 `TOGETHER_API_KEY` 环境变量 |\n| API Key 无效 | `AuthenticationError` | 检查 API Key 是否正确，确认账户状态 |\n| 速率限制 | `RateLimitError` | 降低请求频率，等待冷却时间 |\n| 网络问题 | `APIConnectionError` | 检查网络连接，确认代理设置 |\n\n资料来源：[src/together/error.py:1-50]()\n\n## 工作流程图\n\n```mermaid\ngraph TD\n    A[开始] --> B{是否安装 SDK?}\n    B -->|否| C[安装 together-python]\n    C --> D{是否有 API Key?}\n    D -->|否| E[申请 API Key]\n    E --> F[配置环境变量]\n    D -->|是| F\n    F --> G[初始化客户端]\n    G --> H{使用场景}\n    H -->|同步| I[使用 Together 客户端]\n    H -->|异步| J[使用 AsyncTogether 客户端]\n    H -->|CLI| K[使用 together CLI]\n    I --> L[调用 API]\n    J --> L\n    K --> L\n```\n\n## 下一步\n\n- [快速开始指南](../quickstart) - 了解基本使用方法\n- [聊天补全](../chat-completions) - 对话功能详解\n- [模型微调](../fine-tuning) - 自定义模型训练\n- [CLI 参考](../cli-reference) - 命令行工具完整文档\n\n---\n\n<a id='page-client-architecture'></a>\n\n## 客户端架构\n\n### 相关页面\n\n相关主题：[项目介绍](#page-introduction), [请求流程与抽象层](#page-request-flow)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/abstract/api_requestor.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/api_requestor.py)\n- [src/together/together_response.py](https://github.com/togethercomputer/together-python/blob/main/src/together/together_response.py)\n- [src/together/resources/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/__init__.py)\n- [src/together/resources/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n</details>\n\n# 客户端架构\n\n## 概述\n\nTogether Python 客户端是一个轻量级且易于使用的 Python 库和命令行工具，为 Together AI 平台提供统一的 API 接口。该客户端架构采用分层设计，核心层负责 HTTP 通信和请求处理，资源层提供各类 AI 能力的抽象接口，CLI 层提供命令行交互能力。\n\n客户端的核心设计目标包括：\n\n- **简化 API 调用**：通过 Pythonic 的接口封装底层 HTTP 请求细节\n- **支持同步和异步操作**：提供 `Together` 和 `AsyncTogether` 两种客户端实现\n- **流式响应支持**：原生支持流式输出，便于实时展示生成结果\n- **完整的类型提示**：使用 Pydantic 模型进行请求参数和响应数据的验证\n\n资料来源：[src/together/client.py]()\n\n## 架构分层\n\n### 整体架构图\n\n```mermaid\ngraph TD\n    A[客户端入口] --> B[Together / AsyncTogether]\n    B --> C[资源层 Resources]\n    C --> D[Chat Completions]\n    C --> E[Completions]\n    C --> F[Embeddings]\n    C --> G[Images]\n    C --> H[Fine-tuning]\n    C --> I[Files]\n    C --> J[Rerank]\n    B --> K[APIRequestor]\n    K --> L[HTTP 请求处理]\n    L --> M[Together API]\n```\n\n### 核心组件\n\n| 组件名称 | 文件路径 | 职责描述 |\n|---------|---------|---------|\n| Together | client.py | 同步客户端入口，管理 API 密钥和资源实例 |\n| AsyncTogether | client.py | 异步客户端入口，支持 asyncio 并发操作 |\n| APIRequestor | abstract/api_requestor.py | HTTP 请求的实际执行者，处理认证、重试、超时 |\n| TogetherResponse | together_response.py | 统一响应数据结构定义 |\n| 资源类 | resources/*.py | 封装各类 AI 能力的业务逻辑 |\n\n资料来源：[src/together/client.py](), [src/together/abstract/api_requestor.py]()\n\n## 客户端初始化\n\n### 基本用法\n\n```python\nfrom together import Together\n\n# 使用环境变量中的 API Key\nclient = Together()\n\n# 直接指定 API Key\nclient = Together(api_key=\"your-api-key-here\")\n```\n\n客户端初始化时接受以下配置参数：\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|-------|------|-------|------|\n| api_key | str | None | Together API 密钥，默认从环境变量 `TOGETHER_API_KEY` 读取 |\n| base_url | str | api.together.xyz | API 基础 URL |\n| timeout | float | 600 | 请求超时时间（秒） |\n| max_retries | int | 2 | 失败重试次数 |\n| client | httpx.Client | None | 可自定义的 HTTP 客户端实例 |\n\n资料来源：[src/together/client.py]()\n\n### 异步客户端\n\n```python\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\n# 在 async 函数中使用\nasync def main():\n    response = await async_client.chat.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        messages=[{\"role\": \"user\", \"content\": \"Hello!\"}]\n    )\n```\n\n异步客户端继承自 `AsyncHTTPHandler`，支持使用 `asyncio.gather` 等工具进行并发请求。\n\n资料来源：[src/together/resources/__init__.py]()\n\n## 请求处理流程\n\n### 同步请求流程\n\n```mermaid\nsequenceDiagram\n    participant C as Together 客户端\n    participant R as Resources\n    participant A as APIRequestor\n    participant H as HTTP Handler\n    \n    C->>R: 调用 .chat.completions.create()\n    R->>A: 创建 TogetherRequest\n    A->>H: request_raw() / request()\n    H->>H: 添加认证头\n    H->>H: 处理重试逻辑\n    H->>Together API: 发送 HTTP 请求\n    Together API-->>H: 返回响应\n    H-->>A: 解析响应数据\n    A-->>R: 返回 TogetherResponse\n    R-->>C: 转换为 Pydantic 模型\n```\n\n### 流式响应处理\n\n```python\nstream = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component\",\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n流式响应使用生成器模式，逐块返回数据。每个 chunk 都是一个 `CompletionChunk` 或 `ChatCompletionChunk` 对象。\n\n资料来源：[src/together/resources/completions.py](), [src/together/resources/chat/completions.py]()\n\n## API 请求器\n\n### APIRequestor 职责\n\n`APIRequestor` 是底层的 HTTP 请求处理器，封装了所有与 Together API 的通信逻辑：\n\n| 功能 | 说明 |\n|-----|------|\n| 认证处理 | 自动添加 Authorization 头和 Together-Version 头 |\n| 重试机制 | 基于指数退避的自动重试 |\n| 超时控制 | 支持可配置的总超时和连接超时 |\n| 错误处理 | 将 HTTP 错误转换为 Python 异常 |\n| 流式支持 | 处理 Server-Sent Events (SSE) 流 |\n\n### 请求方法\n\n```python\n# 同步请求\nresponse, status_code, duration = requestor.request(\n    options=TogetherRequest(\n        method=\"POST\",\n        url=\"chat/completions\",\n        params=payload,\n    ),\n)\n\n# 原始响应（用于文件下载等场景）\nraw_response = requestor.request_raw(\n    options=TogetherRequest(\n        method=\"GET\",\n        url=file_url,\n        headers={\"Range\": \"bytes=0-1\"},\n    ),\n)\n```\n\n资料来源：[src/together/abstract/api_requestor.py]()\n\n## 响应模型\n\n### 统一响应结构\n\n```mermaid\nclassDiagram\n    class TogetherResponse {\n        +Any data\n        +int status_code\n    }\n    \n    class ChatCompletionResponse {\n        +str id\n        +str object\n        +int created\n        +str model\n        +list choices\n        +Usage usage\n    }\n    \n    class CompletionResponse {\n        +str id\n        +str object\n        +int created\n        +str model\n        +list choices\n        +Usage usage\n    }\n    \n    TogetherResponse <|-- ChatCompletionResponse\n    TogetherResponse <|-- CompletionResponse\n```\n\n### 响应模型字段\n\n| 模型类 | 主要字段 | 说明 |\n|-------|---------|------|\n| ChatCompletionResponse | id, model, choices, usage | 聊天完成响应 |\n| CompletionResponse | id, model, choices, usage | 文本补全响应 |\n| EmbeddingResponse | data, model, usage | 向量嵌入响应 |\n| ImageResponse | data | 图像生成响应 |\n| Usage | prompt_tokens, completion_tokens, total_tokens | Token 使用统计 |\n\n资料来源：[src/together/together_response.py]()\n\n## 资源层设计\n\n### 资源模块概览\n\n```mermaid\ngraph TD\n    Resources --> Chat\n    Resources --> Completions\n    Resources --> Embeddings\n    Resources --> Images\n    Resources --> Files\n    Resources --> FineTuning\n    Resources --> Rerank\n    Resources --> Models\n```\n\n| 资源类 | 功能 | 核心方法 |\n|-------|-----|---------|\n| Chat | 聊天完成 | `create()`, `create_async()` |\n| Completions | 文本补全 | `create()`, `create_async()` |\n| Embeddings | 向量嵌入 | `create()` |\n| Images | 图像生成 | `generate()` |\n| Files | 文件管理 | `upload()`, `download()`, `list()`, `retrieve()`, `delete()` |\n| FineTuning | 模型微调 | `create()`, `submit()`, `estimate_price()` |\n| Rerank | 文档重排序 | `create()` |\n\n资料来源：[src/together/resources/__init__.py]()\n\n### 聊天完成资源\n\n聊天完成是最常用的功能之一，支持多种消息格式和工具调用：\n\n```python\n# 简单文本消息\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n)\n\n# 多模态消息（文本+图像）\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\"type\": \"text\", \"text\": \"What's in this image?\"},\n            {\"type\": \"image_url\", \"image_url\": {\"url\": \"https://example.com/image.png\"}}\n        ]\n    }]\n)\n```\n\n资料来源：[src/together/resources/chat/completions.py]()\n\n### 文件管理\n\n文件管理模块提供完整的上传、下载、列表查询等功能：\n\n```python\n# 上传文件\nresponse = client.files.upload(file=open(\"data.jsonl\", \"rb\"))\n\n# 检查文件\nclient.files.check(file_id)\n\n# 下载文件内容\ncontent = client.files.retrieve_content(file_id)\n\n# 列出文件\nfiles = client.files.list()\n```\n\n资料来源：[src/together/filemanager.py]()\n\n## 错误处理\n\n### 异常层次结构\n\n```mermaid\nclassDiagram\n    class TogetherException {\n        +str message\n        +Any http_status\n        +Any body\n    }\n    \n    class AuthenticationError {\n        <<extends TogetherException>>\n    }\n    \n    class RateLimitError {\n        <<extends TogetherException>>\n    }\n    \n    class APIConnectionError {\n        <<extends TogetherException>>\n    }\n    \n    class Timeout {\n        <<extends TogetherException>>\n    }\n    \n    class APIError {\n        <<extends TogetherException>>\n    }\n```\n\n### 异常类型说明\n\n| 异常类 | HTTP 状态码 | 说明 |\n|-------|------------|------|\n| TogetherException | - | 所有异常的基类 |\n| AuthenticationError | 401 | API 密钥无效或缺失 |\n| RateLimitError | 429 | 请求频率超限 |\n| APIConnectionError | - | 网络连接问题 |\n| Timeout | - | 请求超时 |\n| APIError | 4xx/5xx | 其他 API 错误 |\n\n```python\nfrom together.error import RateLimitError, AuthenticationError\n\ntry:\n    response = client.chat.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        messages=[{\"role\": \"user\", \"content\": \"Hello\"}],\n    )\nexcept AuthenticationError as e:\n    print(\"Invalid API key\")\nexcept RateLimitError as e:\n    print(\"Rate limit exceeded, please wait\")\n```\n\n资料来源：[src/together/error.py]()\n\n## 配置管理\n\n### 环境变量\n\n| 环境变量 | 说明 | 必需 |\n|---------|-----|-----|\n| TOGETHER_API_KEY | Together AI API 密钥 | 是 |\n| TOGETHER_BASE_URL | API 基础 URL（可选） | 否 |\n\n### 客户端配置示例\n\n```python\nfrom together import Together\nimport os\n\n# 方式一：环境变量\nclient = Together()  # 自动读取 TOGETHER_API_KEY\n\n# 方式二：直接传入\nclient = Together(api_key=os.environ.get(\"TOGETHER_API_KEY\"))\n\n# 方式三：自定义配置\nclient = Together(\n    api_key=\"your-key\",\n    base_url=\"https://api.together.xyz\",\n    timeout=120,\n    max_retries=3\n)\n```\n\n资料来源：[src/together/client.py]()\n\n## 最佳实践\n\n### 1. 异步并发请求\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def batch_requests():\n    tasks = [\n        async_client.chat.completions.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            messages=[{\"role\": \"user\", \"content\": prompt}],\n        )\n        for prompt in prompts\n    ]\n    responses = await asyncio.gather(*tasks)\n    return responses\n```\n\n### 2. 流式响应处理\n\n```python\nstream = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component\",\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n### 3. 错误重试机制\n\n客户端内置自动重试机制，支持指数退避策略。默认配置：\n\n- 最大重试次数：2\n- 超时时间：600 秒\n- 可通过自定义 httpx.Client 调整\n\n资料来源：[src/together/abstract/api_requestor.py]()\n\n## 扩展性\n\n### 自定义 HTTP 客户端\n\n```python\nimport httpx\nfrom together import Together\n\n# 使用自定义配置的 HTTP 客户端\ncustom_client = httpx.Client(\n    timeout=httpx.Timeout(60.0, connect=10.0),\n    proxies={\"http://\": \"http://proxy.example.com:8080\"},\n)\n\nclient = Together(client=custom_client)\n```\n\n### 资源扩展\n\n新功能可以通过扩展资源类来实现，所有资源类都遵循统一的接口模式：\n\n```python\nclass BaseResource:\n    def __init__(self, client: TogetherClient) -> None:\n        self._client = client\n```\n\n资料来源：[src/together/resources/__init__.py]()\n\n## 总结\n\nTogether Python 客户端采用清晰的分层架构设计，将 API 通信细节封装在 `APIRequestor` 中，对外提供直观的资源接口。核心设计原则包括：\n\n1. **简洁易用**：通过高级抽象简化 API 调用复杂度\n2. **类型安全**：使用 Pydantic 模型确保请求参数和响应数据的正确性\n3. **灵活扩展**：分层设计便于添加新功能和自定义行为\n4. **完善的错误处理**：层次化的异常体系便于精准捕获和处理错误\n\n该架构既适合快速原型开发，也能满足生产环境对稳定性和性能的要求。\n\n---\n\n<a id='page-request-flow'></a>\n\n## 请求流程与抽象层\n\n### 相关页面\n\n相关主题：[客户端架构](#page-client-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/abstract/api_requestor.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/api_requestor.py)\n- [src/together/abstract/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/abstract/__init__.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/together_response.py](https://github.com/togethercomputer/together-python/blob/main/src/together/together_response.py)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)\n</details>\n\n# 请求流程与抽象层\n\n## 概述\n\nTogether Python SDK 的请求流程与抽象层是整个库的核心架构部分，负责处理所有与 Together API 的通信交互。该层通过分层设计实现了请求的发送、响应的处理、错误的捕获与转换，以及同步/异步操作的支持。开发者通过 `Together` 客户端实例发起各类请求（如聊天补全、文生图、嵌入等），而底层的抽象层则负责将高层 API 调用转换为底层的 HTTP 请求，并与 Together 服务器进行交互。\n\n该架构的核心价值在于**解耦**与**统一**：上层资源（如 `Completions`、`Chat`、`Embeddings` 等）无需关心具体的网络通信细节，只需专注于业务逻辑参数的准备和响应数据的解析。所有底层网络通信、认证、超时重试等机制都由抽象层统一处理，确保了整个 SDK 的一致性与可维护性。\n\n从架构层面看，Together SDK 采用了典型的**客户端-请求者-响应**三层模型。`Together` 客户端作为入口点，提供各类资源对象；资源对象负责构建请求参数并调用请求者；`APIRequestor` 则处理底层的 HTTP 通信，包括认证头的生成、请求发送、超时控制以及错误处理。最终，响应数据通过 `TogetherResponse` 和具体的响应模型类（如 `ChatCompletionResponse`、`CompletionResponse`）返回给调用者。\n\n## 核心组件架构\n\nTogether SDK 的请求流程涉及多个核心组件，它们各司其职、协同工作。下表列出了主要组件及其职责：\n\n| 组件 | 文件位置 | 职责描述 |\n|------|----------|----------|\n| `Together` | `client.py` | 主客户端入口，管理所有资源实例 |\n| `APIRequestor` | `abstract/api_requestor.py` | 底层 HTTP 请求处理 |\n| `TogetherResponse` | `together_response.py` | 原始响应包装器 |\n| `TogetherRequest` | `abstract/` | 请求配置（URL、方法、参数） |\n| 资源类 | `resources/*.py` | 各业务功能的参数构建与响应解析 |\n\n`Together` 主类定义了所有支持的资源类型，包括 `completions`、`chat`、`embeddings`、`files`、`images`、`models`、`fine_tuning`、`rerank`、`audio`、`batches`、`code_interpreter`、`evaluation` 和 `videos`。每个资源都持有对底层客户端的引用，可以直接调用 `APIRequestor` 发起请求。这种设计使得添加新的 API 功能只需扩展资源类，而无需修改底层通信机制。\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[资源层<br/>Completions/Chat/Embeddings...]\n    B --> C[请求构建<br/>参数序列化]\n    C --> D[APIRequestor<br/>抽象请求者]\n    D --> E[HTTP 通信层<br/>requests/httpx]\n    E --> F[Together API 服务器]\n    F --> G[TogetherResponse<br/>原始响应]\n    G --> H[响应解析<br/>Pydantic 模型]\n    H --> I[业务响应对象<br/>ChatCompletion/Completion...]\n```\n\n## 请求流程详解\n\n### 同步请求流程\n\n同步请求是最基本的请求模式，适用于大多数使用场景。请求从客户端发起，经过资源层、请求构建层，最终由 `APIRequestor` 发送 HTTP 请求。以聊天补全为例，完整的请求流程如下：\n\n1. **客户端实例化**：用户创建 `Together` 客户端实例，可传入 `api_key`、`base_url`、`timeout` 等配置参数。若未显式提供，`api_key` 会自动从环境变量 `TOGETHER_API_KEY` 获取。\n2. **资源调用**：用户通过 `client.chat.completions.create()` 发起聊天补全请求，传入模型名称、消息列表等参数。\n3. **参数构建**：资源类将用户参数转换为 API 所需的格式，包括默认值填充、参数校验和序列化。\n4. **请求发送**：`APIRequestor` 接收 `TogetherRequest` 对象，构建完整的 HTTP 请求，包括认证头、内容类型等。\n5. **响应处理**：服务器响应后，`APIRequestor` 将原始响应包装为 `TogetherResponse` 对象返回。\n6. **结果解析**：资源类将 `TogetherResponse` 中的数据解析为具体的响应模型（如 `ChatCompletionResponse`），返回给用户。\n\n在 `client.py` 中，`Together` 类的初始化逻辑展示了配置参数的优先级处理：\n\n```python\ndef __init__(\n    self,\n    *,\n    api_key: str | None = None,\n    base_url: str | None = None,\n    timeout: float | None = None,\n    max_retries: int | None = None,\n    supplied_headers: Dict[str, str] | None = None,\n) -> None:\n```\n\n配置参数按照以下优先级获取：显式传入的参数 > 环境变量 > 默认值。这种设计既提供了灵活性，又保证了向后兼容性。\n\n### 异步请求流程\n\nTogether SDK 完全支持异步操作，通过 `AsyncTogether` 类提供异步版本的客户端。异步请求在处理大量并发请求时具有显著优势，能够有效利用系统资源并提高吞吐量。\n\n异步请求的核心差异在于 `APIRequestor` 使用 `arequest` 方法而非 `request` 方法。在 `resources/chat/completions.py` 中可以看到异步请求的实现模式：\n\n```python\nresponse, _, _ = await requestor.arequest(\n    options=TogetherRequest(\n        method=\"POST\",\n        url=\"chat/completions\",\n        params=parameter_payload,\n    ),\n    stream=stream,\n)\n```\n\n异步方法返回协程对象，配合 `asyncio` 或 `aiohttp` 等异步框架使用。资源类可以将异步请求封装为异步生成器，便于处理流式响应。流式响应通过异步生成器实现，每次迭代返回一个新的响应块，直到所有数据发送完毕。\n\n```mermaid\nsequenceDiagram\n    participant User as 用户代码\n    participant Client as AsyncTogether\n    participant Resource as 资源类\n    participant Requestor as APIRequestor\n    participant Server as Together API\n    \n    User->>Client: 异步调用\n    Client->>Resource: create()\n    Resource->>Resource: 构建参数\n    Resource->>Requestor: arequest()\n    Requestor->>Server: async HTTP POST\n    Server-->>Requestor: 流式响应\n    loop 流式处理\n        Requestor-->>Resource: 异步生成器\n        Resource-->>User: ChatCompletionChunk\n    end\n```\n\n### 流式响应处理\n\n流式响应是 Together API 的重要特性，特别适用于需要实时展示生成内容的场景，如聊天机器人和代码补全。SDK 对流式响应的处理采用了异步生成器模式，既保证了实时性，又提供了良好的编程接口。\n\n在 `resources/completions.py` 中，流式响应的处理逻辑展示了响应类型的动态判断：\n\n```python\nif stream:\n    # must be an iterator\n    assert not isinstance(response, TogetherResponse)\n    return (CompletionChunk(**line.data) async for line in response)\nassert isinstance(response, TogetherResponse)\nreturn CompletionResponse(**response.data)\n```\n\n当启用流式传输时，响应对象不再是单一的 `TogetherResponse`，而是变成了一个异步迭代器。每次迭代从服务器接收一个数据块，解析为对应的 Chunk 类型（如 `CompletionChunk` 或 `ChatCompletionChunk`）。这种设计允许用户实时处理响应数据，无需等待完整响应生成。\n\n## 抽象层设计\n\n### APIRequestor 职责\n\n`APIRequestor` 是请求流程抽象层的核心组件，负责所有底层的 HTTP 通信逻辑。它封装了认证、请求发送、超时控制、重试机制和错误处理等复杂逻辑，为上层资源类提供简洁统一的接口。\n\n`APIRequestor` 的主要职责包括：\n\n- **认证管理**：自动从环境变量或客户端配置获取 API 密钥，生成符合 Together API 规范的认证头。在 `filemanager.py` 中可以看到认证头的生成方式：`together.utils.get_headers(method, requestor.api_key)`\n- **请求发送**：支持同步的 `request` 方法和异步的 `arequest` 方法，处理不同类型的 HTTP 请求（GET、POST 等）\n- **参数传递**：接收 `TogetherRequest` 对象作为请求配置，包含 URL、HTTP 方法、查询参数、请求体等\n- **响应包装**：将原始 HTTP 响应转换为 `TogetherResponse` 对象，统一响应处理流程\n- **错误转换**：捕获 HTTP 错误和业务错误，转换为合适的异常类型抛出\n\n`APIRequestor` 的设计遵循了**单一职责原则**，将网络通信的复杂性隔离在抽象层内部。上层代码只需关注业务逻辑，无需直接处理 HTTP 协议的细节。这种设计也便于单元测试，因为可以使用 Mock 对象替代真实的网络请求。\n\n### TogetherRequest 配置对象\n\n`TogetherRequest` 是请求配置的数据类，封装了发起 HTTP 请求所需的所有信息。它是连接上层业务逻辑与底层网络通信的桥梁，确保了请求参数的完整性和一致性。\n\n`TogetherRequest` 通常包含以下字段：\n\n| 字段 | 类型 | 描述 |\n|------|------|------|\n| `method` | `str` | HTTP 方法（GET、POST、DELETE 等） |\n| `url` | `str` | API 端点路径 |\n| `params` | `Dict` | 查询参数或请求体数据 |\n| `headers` | `Dict` | 自定义请求头 |\n| `stream` | `bool` | 是否启用流式响应 |\n| `override_headers` | `bool` | 是否覆盖默认头 |\n| `allow_redirects` | `bool` | 是否允许重定向 |\n\n通过使用 `model_dump(exclude_none=True)` 方法，可以方便地将请求配置序列化为字典，去除 `None` 值，保持请求体的简洁。\n\n### TogetherResponse 响应包装\n\n`TogetherResponse` 是对原始 HTTP 响应的封装类，它将底层的响应状态码、响应头和响应体统一包装在一起。这种设计简化了响应数据的访问方式，并提供了类型安全的数据访问接口。\n\n`TogetherResponse` 的主要属性包括：\n\n- **status_code**：HTTP 状态码，用于判断请求是否成功\n- **headers**：响应头信息，包含内容类型、字符编码等元数据\n- **data**：响应体数据，已经过 JSON 解析的字典或列表\n\n在非流式响应场景下，资源类通过 `TogetherResponse.data` 访问响应内容，并使用 Pydantic 模型进行数据验证和解析。这种模式确保了响应数据的结构符合预期，提供了自动的类型转换和验证功能。\n\n## 错误处理机制\n\n### 异常层次结构\n\nTogether SDK 定义了一套完整的异常层次结构，从基类 `TogetherException` 派生出各类具体异常。这种设计允许调用者采用**宽捕获**或**精确捕获**的方式处理错误，既可以捕获所有 Together 相关错误，也可以针对特定错误类型进行处理。\n\n在 `error.py` 中定义的主要异常类型包括：\n\n| 异常类型 | 描述 | 典型场景 |\n|----------|------|----------|\n| `TogetherException` | 基类异常 | 所有异常的父类 |\n| `AuthenticationError` | 认证错误 | API 密钥无效或缺失 |\n| `RateLimitError` | 速率限制错误 | 请求频率超出限制 |\n| `FileTypeError` | 文件类型错误 | 上传了不支持的文件格式 |\n| `APIConnectionError` | 连接错误 | 网络连接失败 |\n| `Timeout` | 超时错误 | 请求超时 |\n| `APIError` | 通用 API 错误 | 服务器返回的错误响应 |\n\n异常类的构造函数接收多种类型的消息参数，包括 `TogetherErrorResponse`（服务器返回的错误响应结构）、`Exception`（原始异常对象）、字符串消息或 `RequestException`。这种灵活性使得错误信息可以来自不同的来源，便于调试和日志记录。\n\n### 错误处理流程\n\n错误处理贯穿整个请求流程，在多个层面进行：\n\n1. **HTTP 层错误捕获**：`APIRequestor` 捕获底层 HTTP 异常（如连接超时、DNS 解析失败等），转换为 `APIConnectionError` 或 `Timeout`。\n2. **HTTP 状态码检查**：响应返回后检查状态码，非 2xx 状态码会触发异常。在 `filemanager.py` 中可以看到：`response.raise_for_status()` 用于触发 HTTP 状态码异常。\n3. **业务错误解析**：Together API 返回的错误响应会解析为结构化的错误信息，便于调用者理解错误原因。\n4. **重试机制**：`APIRequestor` 实现了一定的重试逻辑，对于临时性错误（如 503 Service Unavailable）会自动重试。\n\n```mermaid\ngraph TD\n    A[发起请求] --> B{网络正常?}\n    B -->|否| C[APIConnectionError]\n    B -->|是| D{状态码 2xx?}\n    D -->|否| E{可重试状态码?}\n    D -->|是| F{流式响应?}\n    F -->|否| G[TogetherResponse]\n    F -->|是| H[异步生成器]\n    E -->|是| I[重试请求]\n    E -->|否| J[APIError]\n    I --> A\n```\n\n## 文件管理中的请求流程\n\n文件管理模块展示了请求流程的另一个应用场景，包括文件上传、下载和元数据获取等操作。该模块使用了重定向机制来处理大文件上传，这是标准的 multipart/form-data 上传模式。\n\n### 上传流程\n\n文件上传采用了**重定向模式**：首先向 API 发起初始化请求，获取预签名的上传 URL；然后直接向该 URL 上传文件内容；最后确认上传完成。这种模式可以将大文件上传的负载分散到对象存储服务，减轻 API 服务器的压力。\n\n在 `filemanager.py` 中，`get_upload_url` 方法展示了重定向流程的实现：\n\n```python\nresponse = requestor.request_raw(\n    options=TogetherRequest(\n        method=method,\n        url=url,\n        params=data,\n        allow_redirects=False,\n        override_headers=True,\n        headers=headers,\n    ),\n    remaining_retries=MAX_RETRIES,\n)\n```\n\n设置 `allow_redirects=False` 使得响应返回重定向头而非自动跟随，SDK 可以获取 `Location` 头获取实际的 upload URL 和文件 ID。\n\n### 下载流程\n\n文件下载支持断点续传和并发控制。通过发送 Range 请求获取文件大小信息，然后使用 `FileLock` 防止同一文件的并发下载。下载过程中使用临时文件，写入完成后原子性地重命名，确保文件完整性。\n\n## 参数构建与序列化\n\n资源类在发起请求前，需要将用户友好的参数转换为 API 所需的格式。这一过程包括默认值填充、参数校验、类型转换和序列化。\n\n以聊天补全为例，参数构建在资源类中完成：\n\n```python\nparameter_payload = ChatCompletionCreateParams(\n    model=model,\n    messages=messages,\n    temperature=temperature,\n    max_tokens=max_tokens,\n    top_p=top_p,\n    ...\n).model_dump(exclude_none=True)\n```\n\n使用 Pydantic 的 `model_dump(exclude_none=True)` 方法可以方便地生成 API 兼容的 JSON 字典，自动排除值为 `None` 的可选参数。这种模式既保证了参数的规范性，又提供了灵活的默认值处理。\n\n## 总结\n\nTogether Python SDK 的请求流程与抽象层通过分层设计实现了优雅的架构：主客户端提供统一入口，资源类封装业务逻辑，请求者抽象处理底层通信细节。这种设计既保证了代码的可读性和可维护性，又为扩展新功能提供了清晰的方向。\n\n核心的抽象包括 `APIRequestor` 负责 HTTP 通信、`TogetherRequest` 封装请求配置、`TogetherResponse` 包装响应数据、`TogetherException` 及其子类处理错误。这些组件协同工作，为开发者提供了简洁而强大的 API 调用体验。开发者无需关心网络通信的复杂性，只需关注业务逻辑的实现，通过高层 API 即可完成与 Together 平台的所有交互。\n\n---\n\n<a id='page-chat-completions'></a>\n\n## 聊天补全 API\n\n### 相关页面\n\n相关主题：[文本补全 API](#page-completions), [多模态功能](#page-multimodal)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/chat/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/__init__.py)\n- [src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n- [src/together/types/chat_completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/chat_completions.py)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)\n</details>\n\n# 聊天补全 API\n\n## 概述\n\n聊天补全 API（Chat Completions API）是 together-python 客户端库的核心功能之一，提供与 Together 平台上的大语言模型进行交互的统一接口。该 API 基于 OpenAI 兼容的聊天补全格式，支持文本对话、多模态输入（图像/视频）、流式输出、异步调用以及日志概率获取等高级功能。\n\n在 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)\n\n## 核心组件架构\n\n### 模块依赖关系\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[resources.Chat]\n    B --> C[ChatCompletions 类]\n    C --> D[types/chat_completions.py]\n    C --> E[requestor 请求模块]\n    \n    F[CLI chat 命令] --> C\n```\n\n### 客户端集成\n\n`Together` 类在初始化时自动绑定所有资源端点，包括聊天补全功能：\n\n| 属性 | 类型 | 说明 |\n|------|------|------|\n| `client.chat` | `resources.Chat` | 聊天补全 API 入口 |\n| `client.completions` | `resources.Completions` | 文本补全 API |\n| `client.embeddings` | `resources.Embeddings` | 向量嵌入 API |\n| `client.images` | `resources.Images` | 图像生成 API |\n| `client.fine_tuning` | `resources.FineTuning` | 微调 API |\n\n资料来源：[src/together/client.py:10-22](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n\n## 主要功能特性\n\n### 1. 基础文本对话\n\n聊天补全 API 支持最简单的文本消息交互，使用 `messages` 参数传递对话历史：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n)\nprint(response.choices[0].message.content)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 2. 多模态消息支持\n\nAPI 支持在同一请求中传递多种内容类型，包括文本、图像 URL 和视频 URL：\n\n| 内容类型 | 类型标识 | 用途 |\n|---------|---------|------|\n| 纯文本 | `{\"type\": \"text\", \"text\": \"...\"}` | 普通文本消息 |\n| 图像输入 | `{\"type\": \"image_url\", \"image_url\": {\"url\": \"...\"}}` | 视觉理解任务 |\n| 视频输入 | `{\"type\": \"video_url\", \"video_url\": {\"url\": \"...\"}}` | 视频理解任务 |\n\n#### 带图像的多模态示例\n\n```python\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": \"What's in this image?\"\n            },\n            {\n                \"type\": \"image_url\",\n                \"image_url\": {\n                    \"url\": \"https://huggingface.co/datasets/patrickvonplaten/random_img/resolve/main/yosemite.png\"\n                }\n            }\n        ]\n    }]\n)\n```\n\n#### 带视频的多模态示例\n\n```python\nresponse = client.chat.completions.create(\n    model=\"Qwen/Qwen2.5-VL-72B-Instruct\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": \"What's happening in this video?\"\n            },\n            {\n                \"type\": \"video_url\",\n                \"video_url\": {\n                    \"url\": \"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4\"\n                }\n            }\n        ]\n    }]\n)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 3. 流式输出\n\n启用流式模式后，API 以增量方式返回生成的内容，适合需要实时展示的交互场景：\n\n```python\nstream = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 4. 异步调用\n\n通过 `AsyncTogether` 客户端实现并发请求处理：\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def async_chat_completion(messages):\n    tasks = [\n        async_client.chat.completions.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            messages=[{\"role\": \"user\", \"content\": message}],\n        )\n        for message in messages\n    ]\n    responses = await asyncio.gather(*tasks)\n    return responses\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 5. 日志概率（Logprobs）\n\nLogprobs 功能允许获取 token 级别的生成概率，用于评估模型输出的置信度：\n\n```python\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-3B-Instruct-Turbo\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n    logprobs=1\n)\n```\n\n日志概率的主要应用场景包括：\n\n| 场景 | 说明 |\n|-----|------|\n| 置信度评估 | 判断模型对输出的自信程度 |\n| 低置信度过滤 | 拒绝或重试概率较低的输出 |\n| 模型集成 | 比较不同模型的概率分布 |\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n## API 参数详解\n\n### 核心请求参数\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| `model` | `str` | 必填 | 模型标识符，如 `meta-llama/Llama-4-Scout-17B-16E-Instruct` |\n| `messages` | `List[Dict]` | 必填 | 对话消息列表，每条包含 `role` 和 `content` |\n| `max_tokens` | `int` | `None` | 最大生成 token 数 |\n| `temperature` | `float` | `None` | 采样温度，控制随机性 |\n| `top_p` | `float` | `None` | 核采样概率阈值 |\n| `top_k` | `int` | `None` | Top-K 采样参数 |\n| `stream` | `bool` | `False` | 是否启用流式输出 |\n| `logprobs` | `int` | `None` | 返回 logprobs 的数量 |\n\n资料来源：[src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n\n### 惩罚参数\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `repetition_penalty` | `float` | 重复惩罚系数 |\n| `presence_penalty` | `float` | 存在惩罚（鼓励引入新话题） |\n| `frequency_penalty` | `float` | 频率惩罚（降低高频词出现） |\n| `min_p` | `float` | 最小概率阈值采样 |\n\n资料来源：[src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)\n\n### 高级参数\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `echo` | `bool` | 是否回显输入 prompt |\n| `n` | `int` | 生成数量 |\n| `safety_model` | `str` | 安全审查模型标识 |\n| `response_format` | `dict` | 响应格式约束（如 JSON mode） |\n| `tools` | `List[Dict]` | 可用工具定义列表 |\n| `tool_choice` | `str` | 工具选择策略 |\n| `audio_url` | `List[str]` | 附加到用户消息的音频 URL |\n| `multimodal_params` | `dict` | 多模态额外参数 |\n\n资料来源：[src/together/resources/chat/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/chat/completions.py)\n\n## 请求处理流程\n\n### 同步请求流程\n\n```mermaid\nsequenceDiagram\n    participant Client as Together 客户端\n    participant API as Chat Completions API\n    participant Backend as Together 后端\n    \n    Client->>API: client.chat.completions.create(params)\n    API->>API: 验证参数，构建请求\n    API->>Backend: POST /chat/completions\n    Backend-->>API: 返回 ChatCompletionResponse\n    API-->>Client: 返回最终响应对象\n    \n    Note over API,Backend: stream=True 时\n    API->>Backend: POST /chat/completions (stream=true)\n    Backend-->>API: 流式事件流\n    API-->>Client: 异步生成器 (AsyncGenerator)\n```\n\n### 响应对象结构\n\n```python\nChatCompletionResponse {\n    id: str                    # 请求唯一标识\n    object: str                # 对象类型\n    created: int               # 创建时间戳\n    model: str                 # 实际使用的模型\n    choices: List[Choice]      # 生成结果列表\n    usage: Usage               # Token 使用统计\n}\n\nChoice {\n    index: int                 # 结果索引\n    message: Message           # 完整消息内容\n    logprobs: Logprobs | None  # 日志概率（可选）\n    finish_reason: str         # 结束原因\n}\n```\n\n资料来源：[src/together/types/chat_completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/chat_completions.py)\n\n## CLI 命令行接口\n\n通过 `together` CLI 可以直接调用聊天补全功能：\n\n```bash\ntogether chat.completions \\\n  --message \"What is machine learning?\" \\\n  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \\\n  --max-tokens 512\n```\n\n### CLI 可用选项\n\n| CLI 选项 | 对应参数 | 说明 |\n|---------|---------|------|\n| `--message` | `messages` | 消息内容（可多次指定） |\n| `--model` | `model` | 模型名称 |\n| `--max-tokens` | `max_tokens` | 最大 token 数 |\n| `--stop` | `stop` | 停止序列 |\n| `--temperature` | `temperature` | 采样温度 |\n| `--top-p` | `top_p` | 核采样概率 |\n| `--top-k` | `top_k` | Top-K 采样 |\n| `--no-stream` | `stream=False` | 禁用流式输出 |\n| `--logprobs` | `logprobs` | 返回 logprobs |\n| `--safety-model` | `safety_model` | 安全模型 |\n| `--audio-url` | `audio_url` | 音频 URL |\n\n资料来源：[src/together/cli/api/chat.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/chat.py)\n\n## 完整使用示例\n\n### 示例一：基础聊天\n\n```python\nfrom together import Together\n\nclient = Together(api_key=\"your-api-key\")\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=[\n        {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n        {\"role\": \"user\", \"content\": \"What are the top 3 things to do in San Francisco?\"}\n    ],\n    temperature=0.7,\n    max_tokens=256\n)\n\nprint(response.choices[0].message.content)\n```\n\n### 示例二：多轮对话\n\n```python\nmessages = [\n    {\"role\": \"system\", \"content\": \"You are a Python expert.\"},\n    {\"role\": \"user\", \"content\": \"Explain what a decorator is.\"},\n    {\"role\": \"assistant\", \"content\": \"A decorator in Python is a function that...\"},\n    {\"role\": \"user\", \"content\": \"Give me an example.\"}\n]\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    messages=messages\n)\n```\n\n### 示例三：并发请求\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync def batch_chat():\n    async_client = AsyncTogether()\n    \n    queries = [\n        \"What is AI?\",\n        \"What is ML?\",\n        \"What is DL?\"\n    ]\n    \n    tasks = [\n        async_client.chat.completions.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            messages=[{\"role\": \"user\", \"content\": q}]\n        )\n        for q in queries\n    ]\n    \n    results = await asyncio.gather(*tasks)\n    \n    for i, response in enumerate(results):\n        print(f\"Q{i+1}: {queries[i]}\")\n        print(f\"A{i+1}: {response.choices[0].message.content}\\n\")\n\nasyncio.run(batch_chat())\n```\n\n## 错误处理\n\n聊天补全 API 可能抛出的异常类型定义于 `src/together/error.py`：\n\n| 异常类型 | 说明 |\n|---------|------|\n| `AuthenticationError` | API 密钥无效或缺失 |\n| `RateLimitError` | 请求频率超限 |\n| `APIConnectionError` | 网络连接错误 |\n| `Timeout` | 请求超时 |\n| `TogetherException` | 基础异常类 |\n\n```python\nfrom together import Together\nfrom together.error import RateLimitError, AuthenticationError\n\nclient = Together()\n\ntry:\n    response = client.chat.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        messages=[{\"role\": \"user\", \"content\": \"Hello\"}]\n    )\nexcept AuthenticationError:\n    print(\"请检查 API 密钥是否正确设置\")\nexcept RateLimitError:\n    print(\"请求频率超限，请稍后重试\")\nexcept Exception as e:\n    print(f\"发生错误: {e}\")\n```\n\n资料来源：[src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n## 最佳实践\n\n1. **环境变量配置**：将 API 密钥存储在环境变量 `TOGETHER_API_KEY` 中，避免硬编码\n2. **流式响应处理**：对于长文本生成，使用流式模式提升用户体验\n3. **错误重试**：结合指数退避策略处理临时性网络错误\n4. **资源清理**：异步操作完成后确保正确关闭连接\n5. **多模态优化**：图像输入时使用合理的分辨率以平衡质量和延迟\n\n## 相关资源\n\n- SDK 文档：[Together Python SDK](https://github.com/togethercomputer/together-python)\n- API 平台：[api.together.xyz](https://api.together.xyz/)\n- 模型列表：`together models list` 或 `client.models.list()`\n\n---\n\n<a id='page-completions'></a>\n\n## 文本补全 API\n\n### 相关页面\n\n相关主题：[聊天补全 API](#page-chat-completions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/cli/api/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/completions.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/types/completions.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/completions.py)\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n</details>\n\n# 文本补全 API\n\n## 概述\n\n文本补全 API（Completions API）是 Together Python 客户端库的核心功能之一，提供对大型语言模型文本生成能力的访问。该 API 允许开发者通过简单的接口调用，向 Together 平台上的各种语言模型发送补全请求，并获取生成的文本内容。\n\n## 核心组件架构\n\n文本补全 API 的架构涉及多个协同工作的组件，从客户端入口到最终的 API 请求处理。\n\n```mermaid\ngraph TD\n    A[开发者代码] --> B[Together 客户端实例]\n    B --> C[completions 资源对象]\n    C --> D[Completions.create 方法]\n    D --> E[请求参数构建]\n    E --> F[API 请求发送]\n    F --> G[Together API 服务器]\n    G --> H[CompletionResponse]\n    H --> I[开发者获取结果]\n    \n    style A fill:#e1f5fe\n    style G fill:#fff3e0\n    style I fill:#e8f5e9\n```\n\n### 主要组件说明\n\n| 组件 | 文件位置 | 职责 |\n|------|----------|------|\n| Together 客户端 | `src/together/client.py` | 作为统一的 API 入口点 |\n| Completions 资源 | `src/together/resources/completions.py` | 实现补全功能的核心逻辑 |\n| CLI 命令 | `src/together/cli/api/completions.py` | 命令行接口实现 |\n| 类型定义 | `src/together/types/completions.py` | 请求和响应数据模型 |\n\n## 客户端集成\n\nTogether 主客户端类通过 `completions` 属性集成了文本补全功能。\n\n```python\nclass Together:\n    completions: resources.Completions\n    # ... 其他资源\n```\n\n资料来源：[src/together/client.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n\n### 初始化与认证\n\n客户端支持通过多种方式配置 API 密钥：\n\n```python\nfrom together import Together\n\n# 方式一：通过参数直接传入\nclient = Together(api_key=\"your-api-key\")\n\n# 方式二：通过环境变量自动读取\n# 需要设置 TOGETHER_API_KEY 环境变量\nclient = Together()\n```\n\n## API 方法详解\n\n### 创建补全请求\n\n`completions.create()` 是文本补全 API 的核心方法，支持同步和流式两种模式。\n\n#### 方法签名\n\n```python\nasync def create(\n    self,\n    *,\n    model: str,\n    prompt: str,\n    max_tokens: int | None = None,\n    temperature: float | None = None,\n    top_p: int | None = None,\n    top_k: int | None = None,\n    stop: str | list[str] | None = None,\n    repetition_penalty: float | None = None,\n    presence_penalty: float | None = None,\n    frequency_penalty: float | None = None,\n    min_p: float | None = None,\n    stream: bool = False,\n    logprobs: int | None = None,\n    echo: bool = False,\n    n: int | None = None,\n    safety_model: str | None = None,\n    response_format: dict | None = None,\n    tools: list[dict] | None = None,\n    tool_choice: str | dict | None = None,\n    **kwargs,\n) -> CompletionResponse | AsyncGenerator[CompletionChunk, None]\n```\n\n资料来源：[src/together/resources/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n\n#### 参数说明\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| `model` | str | 必需 | 模型标识符，如 `meta-llama/Llama-4-Scout-17B-16E-Instruct` |\n| `prompt` | str | 必需 | 输入提示文本 |\n| `max_tokens` | int | None | 生成令牌的最大数量 |\n| `temperature` | float | None | 采样温度，控制随机性 |\n| `top_p` | int | None | Nucleus 采样阈值 |\n| `top_k` | float | None | Top-K 采样参数 |\n| `stop` | str \\| list[str] | None | 停止生成的字符串或字符串列表 |\n| `repetition_penalty` | float | None | 重复惩罚系数 |\n| `presence_penalty` | float | None | 存在惩罚系数 |\n| `frequency_penalty` | float | None | 频率惩罚系数 |\n| `min_p` | float | None | 最小概率阈值 |\n| `stream` | bool | False | 是否启用流式输出 |\n| `logprobs` | int | None | 返回的对数概率数量 |\n| `echo` | bool | False | 是否回显输入提示 |\n| `n` | int | None | 生成数量 |\n| `safety_model` | str | None | 安全模型标识 |\n| `response_format` | dict | None | 响应格式规范 |\n| `tools` | list[dict] | None | 可用工具列表 |\n| `tool_choice` | str \\| dict | None | 工具选择策略 |\n\n## 使用模式\n\n### 基础文本补全\n\n最基本的文本补全调用，返回完整的补全结果：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    max_tokens=512,\n)\n\nprint(response.choices[0].text)\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 流式输出\n\n流式模式允许实时获取生成的令牌，适合需要即时反馈的场景：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nstream = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n#### 流式输出流程图\n\n```mermaid\nsequenceDiagram\n    participant 客户端\n    participant API\n    participant 模型\n    \n    客户端->>API: POST /completions (stream=True)\n    API->>模型: 转发请求\n    模型-->>API: 流式令牌 1\n    API-->>客户端: CompletionChunk 1\n    模型-->>API: 流式令牌 2\n    API-->>客户端: CompletionChunk 2\n    模型-->>API: 流式令牌 N\n    API-->>客户端: CompletionChunk N\n    模型-->>API: [DONE]\n    API-->>客户端: 流结束信号\n```\n\n### 异步并发请求\n\n对于需要同时处理多个补全请求的场景，可以使用异步客户端：\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nprompts = [\n    \"Write a Next.js component with TailwindCSS for a header component.\",\n    \"Write a python function for the fibonacci sequence\",\n]\n\nasync def async_completions(prompts):\n    tasks = [\n        async_client.completions.create(\n            model=\"codellama/CodeLlama-34b-Python-hf\",\n            prompt=prompt,\n        )\n        for prompt in prompts\n    ]\n    responses = await asyncio.gather(*tasks)\n\n    for response in responses:\n        print(response.choices[0].text)\n\nasyncio.run(async_completions(prompts))\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n## CLI 命令行接口\n\nTogether CLI 提供了命令行方式的文本补全功能：\n\n```bash\ntogether completions \\\n  \"Large language models are \" \\\n  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \\\n  --max-tokens 512 \\\n  --stop \".\"\n```\n\n资料来源：[README.md:1-100](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### CLI 参数选项\n\n| CLI 选项 | 对应 API 参数 | 说明 |\n|----------|---------------|------|\n| `--model` | model | 模型名称 |\n| `--max-tokens` | max_tokens | 最大令牌数 |\n| `--stop` | stop | 停止序列 |\n| `--temperature` | temperature | 采样温度 |\n| `--top-p` | top_p | Nucleus 采样 |\n| `--top-k` | top_k | Top-K 采样 |\n| `--repetition-penalty` | repetition_penalty | 重复惩罚 |\n| `--presence-penalty` | presence_penalty | 存在惩罚 |\n| `--frequency-penalty` | frequency_penalty | 频率惩罚 |\n| `--no-stream` | stream=False | 禁用流式输出 |\n| `--logprobs` | logprobs | 返回对数概率 |\n| `--echo` | echo | 回显提示 |\n| `--n` | n | 生成数量 |\n| `--safety-model` | safety_model | 安全模型 |\n| `--raw` | - | 输出原始 JSON |\n\n资料来源：[src/together/cli/api/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/completions.py)\n\n## 响应数据结构\n\n### 完整响应\n\n当 `stream=False` 时，返回 `CompletionResponse` 对象：\n\n```python\n@dataclass\nclass CompletionResponse:\n    id: str\n    choices: List[CompletionChoice]\n    model: str\n    usage: CompletionUsage\n    created: int\n    object: str = \"text_completion\"\n```\n\n### 流式响应\n\n当 `stream=True` 时，返回 `CompletionChunk` 对象的异步生成器：\n\n```python\n@dataclass\nclass CompletionChunk:\n    id: str\n    choices: List[CompletionChoicesChunk]\n    model: str\n    created: int\n    object: str = \"text_completion.chunk\"\n```\n\n每个 `CompletionChoicesChunk` 包含 `delta` 字段，其中 `delta.content` 包含新生成的文本片段：\n\n```python\nfor chunk in stream:\n    assert isinstance(chunk, CompletionChunk)\n    if chunk.choices and chunk.choices[0].delta:\n        print(chunk.choices[0].delta.content, end=\"\", flush=True)\n```\n\n资料来源：[src/together/resources/completions.py:1-150](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/completions.py)\n\n## 错误处理\n\n文本补全 API 可能抛出多种异常类型，继承自 `TogetherException` 基类：\n\n```mermaid\ngraph TD\n    A[TogetherException] --> B[RateLimitError]\n    A --> C[AuthenticationError]\n    A --> D[APIConnectionError]\n    A --> E[Timeout]\n    A --> F[InvalidRequestError]\n```\n\n| 异常类型 | 说明 | 处理建议 |\n|----------|------|----------|\n| `RateLimitError` | 请求频率超限 | 实现退避重试机制 |\n| `AuthenticationError` | 认证失败 | 检查 API 密钥配置 |\n| `APIConnectionError` | 网络连接问题 | 检查网络状态 |\n| `Timeout` | 请求超时 | 增加超时时间或重试 |\n| `InvalidRequestError` | 请求参数错误 | 检查参数有效性 |\n\n资料来源：[src/together/error.py:1-100](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n### 错误处理示例\n\n```python\nfrom together import Together\nfrom together.error import RateLimitError, APIConnectionError\n\nclient = Together()\n\ntry:\n    response = client.completions.create(\n        model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n        prompt=\"Hello, world!\",\n    )\nexcept RateLimitError:\n    print(\"请求频率超限，请稍后重试\")\nexcept APIConnectionError:\n    print(\"网络连接失败，请检查网络\")\nexcept Exception as e:\n    print(f\"发生错误: {e}\")\n```\n\n## 最佳实践\n\n### 参数调优建议\n\n| 使用场景 | 推荐参数配置 |\n|----------|--------------|\n| 代码生成 | `temperature=0.2`, `max_tokens=1024` |\n| 创意写作 | `temperature=0.8-1.0`, `top_p=0.95` |\n| 问答系统 | `temperature=0.3`, `max_tokens=256` |\n| 摘要生成 | `temperature=0.3`, `presence_penalty=0.1` |\n\n### 性能优化\n\n1. **使用流式输出**：对于需要实时反馈的场景，启用 `stream=True`\n2. **合理设置 max_tokens**：避免生成过长文本造成不必要的资源消耗\n3. **使用异步客户端**：处理批量请求时使用 `AsyncTogether`\n4. **缓存模型响应**：对于相同提示的重复请求考虑实现缓存机制\n\n### 安全考虑\n\n1. **设置 safety_model**：对敏感内容使用安全模型过滤\n2. **限制输出长度**：通过 `max_tokens` 控制最大生成长度\n3. **使用停止序列**：通过 `stop` 参数避免生成不期望的内容\n\n---\n\n<a id='page-multimodal'></a>\n\n## 多模态功能\n\n### 相关页面\n\n相关主题：[聊天补全 API](#page-chat-completions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/images.py)\n- [src/together/resources/code_interpreter.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/code_interpreter.py)\n- [src/together/resources/videos.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/videos.py)\n- [src/together/resources/audio/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/audio/__init__.py)\n- [src/together/types/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/images.py)\n- [examples/code_interpreter_demo.py](https://github.com/togethercomputer/together-python/blob/main/examples/code_interpreter_demo.py)\n</details>\n\n# 多模态功能\n\nTogether Python SDK 提供了丰富的多模态功能，支持文本、图像、视频和音频等多种模态的数据处理与生成。这些功能通过统一的客户端接口暴露，使开发者能够便捷地调用各种多模态 AI 能力。\n\n## 功能概述\n\nTogether Python SDK 的多模态功能主要包括以下几个模块：\n\n| 模块 | 功能描述 | 主要类/方法 |\n|------|----------|-------------|\n| 图像生成 | 根据文本描述生成图像 | `client.images.generate()` |\n| 聊天多模态 | 支持文本+图像的对话 | `client.chat.completions.create()` |\n| 代码解释器 | 执行多模态代码 | `client.code_interpreter` |\n| 视频生成 | 生成视频内容 | `client.videos` |\n| 音频处理 | 音频相关功能 | `client.audio` |\n\n资料来源：[src/together/client.py:25-38](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n\n## 架构设计\n\n### 客户端架构\n\nTogether SDK 采用模块化架构，各个多模态功能通过独立的资源类实现：\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[chat 聊天模块]\n    A --> C[images 图像模块]\n    A --> D[code_interpreter 代码解释器]\n    A --> E[videos 视频模块]\n    A --> F[audio 音频模块]\n    \n    B --> B1[文本处理]\n    B --> B2[多图像处理]\n    \n    C --> C1[图像生成]\n    C --> C2[参考图像支持]\n```\n\n## 图像生成功能\n\n### 基本用法\n\n图像生成模块允许通过文本提示词生成图像，支持自定义模型、尺寸、步数和数量等参数。\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.images.generate(\n    prompt=\"space robots\",\n    model=\"stabilityai/stable-diffusion-xl-base-1.0\",\n    steps=10,\n    n=4,\n)\nprint(response.data[0].b64_json)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### CLI 使用方式\n\n通过命令行也可以调用图像生成功能：\n\n```bash\ntogether images generate \\\n  \"space robots\" \\\n  --model stabilityai/stable-diffusion-xl-base-1.0 \\\n  --n 4\n```\n\n### 图像生成参数\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| prompt | str | 必需 | 图像生成提示词 |\n| model | str | 必需 | 使用的模型名称 |\n| steps | int | 20 | 生成步数 |\n| seed | int | None | 随机种子，用于复现 |\n| n | int | 1 | 生成图像数量 |\n| height | int | 1024 | 图像高度 |\n| width | int | 1024 | 图像宽度 |\n| negative_prompt | str | None | 负面提示词 |\n| response_format | str | None | 返回格式 |\n\n资料来源：[src/together/resources/images.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/images.py)\n\n### 请求处理流程\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Images\n    participant APIRequestor\n    participant Together API\n    \n    Client->>Images: images.generate(prompt, model, ...)\n    Images->>Images: 构建 ImageRequest\n    Images->>APIRequestor: arequest(POST, images/generations)\n    APIRequestor->>Together API: HTTP POST\n    Together API-->>APIRequestor: ImageResponse\n    APIRequestor-->>Images: TogetherResponse\n    Images-->>Client: ImageResponse\n```\n\n## 聊天多模态功能\n\n### 多模态消息格式\n\n聊天模块支持多模态消息，消息内容可以是纯文本，也可以是包含文本和图像URL的列表结构。\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.chat.completions.create(\n    model=\"meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\n                \"type\": \"text\",\n                \"text\": \"What's in this image?\"\n            },\n            {\n                \"type\": \"image_url\",\n                \"image_url\": {\n                    \"url\": \"https://example.com/image.png\"\n                }\n            }\n        ]\n    }]\n)\nprint(response.choices[0].message.content)\n```\n\n资料来源：[README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n\n### 内容类型验证\n\n系统对多模态内容有严格的验证规则：\n\n| 规则 | 说明 |\n|------|------|\n| 类型限制 | `content` 字段支持字符串或字典列表 |\n| 有效类型 | `text` 和 `image_url` 两种类型 |\n| 图像位置 | 仅用户消息可包含图像 |\n| 图像编码 | 图像必须为 base64 编码 |\n| 大小限制 | base64 编码后小于 10MB |\n| 数量限制 | 每条消息最多 3 张图像 |\n\n资料来源：[src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)\n\n### 数据格式示例\n\n```python\n# 单文本消息\n{\"role\": \"user\", \"content\": \"普通文本消息\"}\n\n# 多模态消息（文本+图像）\n{\n    \"role\": \"user\",\n    \"content\": [\n        {\"type\": \"text\", \"text\": \"描述这张图片\"},\n        {\"type\": \"image_url\", \"image_url\": {\"url\": \"https://...\"}}\n    ]\n}\n```\n\n## 代码解释器\n\n代码解释器模块支持执行包含多模态数据的代码，能够处理图像等多媒体内容。\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.code_interpreter.run(\n    input=\"分析这张图片并返回描述\",\n    images=[base64_image_data],\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n)\nprint(response)\n```\n\n资料来源：[examples/code_interpreter_demo.py](https://github.com/togethercomputer/together-python/blob/main/examples/code_interpreter_demo.py)\n\n## 视频生成功能\n\n视频生成模块提供视频内容创作能力：\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.videos.generate(\n    prompt=\"宇航员在太空站工作\",\n    model=\"some-video-model\",\n    duration=5,\n)\n```\n\n资料来源：[src/together/resources/videos.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/videos.py)\n\n## 音频功能\n\n音频模块支持音频相关的数据处理：\n\n```python\nfrom together import Together\n\nclient = Together()\n\n# 音频相关功能调用\nresponse = client.audio.transcribe(\n    file=\"audio.wav\",\n    model=\"whisper-model\"\n)\n```\n\n资料来源：[src/together/resources/audio/__init__.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/audio/__init__.py)\n\n## 工作流程图\n\n### 多模态请求处理流程\n\n```mermaid\ngraph TD\n    A[开始请求] --> B[验证 API Key]\n    B --> C[构建请求参数]\n    C --> D{请求类型}\n    \n    D -->|图像生成| E[调用 images.generate]\n    D -->|聊天多模态| F[调用 chat.completions.create]\n    D -->|代码解释| G[调用 code_interpreter.run]\n    D -->|视频生成| H[调用 videos.generate]\n    \n    E --> I[POST /images/generations]\n    F --> J[POST /chat/completions]\n    G --> K[POST /code_interpreter]\n    H --> L[POST /videos/generations]\n    \n    I --> M[返回 ImageResponse]\n    J --> N[返回 ChatCompletionResponse]\n    K --> O[返回执行结果]\n    L --> P[返回 VideoResponse]\n    \n    M --> Q[结束]\n    N --> Q\n    O --> Q\n    P --> Q\n```\n\n## 错误处理\n\nSDK 提供了多层次的错误处理机制：\n\n| 错误类型 | 说明 |\n|----------|------|\n| `RateLimitError` | 请求频率超限 |\n| `FileTypeError` | 文件类型不支持 |\n| `Timeout` | 请求超时 |\n| `APIConnectionError` | API 连接错误 |\n| `InvalidFileFormatError` | 文件格式无效 |\n\n资料来源：[src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n\n## 最佳实践\n\n1. **图像大小优化**：在上传图像前进行压缩，避免超过 10MB 限制\n2. **提示词编写**：使用清晰、具体的描述以获得更好的生成效果\n3. **种子使用**：当需要复现结果时，设置固定的 seed 值\n4. **批量处理**：利用 `n` 参数一次性生成多张图像，提高效率\n\n## 总结\n\nTogether Python SDK 的多模态功能提供了统一、便捷的接口来访问各种生成式 AI 能力。通过模块化的设计，开发者可以根据需求灵活调用图像生成、多模态聊天、代码解释器、视频生成和音频处理等功能。所有功能都遵循一致的 API 设计规范，便于集成到各类应用场景中。\n\n---\n\n<a id='page-embeddings-rerank'></a>\n\n## 嵌入与重排序\n\n### 相关页面\n\n相关主题：[文本补全 API](#page-completions)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/togethercomputer/together-python/blob/main/README.md)\n- [src/together/client.py](https://github.com/togethercomputer/together-python/blob/main/src/together/client.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n</details>\n\n# 嵌入与重排序\n\n## 概述\n\n嵌入（Embeddings）与重排序（Reranking）是 Together Python 库中用于增强检索能力的两大核心功能模块。它们共同构成了语义搜索和文档匹配的技术基础，使开发者能够将文本转换为高维向量表示，并通过相关性评分对候选结果进行排序优化。\n\nTogether Python 客户端通过统一的接口封装了这些功能，支持同步和异步两种调用方式，便于集成到各类应用场景中。嵌入功能主要用于将文本转换为稠密向量，而重排序功能则在此基础上对检索结果进行二次优化，提升最终结果的相关性。\n\n## 架构设计\n\n### 客户端集成\n\nTogether 客户端类在初始化时自动配置了嵌入和重排序资源。客户端采用模块化设计，将不同功能封装为独立的资源类，通过统一的方式对外提供服务。\n\n```mermaid\ngraph TD\n    A[Together 客户端] --> B[Embeddings 嵌入模块]\n    A --> C[Rerank 重排序模块]\n    B --> D[向量嵌入生成]\n    C --> E[相关性评分计算]\n    D --> F[语义相似度匹配]\n    E --> G[结果重排序]\n    F --> G\n```\n\n客户端类中声明了以下相关属性，用于支持嵌入和重排序功能：\n\n| 模块 | 类型 | 用途 |\n|------|------|------|\n| embeddings | resources.Embeddings | 文本向量化嵌入生成 |\n| rerank | resources.Rerank | 文档相关性评分与重排序 |\n\n资料来源：[src/together/client.py:18-35]()\n\n### 错误处理机制\n\n嵌入与重排序模块共享统一的异常处理体系。所有自定义异常均继承自 `TogetherException` 基类，确保错误信息的一致性和可追溯性。\n\n| 异常类型 | 适用场景 |\n|----------|----------|\n| TogetherException | 所有异常的基类 |\n| RateLimitError | 请求频率超限时触发 |\n| APIConnectionError | 网络连接异常时触发 |\n| Timeout | 请求超时情况 |\n| FileTypeError | 文件类型不匹配时触发 |\n\n资料来源：[src/together/error.py:1-60]()\n\n## 嵌入功能详解\n\n### 功能概述\n\n嵌入功能将文本转换为固定维度的稠密向量，这种向量表示能够捕捉文本的语义信息。在自然语言处理领域，向量嵌入是语义搜索、文本相似度计算、聚类分析等任务的基础。通过 Together 平台提供的嵌入模型，开发者可以将任意文本转换为可计算的数值向量。\n\n### 使用方式\n\n#### 基础用法\n\n```python\nfrom typing import List\nfrom together import Together\n\nclient = Together()\n\ndef get_embeddings(texts: List[str], model: str) -> List[List[float]]:\n    texts = [text.replace(\"\\n\", \" \") for text in texts]\n    outputs = client.embeddings.create(model=model, input=texts)\n    return [outputs.data[i].embedding for i in range(len(texts))]\n\ninput_texts = ['Our solar system orbits the Milky Way galaxy at about 515,000 mph']\nembeddings = get_embeddings(input_texts, model='togethercomputer/m2-bert-80M-8k-retrieval')\n```\n\n资料来源：[README.md:65-75]()\n\n#### 核心参数说明\n\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| model | str | 是 | 嵌入模型标识符 |\n| input | List[str] | 是 | 待编码的文本列表 |\n\n#### 处理流程\n\n嵌入处理流程包含以下关键步骤：\n\n1. **文本预处理**：移除换行符等特殊字符，确保输入格式统一\n2. **API 调用**：通过 `client.embeddings.create()` 发起请求\n3. **响应解析**：从返回结果中提取 `embedding` 向量数据\n4. **结果返回**：以浮点数列表形式输出向量\n\n### 支持的模型\n\nTogether 平台提供多种嵌入模型，常见选择包括 `togethercomputer/m2-bert-80M-8k-retrieval` 等专门针对检索任务优化的模型。开发者可根据精度、速度和成本需求选择合适的模型。\n\n## 重排序功能详解\n\n### 功能概述\n\n重排序（Reranking）是信息检索领域的重要技术。当初始检索返回多个候选文档后，重排序模型会对这些文档进行相关性评分，并按照评分高低重新排列，从而将最相关的文档优先展示给用户。\n\nTogether 平台集成了高质量的重排序模型（如 Salesforce/Llama-Rank-V1），能够显著提升检索系统的最终效果。重排序通常作为第二阶段处理，位于初步向量检索之后。\n\n### 使用方式\n\n```python\nfrom typing import List\nfrom together import Together\n\nclient = Together()\n\ndef get_reranked_documents(\n    query: str, \n    documents: List[str], \n    model: str, \n    top_n: int = 3\n) -> List[str]:\n    outputs = client.rerank.create(\n        model=model, \n        query=query, \n        documents=documents, \n        top_n=top_n\n    )\n    # sort by relevance score and returns the original docs\n    return [\n        documents[i] \n        for i in [x.index for x in sorted(\n            outputs.results, \n            key=lambda x: x.relevance_score, \n            reverse=True\n        )]\n    ]\n\nquery = \"What is the capital of the United States?\"\ndocuments = [\"New York\", \"Washington, D.C.\", \"Los Angeles\"]\n\nreranked_documents = get_reranked_documents(\n    query, \n    documents, \n    model='Salesforce/Llama-Rank-V1', \n    top_n=1\n)\n```\n\n资料来源：[README.md:80-100]()\n\n#### 核心参数说明\n\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| model | str | 是 | 重排序模型标识符 |\n| query | str | 是 | 查询文本 |\n| documents | List[str] | 是 | 待排序的文档列表 |\n| top_n | int | 否 | 返回的最相关文档数量，默认返回全部 |\n\n#### 返回结果结构\n\n重排序结果包含每个文档的索引位置和相关性评分：\n\n| 字段 | 类型 | 说明 |\n|------|------|------|\n| index | int | 原始文档列表中的位置 |\n| relevance_score | float | 相关性评分，数值越高越相关 |\n\n## 组合工作流\n\n嵌入与重排序通常组合使用，形成完整的检索管道。这种两阶段检索架构能够兼顾召回率和精确率：\n\n```mermaid\ngraph LR\n    A[用户查询] --> B[嵌入阶段]\n    B --> C[向量相似度检索]\n    C --> D[候选文档集]\n    D --> E[重排序阶段]\n    E --> F[最终排序结果]\n    \n    G[文档库] --> H[文档嵌入]\n    H --> C\n```\n\n### 典型应用场景\n\n| 场景 | 嵌入作用 | 重排序作用 |\n|------|----------|------------|\n| 语义搜索 | 将查询和文档转为向量 | 对初步结果进行相关性优化 |\n| 推荐系统 | 用户和物品向量化 | 精细化排序提升推荐准确度 |\n| 问答系统 | 问题与答案片段编码 | 排序最相关的答案片段 |\n\n## 异步调用支持\n\nTogether Python 库同时支持异步调用方式，便于在异步应用框架中集成使用。异步客户端 `AsyncTogether` 提供了与非异步版本相同的接口设计，确保开发体验的一致性。\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def async_rerank_example(query: str, documents: List[str]):\n    results = await async_client.rerank.create(\n        model='Salesforce/Llama-Rank-V1',\n        query=query,\n        documents=documents,\n        top_n=5\n    )\n    return results\n```\n\n## 最佳实践\n\n### 文本预处理\n\n在调用嵌入功能前，建议对输入文本进行标准化处理：\n\n- 移除多余的换行符和空白字符\n- 统一文本编码格式\n- 限制单条文本的最大长度以符合模型要求\n\n### 性能优化建议\n\n| 优化方向 | 具体措施 |\n|----------|----------|\n| 批处理 | 批量提交嵌入请求以减少网络开销 |\n| 缓存 | 对频繁查询的嵌入结果进行缓存 |\n| 模型选择 | 根据精度需求选择合适的模型规格 |\n| top_n 参数 | 仅获取必要的重排序结果数量 |\n\n### 错误处理\n\n集成时应妥善处理各类异常情况：\n\n- 网络异常：实现重试机制\n- 频率限制：遵守 API 调用频率约束\n- 输入验证：确保文档列表非空且格式正确\n\n## 相关资源\n\n更多关于嵌入和重排序的详细文档，请参考 Together 官方文档：\n\n- [嵌入功能概述](https://docs.together.ai/docs/rerank-overview)\n- [微调功能与文件上传](https://docs.together.ai/docs/fine-tuning-python)\n\n资料来源：[README.md:100-102]()\n\n---\n\n<a id='page-files-management'></a>\n\n## 文件管理\n\n### 相关页面\n\n相关主题：[模型微调](#page-finetuning)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/files.py)\n- [src/together/filemanager.py](https://github.com/togethercomputer/together-python/blob/main/src/together/filemanager.py)\n- [src/together/types/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/files.py)\n- [src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)\n</details>\n\n# 文件管理\n\nTogether Python SDK 提供了一套完整的文件管理功能，用于支持模型微调、数据上传、文件检索与删除等操作。该模块是整个 SDK 与 Together AI 平台进行数据交互的重要桥梁。\n\n## 功能概述\n\nTogether AI 的文件管理 API 主要服务于以下核心场景：\n\n1. **微调数据管理**：上传训练数据集以进行模型微调\n2. **文件元数据查询**：查看已上传文件的详细信息\n3. **文件内容检索**：获取已上传文件的具体内容\n4. **存储空间管理**：删除不再需要的文件以释放空间\n\n文件管理模块在整个 SDK 架构中属于基础资源层，被 `FineTuning`（微调）和 `Files`（文件）两个核心资源类所依赖。客户端通过 `Together` 类的 `files` 属性访问这些功能。\n\n```mermaid\ngraph LR\n    A[用户代码] --> B[Together 客户端]\n    B --> C[Files 资源类]\n    C --> D[Together API]\n    D --> E[(远程存储)]\n    \n    F[CLI 命令] --> C\n    G[微调模块] --> C\n```\n\n## 核心组件\n\n### Files 资源类\n\n`Files` 资源类封装了所有与文件操作相关的 API 方法。资料来源：[src/together/resources/files.py]()\n\n| 方法名 | 功能描述 |\n|--------|----------|\n| `upload()` | 上传本地文件到 Together 服务器 |\n| `list()` | 列出当前账户下的所有文件 |\n| `retrieve()` | 获取指定文件的元数据 |\n| `retrieve_content()` | 下载并返回文件内容 |\n| `delete()` | 删除指定文件 |\n\n### 文件类型定义\n\nTogether SDK 使用 `FilePurpose` 枚举定义文件的用途类别。资料来源：[src/together/types/files.py]()\n\n| 枚举值 | 用途说明 |\n|--------|----------|\n| `fine-tunes` | 微调训练数据 |\n| `batch` | 批量处理任务 |\n| `evaluation` | 模型评估数据 |\n\n### 错误处理\n\n文件管理模块定义了专门的异常类用于处理各类错误情况。资料来源：[src/together/error.py]()\n\n| 异常类 | 触发场景 |\n|--------|----------|\n| `FileTypeError` | 文件类型不符合要求 |\n| `InvalidFileFormatError` | 文件格式验证失败 |\n| `APIConnectionError` | API 连接异常 |\n\n## Python API 使用\n\n### 初始化客户端\n\n```python\nfrom together import Together\n\nclient = Together()\n```\n\n### 上传文件\n\n使用 `files.upload()` 方法将本地文件上传至服务器：\n\n```python\nresponse = client.files.upload(\n    file=\"somedata.jsonl\",\n    purpose=\"fine-tunes\"  # 可选，默认为 fine-tunes\n)\n```\n\n上传时系统会自动进行文件格式校验。资料来源：[README.md]() 和 [src/together/utils/files.py]()\n\n### 列出文件\n\n获取账户下所有已上传文件的列表：\n\n```python\nresponse = client.files.list()\n```\n\n返回结果包含每个文件的元数据信息，包括文件名、创建时间、文件大小等。\n\n### 检索文件元数据\n\n通过文件 ID 获取特定文件的详细信息：\n\n```python\nresponse = client.files.retrieve(\n    id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\"\n)\n```\n\n### 获取文件内容\n\n下载并读取已上传文件的实际内容：\n\n```python\ncontent = client.files.retrieve_content(\n    id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\"\n)\n```\n\n### 删除文件\n\n从服务器删除指定文件以释放存储空间：\n\n```python\nclient.files.delete(\n    id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\"\n)\n```\n\n## CLI 命令行接口\n\nTogether SDK 提供了命令行工具用于文件管理操作。资料来源：[src/together/cli/api/files.py]()\n\n### 基本命令结构\n\n```bash\ntogether files <子命令>\n```\n\n### 查看帮助\n\n```bash\ntogether files --help\n```\n\n### 检查文件\n\n在上传前验证本地文件格式是否正确：\n\n```bash\ntogether files check example.jsonl\n```\n\n### 上传文件\n\n将本地文件上传至 Together 服务器：\n\n```bash\ntogether files upload example.jsonl\n```\n\n支持指定文件用途：\n\n```bash\ntogether files upload example.jsonl --purpose fine-tunes\n```\n\n### 列出文件\n\n显示账户下所有已上传文件：\n\n```bash\ntogether files list\n```\n\n### 检索文件元数据\n\n获取特定文件的详细信息：\n\n```bash\ntogether files retrieve file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n```\n\n### 检索文件内容\n\n下载并显示文件内容：\n\n```bash\ntogether files retrieve-content file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n```\n\n### 删除文件\n\n从服务器删除指定文件：\n\n```bash\ntogether files delete file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n```\n\n## 文件格式校验\n\nTogether SDK 在文件上传前会进行严格的格式验证，确保数据符合微调要求。资料来源：[src/together/utils/files.py]()\n\n### JSONL 格式验证\n\n上传的文件必须符合 JSONL（JSON Lines）格式规范：\n\n- 每行必须是有效的 JSON 对象\n- 文件扩展名应为 `.jsonl`\n- 支持单行或多行 JSON 格式\n\n### 多模态内容验证\n\n对于包含多模态内容的文件，系统会进行以下校验：\n\n| 校验项 | 说明 |\n|--------|------|\n| 内容类型 | 必须是 `text` 或 `image_url` |\n| 图片数量 | 每个示例最多包含规定数量的图片 |\n| Base64 长度 | Base64 编码的图片数据需小于 10MB |\n| 角色限制 | 图片只能出现在 `user` 角色的消息中 |\n\n### 错误处理机制\n\n校验失败时会抛出 `InvalidFileFormatError` 异常，包含以下详细信息：\n\n- 错误发生的行号\n- 错误类型标识\n- 具体的错误描述\n\n## 与微调模块的集成\n\n文件管理模块与微调功能紧密集成，是进行模型微调的前置步骤。资料来源：[src/together/resources/finetune.py]()\n\n### 典型工作流程\n\n```mermaid\ngraph TD\n    A[准备训练数据] --> B[上传文件]\n    B --> C[获取 file ID]\n    C --> D[创建微调任务]\n    D --> E[监控训练进度]\n    E --> F[下载微调模型]\n```\n\n### 训练文件引用\n\n在创建微调任务时，通过 `training_file` 参数引用已上传文件的 ID：\n\n```python\nclient.fine_tuning.create(\n    training_file=\"file-xxxxx\",\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\"\n)\n```\n\n## 配置与参数\n\n### 客户端初始化参数\n\n| 参数名 | 类型 | 说明 | 默认值 |\n|--------|------|------|--------|\n| `api_key` | str | API 密钥 | 环境变量 TOGETHER_API_KEY |\n| `base_url` | str | API 基础地址 | 环境变量 TOGETHER_BASE_URL |\n| `timeout` | float | 请求超时时间 | 600 秒 |\n| `max_retries` | int | 最大重试次数 | 2 |\n\n### 文件上传参数\n\n| 参数名 | 类型 | 说明 | 必填 |\n|--------|------|------|------|\n| `file` | str/Path | 本地文件路径 | 是 |\n| `purpose` | str | 文件用途 | 否 |\n| `check` | bool | 是否校验文件格式 | 否（默认 True） |\n\n## 最佳实践\n\n### 数据准备\n\n1. **文件格式**：使用标准 JSONL 格式，每行一个 JSON 对象\n2. **数据清洗**：确保数据编码为 UTF-8，避免特殊字符问题\n3. **文件大小**：建议单个文件不超过 100MB\n\n### 上传策略\n\n1. **预校验**：使用 `check` 参数在上传说进行格式验证\n2. **分批处理**：大量数据建议分批上传\n3. **错误处理**：捕获并处理 `InvalidFileFormatError` 异常\n\n### 存储管理\n\n1. **定期清理**：删除已完成微调的临时文件\n2. **命名规范**：使用有意义的文件名便于识别\n3. **记录追踪**：保存 file ID 以便后续引用\n\n## 相关资源\n\n- [微调文档](https://docs.together.ai/docs/fine-tuning-python)\n- [Together API 文档](https://docs.together.ai/reference)\n- [GitHub 仓库](https://github.com/togethercomputer/together-python)\n\n---\n\n<a id='page-finetuning'></a>\n\n## 模型微调\n\n### 相关页面\n\n相关主题：[文件管理](#page-files-management)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/together/resources/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)\n- [src/together/cli/api/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)\n- [src/together/utils/files.py](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)\n- [src/together/error.py](https://github.com/togethercomputer/together-python/blob/main/src/together/error.py)\n- [src/together/types/finetune.py](https://github.com/togethercomputer/together-python/blob/main/src/together/types/finetune.py)\n</details>\n\n# 模型微调\n\n## 概述\n\n模型微调（Fine-Tuning）是 Together Python SDK 中用于自定义预训练语言模型行为的核心功能模块。通过微调，用户可以使用自己的数据集对 Together 平台上托管的预训练模型进行定制化训练，使其更好地适应特定任务场景，如特定领域的问答、代码生成、内容分类等。\n\nTogether SDK 提供了完整的微调工作流支持，涵盖从训练任务提交、检查点管理到模型部署的全生命周期管理。\n\n---\n\n## 核心组件\n\n### 主要类和方法\n\n| 组件 | 位置 | 说明 |\n|------|------|------|\n| `FineTuning` | `src/together/resources/finetune.py` | 微调核心资源类，提供所有微调相关操作 |\n| `_parse_raw_checkpoints` | `src/together/resources/finetune.py:78-97` | 解析检查点元数据的辅助函数 |\n| `FinetuneCheckpoint` | `src/together/types/finetune.py` | 检查点数据模型 |\n\n### 异常处理体系\n\n微调过程中可能遇到的异常类型定义于 `src/together/error.py`：\n\n| 异常类 | 说明 | 触发场景 |\n|--------|------|----------|\n| `TogetherException` | 基异常类 | 通用错误 |\n| `RateLimitError` | 速率限制错误 | API 请求频率超限 |\n| `FileTypeError` | 文件类型错误 | 上传文件格式不支持 |\n| `APIConnectionError` | 连接错误 | 无法建立 API 连接 |\n| `Timeout` | 超时错误 | 请求响应超时 |\n\n---\n\n## 微调参数配置\n\n### 基础训练参数\n\n```python\nfrom together import Together\n\nclient = Together()\n\nresponse = client.fine_tuning.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    training_file=\"file-xxx\",\n    validation_file=\"file-yyy\",\n    n_epochs=3,\n    batch_size=4,\n    learning_rate=1e-5,\n    n_checkpoints=1\n)\n```\n\n### 完整参数表\n\n| 参数名 | 类型 | 默认值 | 说明 |\n|--------|------|--------|------|\n| `model` | `str` | 必填 | 基础模型名称 |\n| `training_file` | `str` | 必填 | 训练数据文件 ID |\n| `validation_file` | `str` | 可选 | 验证数据文件 ID |\n| `n_epochs` | `int` | - | 训练轮数 |\n| `n_evals` | `int` | - | 评估频率 |\n| `n_checkpoints` | `int` | - | 保存的检查点数量 |\n| `batch_size` | `int` | - | 批处理大小 |\n| `learning_rate` | `float` | - | 学习率 |\n| `lr_scheduler_type` | `str` | - | 学习率调度器类型 |\n| `min_lr_ratio` | `float` | - | 最小学习率比例 |\n| `scheduler_num_cycles` | `int` | - | 调度器循环次数 |\n| `warmup_ratio` | `float` | - | 预热比例 |\n| `max_grad_norm` | `float` | - | 梯度裁剪最大值 |\n| `weight_decay` | `float` | - | 权重衰减系数 |\n| `suffix` | `str` | - | 输出模型名称后缀 |\n\n*资料来源：[src/together/resources/finetune.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## LoRA 微调配置\n\nTogether SDK 支持 Low-Rank Adaptation（LoRA）高效微调方法，显著降低训练参数量和计算成本。\n\n### LoRA 相关参数\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `lora` | `bool` | 是否启用 LoRA |\n| `lora_r` | `int` | LoRA 秩（rank） |\n| `lora_dropout` | `float` | LoRA dropout 率 |\n| `lora_alpha` | `float` | LoRA alpha 值 |\n| `lora_trainable_modules` | `str` | 可训练的模块名称 |\n\n### 配置示例\n\n```python\nresponse = client.fine_tuning.create(\n    model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n    training_file=\"file-xxx\",\n    lora=True,\n    lora_r=8,\n    lora_alpha=16,\n    lora_dropout=0.05\n)\n```\n\n*资料来源：[src/together/resources/finetune.py:30-35](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## 高级训练配置\n\n### DPO/RLHF 训练\n\nTogether 支持直接偏好优化（DPO）和相关强化学习方法：\n\n| 参数名 | 说明 |\n|--------|------|\n| `training_method` | 训练方法（标准/DPO/SimPO/RPO 等） |\n| `dpo_beta` | DPO 的 beta 参数 |\n| `dpo_normalize_logratios_by_length` | 是否按长度归一化 |\n| `rpo_alpha` | RPO alpha 参数 |\n| `simpo_gamma` | SimPO gamma 参数 |\n\n### 多模态训练\n\n| 参数名 | 类型 | 说明 |\n|--------|------|------|\n| `train_vision` | `bool` | 是否训练视觉编码器 |\n| `multimodal_params` | `dict` | 多模态相关参数 |\n\n### Weights & Biases 集成\n\n| 参数名 | 说明 |\n|--------|------|\n| `wandb_api_key` | W&B API 密钥 |\n| `wandb_base_url` | W&B 基础 URL |\n| `wandb_project_name` | W&B 项目名称 |\n| `wandb_name` | W&B 运行名称 |\n\n### 其他高级参数\n\n| 参数名 | 说明 |\n|--------|------|\n| `train_on_inputs` | 是否在输入上训练（支持 auto 自动判断） |\n| `from_checkpoint` | 从指定检查点继续训练 |\n| `from_hf_model` | 从 Hugging Face 模型开始训练 |\n| `hf_model_revision` | Hugging Face 模型版本 |\n| `hf_api_token` | Hugging Face API 令牌 |\n| `hf_output_repo_name` | Hugging Face 输出仓库名称 |\n\n*资料来源：[src/together/resources/finetune.py:36-56](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## 检查点管理\n\n### 检查点解析机制\n\n`_parse_raw_checkpoints` 函数负责解析服务器返回的检查点元数据：\n\n```python\ndef _parse_raw_checkpoints(\n    checkpoints: List[Dict[str, str]], id: str\n) -> List[FinetuneCheckpoint]:\n    parsed_checkpoints = []\n    for checkpoint in checkpoints:\n        step = checkpoint[\"step\"]\n        checkpoint_type = checkpoint[\"checkpoint_type\"]\n        checkpoint_name = (\n            f\"{id}:{step}\" if \"intermediate\" in checkpoint_type.lower() else id\n        )\n\n        parsed_checkpoints.append(\n            FinetuneCheckpoint(\n                type=checkpoint_type,\n                timestamp=checkpoint[\"created_at\"],\n                name=checkpoint_name,\n            )\n        )\n\n    parsed_checkpoints.sort(key=lambda x: x.timestamp, reverse=True)\n    return parsed_checkpoints\n```\n\n检查点按时间戳降序排列，最新的检查点排在前面。\n\n*资料来源：[src/together/resources/finetune.py:78-97](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n### 检查点类型\n\n| 类型 | 说明 | 适用场景 |\n|------|------|----------|\n| `default` | 默认检查点 | 标准训练 |\n| `intermediate` | 中间检查点 | 定期保存 |\n| `merged` | 合并检查点 | LoRA 适配器与基础模型合并 |\n| `adapter` | 适配器检查点 | 仅 LoRA 权重 |\n\n---\n\n## CLI 微调命令\n\nTogether CLI 提供了完整的微调命令行接口。\n\n### 查看帮助\n\n```bash\ntogether fine-tuning --help\n```\n\n### 下载微调检查点\n\n```bash\ntogether fine-tuning download <FINE_TUNE_ID> \\\n  --output_dir ./checkpoints \\\n  --checkpoint-step 1000 \\\n  --checkpoint-type merged\n```\n\n| CLI 参数 | 说明 |\n|----------|------|\n| `--output_dir` / `-o` | 输出目录路径 |\n| `--checkpoint-step` / `-s` | 检查点步数（默认最新） |\n| `--checkpoint-type` | 检查点类型 |\n\n*资料来源：[src/together/cli/api/finetune.py:1-50](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)*\n\n### 删除微调任务\n\n```bash\ntogether fine-tuning delete <FINE_TUNE_ID> --force\n```\n\n| CLI 参数 | 说明 |\n|----------|------|\n| `--force` | 强制删除，无需确认 |\n| `--quiet` / `-y` | 静默模式，不提示确认 |\n\n*资料来源：[src/together/cli/api/finetune.py:60-80](https://github.com/togethercomputer/together-python/blob/main/src/together/cli/api/finetune.py)*\n\n---\n\n## 数据格式验证\n\nTogether SDK 在 `src/together/utils/files.py` 中实现了严格的数据格式验证机制。\n\n### 支持的数据格式\n\n微调数据必须符合特定的 JSON 格式要求：\n\n1. **文本消息**\n```json\n{\n  \"type\": \"text\",\n  \"text\": \"用户输入内容\"\n}\n```\n\n2. **多模态消息**（仅支持用户角色）\n```json\n{\n  \"type\": \"image_url\",\n  \"image_url\": {\n    \"url\": \"https://...\"\n  }\n}\n```\n\n### 验证规则\n\n| 规则 | 错误类型 | 说明 |\n|------|----------|------|\n| 内容必须为 dict | `InvalidFileFormatError` | JSON 结构错误 |\n| 必须包含 `type` 字段 | `InvalidFileFormatError` | 缺少类型标识 |\n| 文本内容必须为字符串 | `InvalidFileFormatError` | 文本格式错误 |\n| 图片仅限用户消息 | `InvalidFileFormatError` | 角色限制 |\n| 图片 URL 必须为字典 | `InvalidFileFormatError` | URL 格式错误 |\n| Base64 图片最大 10MB | `InvalidFileFormatError` | 文件过大 |\n| 每条消息最多 10 张图片 | `InvalidFileFormatError` | 图片数量超限 |\n\n*资料来源：[src/together/utils/files.py:1-80](https://github.com/togethercomputer/together-python/blob/main/src/together/utils/files.py)*\n\n---\n\n## 价格估算机制\n\n在提交微调任务前，SDK 会自动进行价格估算：\n\n```python\nif from_checkpoint is None and from_hf_model is None:\n    price_estimation_result = self.estimate_price(\n        training_file=training_file,\n        validation_file=validation_file,\n        model=model_name,\n        n_epochs=finetune_request.n_epochs,\n        n_evals=finetune_request.n_evals,\n        training_type=\"lora\" if lora else \"full\",\n        training_method=training_method,\n    )\n    price_limit_passed = price_estimation_result.allowed_to_proceed\nelse:\n    price_limit_passed = True\n```\n\n价格估算基于以下因素：\n- 训练文件大小\n- 验证文件大小\n- 模型类型\n- 训练轮数\n- 评估次数\n- 训练类型（全量/LoRA）\n- 训练方法\n\n*资料来源：[src/together/resources/finetune.py:60-73](https://github.com/togethercomputer/together-python/blob/main/src/together/resources/finetune.py)*\n\n---\n\n## 异步操作支持\n\nTogether SDK 提供异步客户端用于并发微调任务管理：\n\n```python\nimport asyncio\nfrom together import AsyncTogether\n\nasync_client = AsyncTogether()\n\nasync def fine_tune_multiple():\n    tasks = [\n        async_client.fine_tuning.create(\n            model=\"meta-llama/Llama-4-Scout-17B-16E-Instruct\",\n            training_file=file_id,\n        )\n        for file_id in training_files\n    ]\n    results = await asyncio.gather(*tasks)\n```\n\n---\n\n## 工作流程图\n\n```mermaid\ngraph TD\n    A[准备训练数据] --> B[上传数据文件]\n    B --> C{选择训练方式}\n    C -->|全量微调| D[设置基础参数]\n    C -->|LoRA| E[配置 LoRA 参数]\n    C -->|DPO/SimPO| F[配置强化学习参数]\n    D --> G[价格估算]\n    E --> G\n    F --> G\n    G --> H{价格限制检查}\n    H -->|通过| I[提交训练任务]\n    H -->|超出| J[调整参数或确认]\n    J --> G\n    I --> K[监控训练进度]\n    K --> L[生成检查点]\n    L --> M{训练完成?}\n    M -->|否| K\n    M -->|是| N[下载最终模型]\n    N --> O[部署使用]\n```\n\n---\n\n## 最佳实践\n\n### 1. 数据准备\n- 确保训练数据格式正确，参考数据格式验证章节\n- 使用验证集监控训练效果\n- 数据量建议不少于 1000 条样本\n\n### 2. 参数选择\n- 首次尝试使用默认参数\n- LoRA 微调时，`lora_r` 通常设置在 8-16 之间\n- 学习率建议从 1e-5 开始，逐步调整\n\n### 3. 检查点管理\n- 设置合理的 `n_checkpoints` 值\n- 定期保存中间检查点便于恢复\n- 使用 `--checkpoint-type merged` 获取可直接部署的模型\n\n### 4. 成本控制\n- 充分利用价格估算功能\n- 从检查点继续训练可节省成本\n- 使用 `wandb` 监控训练过程\n\n---\n\n## 错误处理\n\n微调过程中可能遇到的常见错误及解决方案：\n\n| 错误类型 | 可能原因 | 解决方案 |\n|----------|----------|----------|\n| `FileTypeError` | 数据文件格式不支持 | 确保文件为 JSONL 格式 |\n| `RateLimitError` | API 请求过于频繁 | 降低请求频率 |\n| `Timeout` | 训练任务超时 | 减少训练数据量或轮数 |\n| `APIConnectionError` | 网络连接问题 | 检查网络设置和 API 密钥 |\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：togethercomputer/together-python\n\n摘要：发现 12 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。\n\n## 1. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作: 假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:624113979 | https://github.com/togethercomputer/together-python | README/documentation is current enough for a first validation pass.\n\n## 2. 运行坑 · 来源证据：v.1.5.31\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.31\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ec69ff431b15448799cc64a826efd011 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. 运行坑 · 来源证据：v.1.5.33\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.33\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8246897bffc548df9673fe0c390cb514 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. 运行坑 · 来源证据：v1.5.28\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v1.5.28\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7e7977d7006e43939b5ceb03d0efad33 | https://github.com/togethercomputer/together-python/releases/tag/v1.5.28 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. 维护坑 · 来源证据：v.1.5.29\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v.1.5.29\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e91b0421f8fe42ac815a709d90dcca27 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 维护坑 · 来源证据：v1.5.27\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v1.5.27\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_569e5bacb3584ae794141c49af91c5db | https://github.com/togethercomputer/together-python/releases/tag/v1.5.27 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作: 维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | last_activity_observed missing\n\n## 8. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作: 下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n\n## 9. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作: 评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 来源证据：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4b91e5a8164f4aa9910f3d9737f1995c | https://github.com/togethercomputer/together-python/issues/443 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作: issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | issue_or_pr_quality=unknown\n\n## 12. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | release_recency=unknown\n\n<!-- canonical_name: togethercomputer/together-python; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：togethercomputer/together-python\n\n摘要：发现 12 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。\n\n## 1. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作: 假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:624113979 | https://github.com/togethercomputer/together-python | README/documentation is current enough for a first validation pass.\n\n## 2. 运行坑 · 来源证据：v.1.5.31\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.31\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ec69ff431b15448799cc64a826efd011 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.31 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. 运行坑 · 来源证据：v.1.5.33\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v.1.5.33\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8246897bffc548df9673fe0c390cb514 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.33 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. 运行坑 · 来源证据：v1.5.28\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v1.5.28\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7e7977d7006e43939b5ceb03d0efad33 | https://github.com/togethercomputer/together-python/releases/tag/v1.5.28 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. 维护坑 · 来源证据：v.1.5.29\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v.1.5.29\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e91b0421f8fe42ac815a709d90dcca27 | https://github.com/togethercomputer/together-python/releases/tag/v.1.5.29 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 维护坑 · 来源证据：v1.5.27\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v1.5.27\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_569e5bacb3584ae794141c49af91c5db | https://github.com/togethercomputer/together-python/releases/tag/v1.5.27 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作: 维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | last_activity_observed missing\n\n## 8. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作: 下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n\n## 9. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作: 评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:624113979 | https://github.com/togethercomputer/together-python | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 来源证据：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：`LogProbs.top_logprobs` typed as `Dict` but API returns `List[Dict]`\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4b91e5a8164f4aa9910f3d9737f1995c | https://github.com/togethercomputer/together-python/issues/443 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作: issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | issue_or_pr_quality=unknown\n\n## 12. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:624113979 | https://github.com/togethercomputer/together-python | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# together-python - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 together-python 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的软件开发与交付任务。\n我常用的宿主 AI：Local CLI\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 示例引导, 判断线索。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- 安装前能力预览: <div align=\"center\"> 输入：用户任务, 当前 AI 对话上下文；输出：示例引导, 判断线索。\n\n【必须安装后才可验证的能力】\n- 命令行启动或安装流程: 项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 输入：终端环境, 包管理器, 项目依赖；输出：安装结果, 列表/更新/运行结果。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. page-introduction：项目介绍。围绕“项目介绍”模拟一次用户任务，不展示安装或运行结果。\n2. page-installation：安装与配置。围绕“安装与配置”模拟一次用户任务，不展示安装或运行结果。\n3. page-client-architecture：客户端架构。围绕“客户端架构”模拟一次用户任务，不展示安装或运行结果。\n4. page-chat-completions：聊天补全 API。围绕“聊天补全 API”模拟一次用户任务，不展示安装或运行结果。\n5. page-completions：文本补全 API。围绕“文本补全 API”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. page-introduction\n输入：用户提供的“项目介绍”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. page-installation\n输入：用户提供的“安装与配置”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. page-client-architecture\n输入：用户提供的“客户端架构”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. page-chat-completions\n输入：用户提供的“聊天补全 API”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. page-completions\n输入：用户提供的“文本补全 API”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / page-introduction：Step 1 必须围绕“项目介绍”形成一个小中间产物，并等待用户确认。\n- Step 2 / page-installation：Step 2 必须围绕“安装与配置”形成一个小中间产物，并等待用户确认。\n- Step 3 / page-client-architecture：Step 3 必须围绕“客户端架构”形成一个小中间产物，并等待用户确认。\n- Step 4 / page-chat-completions：Step 4 必须围绕“聊天补全 API”形成一个小中间产物，并等待用户确认。\n- Step 5 / page-completions：Step 5 必须围绕“文本补全 API”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n- 涉及安装、插件加载、工具调用或外部服务的能力必须安装后验证。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/togethercomputer/together-python\n- https://github.com/togethercomputer/together-python#readme\n- README.md\n- src/together/__init__.py\n- src/together/version.py\n- pyproject.toml\n- src/together/constants.py\n- src/together/client.py\n- src/together/abstract/api_requestor.py\n- src/together/together_response.py\n- src/together/resources/__init__.py\n- src/together/resources/chat/__init__.py\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 together-python 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：togethercomputer/together-python\n\n## 官方安装入口\n\n### Python / pip · 官方安装入口\n\n```bash\npip install --upgrade together\n```\n\n来源：https://github.com/togethercomputer/together-python#readme\n\n## 来源\n\n- repo: https://github.com/togethercomputer/together-python\n- docs: https://github.com/togethercomputer/together-python#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_31d14fc791254a9b98e59b395f9c91c3"
}
