Haystack 集成 Together AI:TogetherAIChatGenerator 与 TogetherAIGenerator 实战指南
【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack
Together AI 提供 OpenAI 兼容的托管推理 API,可一键调用 Llama、DeepSeek 等开源模型。Haystack 通过togetherai-haystack集成包提供TogetherAIChatGenerator与TogetherAIGenerator两个生成器组件,分别面向多轮对话与单轮文本生成场景。本文基于仓库中的 Together AI API 参考文档 与配套的 TogetherAIChatGenerator 使用指南、TogetherAIGenerator 使用指南,并结合 Haystack 核心源码,系统讲解两个组件的继承关系、完整参数、生成参数调优、流式输出、工具调用与 Pipeline 集成方式,帮助你快速构建基于 Together AI 的 RAG 与对话应用。
组件概览:两个生成器的定位与继承关系
Together AI 集成包含两个组件,它们都位于haystack_integrations.components.generators.togetherai模块下:
| 组件 | 输入 | 输出 | 典型位置 | 继承关系 |
|---|---|---|---|---|
TogetherAIChatGenerator | messages(ChatMessage列表) | replies(ChatMessage列表) | ChatPromptBuilder 之后 | 继承自 Haystack 核心的OpenAIChatGenerator |
TogetherAIGenerator | prompt(字符串) | replies(字符串列表)+meta(元数据字典列表) | PromptBuilder 之后 | 继承自TogetherAIChatGenerator |
从 API 参考文档的类声明可以确认这条继承链:TogetherAIChatGenerator的 Bases 是OpenAIChatGenerator,TogetherAIGenerator的 Bases 是TogetherAIChatGenerator。由于 Together AI 提供了与 OpenAI 兼容的/v1端点,TogetherAIChatGenerator直接复用了 Haystack 核心组件 OpenAIChatGenerator 的实现,只需将默认api_base_url指向https://api.together.xyz/v1即可;TogetherAIGenerator则在对话生成器之上做了一层“非对话式”包装:内部把用户输入的prompt字符串转换为ChatMessage后调用底层对话 API,并把返回的ChatMessage拆解成纯文本replies与元数据meta。
使用这两个组件的前提是:拥有一个活跃的 Together AI 账号(账户内有足够额度)并取得 API Key。Key 有两种提供方式:
- 推荐:设置
TOGETHER_API_KEY环境变量; - 或通过
api_key初始化参数配合 Haystack 的 Secret API(例如Secret.from_token("your-api-key-here"))显式传入。
默认模型为meta-llama/Llama-3.3-70B-Instruct-Turbo,完整的受支持模型列表以 Together AI 官方文档为准。
安装与最小可用示例
TogetherAIChatGenerator与TogetherAIGenerator位于独立的集成包中,需要先安装:
pip install togetherai-haystack安装后即可单独使用。先看对话场景的最小示例(对应 API 参考文档中的 Usage example):
from haystack_integrations.components.generators.togetherai import TogetherAIChatGenerator from haystack.dataclasses import ChatMessage messages = [ChatMessage.from_user("What's Natural Language Processing?")] client = TogetherAIChatGenerator() response = client.run(messages) print(response) >> {'replies': [ChatMessage(_content='Natural Language Processing (NLP) is a branch of artificial intelligence >> that focuses on enabling computers to understand, interpret, and generate human language in a way that is >> meaningful and useful.', _role=<ChatRole.ASSISTANT: 'assistant'>, _name=None, >> _meta={'model': 'meta-llama/Llama-3.3-70B-Instruct-Turbo', 'index': 0, 'finish_reason': 'stop', >> 'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})]}TogetherAIChatGenerator的输入输出统一使用 Haystack 的ChatMessage数据类(定义于 haystack/dataclasses/chat_message.py)。ChatMessage封装了消息内容、角色(user/assistant/system/function/tool等)以及可选元数据,保证多轮对话中消息历史的上下文连贯性。每次生成的响应元数据中包含模型名(model)、结果索引(index)、结束原因(finish_reason)以及 token 用量统计(usage)。
再看纯文本生成场景的最小示例:
from haystack_integrations.components.generators.togetherai import TogetherAIGenerator generator = TogetherAIGenerator(model="deepseek-ai/DeepSeek-R1", generation_kwargs={ "temperature": 0.9, }) print(generator.run("Who is the best Italian actor?"))TogetherAIGenerator的输出为字典,包含两个键:
replies:生成的文本字符串列表;meta:与每个回复对应的元数据字典列表,包含模型名、结束原因与 token 用量统计。
TogetherAIChatGenerator:完整初始化参数详解
TogetherAIChatGenerator.__init__的完整签名(仅关键字参数)如下:
__init__( *, api_key: Secret = Secret.from_env_var("TOGETHER_API_KEY"), model: str = "meta-llama/Llama-3.3-70B-Instruct-Turbo", streaming_callback: StreamingCallbackT | None = None, api_base_url: str | None = "https://api.together.xyz/v1", generation_kwargs: dict[str, Any] | None = None, tools: ToolsType | None = None, timeout: float | None = None, max_retries: int | None = None, http_client_kwargs: dict[str, Any] | None = None ) -> None各参数说明如下:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
api_key | Secret | Secret.from_env_var("TOGETHER_API_KEY") | Together AI API Key,推荐通过环境变量注入 |
model | str | meta-llama/Llama-3.3-70B-Instruct-Turbo | 要使用的 Together AI 对话补全模型名 |
streaming_callback | StreamingCallbackT \| None | None | 流式回调函数,每个新 token 到达时被调用,接收一个StreamingChunk参数 |
api_base_url | str \| None | https://api.together.xyz/v1 | Together AI API 基础地址,可覆盖(如代理场景) |
generation_kwargs | dict[str, Any] \| None | None | 直接透传给 Together AI 端点的其他生成参数,见下文专项说明 |
tools | ToolsType \| None | None | 供模型准备调用的Tool与/或Toolset对象列表,或单个Toolset;每个工具名须唯一 |
timeout | float \| None | None | Together AI API 调用超时时间 |
max_retries | int \| None | None | 遇到内部错误时重试 Together AI 的最大次数;未设置时回退到OPENAI_MAX_RETRIES环境变量,再否则为 5 |
http_client_kwargs | dict[str, Any] \| None | None | 用于配置自定义httpx.Client/httpx.AsyncClient的关键字参数字典 |
其中timeout与max_retries的默认值推导逻辑与核心OpenAIChatGenerator完全一致——可以对照 openai.py 中的_client_kwargs实现 确认:timeout未设置时读取OPENAI_TIMEOUT环境变量,缺省 30 秒;max_retries未设置时读取OPENAI_MAX_RETRIES环境变量,缺省 5 次。
工具调用(Function Calling)
TogetherAIChatGenerator通过tools参数支持函数调用,且接受灵活的配置形态:
- Tool 对象列表:逐个传入独立工具;
- 单个 Toolset:直接传入一整个工具集;
- 混合传入:在同一个列表中混用多个 Toolset 与独立 Tool。
这样既可以把相关工具按逻辑分组(Toolset),又能按需加入零散工具。示例:
from haystack.tools import Tool, Toolset from haystack_integrations.components.generators.togetherai import TogetherAIChatGenerator # 创建独立工具 weather_tool = Tool(name="weather", description="Get weather info", ...) news_tool = Tool(name="news", description="Get latest news", ...) # 将相关工具归入一个 toolset math_toolset = Toolset([add_tool, subtract_tool, multiply_tool]) # 混合传入 toolset 与独立工具 generator = TogetherAIChatGenerator( tools=[math_toolset, weather_tool, news_tool] # Toolset 与 Tool 的混合列表 )关于Tool与Toolset的详细定义可参考 haystack/tools/tool.py 与 haystack/tools/toolset.py。从源码看,核心OpenAIChatGenerator在初始化时会通过_check_duplicate_tool_names校验工具名唯一性,并在warm_up阶段调用warm_up_tools预加载工具元数据,这些机制同样作用于TogetherAIChatGenerator。
流式输出(Streaming)
组件支持流式响应:将可调用对象传给streaming_callback参数即可在 token 生成时实时获取输出。回调函数接收StreamingChunk(见 haystack/dataclasses/streaming_chunk.py),你可以访问其content字段取得当前增量文本:
from haystack.dataclasses import ChatMessage from haystack_integrations.components.generators.togetherai import ( TogetherAIChatGenerator, ) client = TogetherAIChatGenerator( model="meta-llama/Llama-3.3-70B-Instruct-Turbo", streaming_callback=lambda chunk: print(chunk.content, end="", flush=True), ) response = client.run([ChatMessage.from_user("What are Agentic Pipelines? Be brief.")]) # 查看本次响应实际使用的模型 print("\n\nModel used:", response["replies"][0].meta.get("model"))TogetherAIGenerator:面向纯文本生成的包装组件
TogetherAIGenerator面向“给定提示词、返回文本”的经典生成场景,其__init__签名如下:
__init__( api_key: Secret = Secret.from_env_var("TOGETHER_API_KEY"), model: str = "meta-llama/Llama-3.3-70B-Instruct-Turbo", api_base_url: str | None = "https://api.together.xyz/v1", streaming_callback: StreamingCallbackT | None = None, system_prompt: str | None = None, generation_kwargs: dict[str, Any] | None = None, timeout: float | None = None, max_retries: int | None = None, ) -> None与TogetherAIChatGenerator相比,多出system_prompt参数:用于设定生成时的系统提示词(提供上下文或行为指令)。如果未提供,则省略系统提示词,模型将使用自身的默认系统提示词。
run 与 run_async:同步与异步生成
run方法用于同步文本生成:
run( *, prompt: str, system_prompt: str | None = None, streaming_callback: StreamingCallbackT | None = None, generation_kwargs: dict[str, Any] | None = None ) -> dict[str, Any]参数要点:
prompt(必填):用于文本生成的输入提示词字符串;system_prompt:可选的系统提示词,若提供则覆盖__init__中设定的值;streaming_callback:若提供,覆盖__init__中的回调;generation_kwargs:本次运行附加的生成参数,会覆盖__init__中传入的同名参数,支持的参数包括temperature、max_new_tokens、top_p等。
run_async提供完全等价的异步版本,签名与语义一致,适合在异步 Pipeline 或asyncio环境中调用:
run_async( *, prompt: str, system_prompt: str | None = None, streaming_callback: StreamingCallbackT | None = None, generation_kwargs: dict[str, Any] | None = None ) -> dict[str, Any]两者返回结构相同:replies为生成的文本字符串列表,meta为对应的元数据字典列表(含模型名、结束原因、token 用量等)。
带系统提示词的完整示例:
from haystack_integrations.components.generators.togetherai import TogetherAIGenerator client = TogetherAIGenerator( model="meta-llama/Llama-3.3-70B-Instruct-Turbo", system_prompt="You are a helpful assistant that provides concise answers.", ) response = client.run("What's Natural Language Processing?") print(response["replies"][0])注意:
TogetherAIGenerator面向文本生成而非对话。若需要在多轮聊天场景中使用 Together AI 模型,应使用TogetherAIChatGenerator。
generation_kwargs:透传 Together AI 端点的生成参数
generation_kwargs是两组件共用的核心调优入口:所有键值对都会被原样发送到 Together AI 的 chat completion 端点。你可以在__init__中设定全局默认值,也可以在run/run_async中按次覆盖。API 参考文档列出的常用参数如下:
| 参数 | 说明 |
|---|---|
max_tokens | 输出文本的最大 token 数上限 |
temperature | 采样温度。值越高模型越“冒险”:0.9 适合创意型任务,0(argmax 采样)适合有明确答案的任务 |
top_p | 核采样(nucleus sampling)替代温度采样:模型只考虑累积概率质量达到top_p的 token。例如0.1表示只考虑概率质量前 10% 的 token |
n | 每个提示词生成的补全数量。例如 3 个提示词且n=2时,共生成 6 个补全 |
stop | 一个或多个停止序列,模型遇到后停止生成 token |
stream | 是否流式返回部分进度。开启后 token 以>from haystack import Pipeline from haystack.components.builders import ChatPromptBuilder from haystack.dataclasses import ChatMessage from haystack_integrations.components.generators.togetherai import ( TogetherAIChatGenerator, ) prompt_builder = ChatPromptBuilder() llm = TogetherAIChatGenerator(model="meta-llama/Llama-3.3-70B-Instruct-Turbo") pipe = Pipeline() pipe.add_component("builder", prompt_builder) pipe.add_component("llm", llm) pipe.connect("builder.prompt", "llm.messages") messages = [ ChatMessage.from_system("Give brief answers."), ChatMessage.from_user("Tell me about {{city}}"), ] response = pipe.run( data={"builder": {"template": messages, "template_variables": {"city": "Berlin"}}}, ) print(response)RAG 管线:BM25Retriever + PromptBuilder + TogetherAIGenerator
序列化:与 Pipeline YAML 的互操作两个组件都实现了标准的 Haystack 序列化接口:
底层原理:基于 OpenAI 兼容协议的实现理解 Together AI 集成只需抓住一个关键事实:Together AI 提供与 OpenAI 兼容的 API(OpenAI API Compatibility),因此集成组件直接建立在 Haystack 核心的
对开发者而言,这意味着:任何对 小结Together AI 集成以极低的接入成本为 Haystack 应用带来了开源模型的托管推理能力: 【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems. 创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考 |