Haystack 集成 Together AI:TogetherAIChatGenerator 与 TogetherAIGenerator 实战指南

发布时间:2026/9/15 22:29:52
Haystack 集成 Together AI:TogetherAIChatGenerator 与 TogetherAIGenerator 实战指南 Haystack 集成 Together AITogetherAIChatGenerator 与 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/haystackTogether 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模块下组件输入输出典型位置继承关系TogetherAIChatGeneratormessagesChatMessage列表repliesChatMessage列表ChatPromptBuilder 之后继承自 Haystack 核心的OpenAIChatGeneratorTogetherAIGeneratorprompt字符串replies字符串列表meta元数据字典列表PromptBuilder 之后继承自TogetherAIChatGenerator从 API 参考文档的类声明可以确认这条继承链TogetherAIChatGenerator的 Bases 是OpenAIChatGeneratorTogetherAIGenerator的 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 examplefrom haystack_integrations.components.generators.togetherai import TogetherAIChatGenerator from haystack.dataclasses import ChatMessage messages [ChatMessage.from_user(Whats Natural Language Processing?)] client TogetherAIChatGenerator() response client.run(messages) print(response) {replies: [ChatMessage(_contentNatural 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., _roleChatRole.ASSISTANT: assistant, _nameNone, _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(modeldeepseek-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_keySecretSecret.from_env_var(TOGETHER_API_KEY)Together AI API Key推荐通过环境变量注入modelstrmeta-llama/Llama-3.3-70B-Instruct-Turbo要使用的 Together AI 对话补全模型名streaming_callbackStreamingCallbackT \| NoneNone流式回调函数每个新 token 到达时被调用接收一个StreamingChunk参数api_base_urlstr \| Nonehttps://api.together.xyz/v1Together AI API 基础地址可覆盖如代理场景generation_kwargsdict[str, Any] \| NoneNone直接透传给 Together AI 端点的其他生成参数见下文专项说明toolsToolsType \| NoneNone供模型准备调用的Tool与/或Toolset对象列表或单个Toolset每个工具名须唯一timeoutfloat \| NoneNoneTogether AI API 调用超时时间max_retriesint \| NoneNone遇到内部错误时重试 Together AI 的最大次数未设置时回退到OPENAI_MAX_RETRIES环境变量再否则为 5http_client_kwargsdict[str, Any] \| NoneNone用于配置自定义httpx.Client/httpx.AsyncClient的关键字参数字典其中timeout与max_retries的默认值推导逻辑与核心OpenAIChatGenerator完全一致——可以对照 openai.py 中的_client_kwargs实现 确认timeout未设置时读取OPENAI_TIMEOUT环境变量缺省 30 秒max_retries未设置时读取OPENAI_MAX_RETRIES环境变量缺省 5 次。工具调用Function CallingTogetherAIChatGenerator通过tools参数支持函数调用且接受灵活的配置形态Tool 对象列表逐个传入独立工具单个 Toolset直接传入一整个工具集混合传入在同一个列表中混用多个 Toolset 与独立 Tool。这样既可以把相关工具按逻辑分组Toolset又能按需加入零散工具。示例from haystack.tools import Tool, Toolset from haystack_integrations.components.generators.togetherai import TogetherAIChatGenerator # 创建独立工具 weather_tool Tool(nameweather, descriptionGet weather info, ...) news_tool Tool(namenews, descriptionGet 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( modelmeta-llama/Llama-3.3-70B-Instruct-Turbo, streaming_callbacklambda chunk: print(chunk.content, end, flushTrue), ) 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( modelmeta-llama/Llama-3.3-70B-Instruct-Turbo, system_promptYou are a helpful assistant that provides concise answers., ) response client.run(Whats 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 适合创意型任务0argmax 采样适合有明确答案的任务top_p核采样nucleus sampling替代温度采样模型只考虑累积概率质量达到top_p的 token。例如0.1表示只考虑概率质量前 10% 的 tokenn每个提示词生成的补全数量。例如 3 个提示词且n2时共生成 6 个补全stop一个或多个停止序列模型遇到后停止生成 tokenstream是否流式返回部分进度。开启后 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(modelmeta-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 TogetherAIGeneratorTogetherAIGenerator最常见的位置是PromptBuilder之后。下面是一个完整的检索增强生成RAG示例先由InMemoryBM25Retriever检索文档再由PromptBuilder组装上下文最后由 Together AI 模型生成答案from haystack import Pipeline, Document from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.components.builders.prompt_builder import PromptBuilder from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.generators.togetherai import TogetherAIGenerator docstore InMemoryDocumentStore() docstore.write_documents([ Document(contentRome is the capital of Italy), Document(contentParis is the capital of France) ]) query What is the capital of France? template Given the following information, answer the question. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }}? pipe Pipeline() pipe.add_component(retriever, InMemoryBM25Retriever(document_storedocstore)) pipe.add_component(prompt_builder, PromptBuilder(templatetemplate)) pipe.add_component(llm, TogetherAIGenerator(modelmeta-llama/Llama-3.3-70B-Instruct-Turbo)) pipe.connect(retriever, prompt_builder.documents) pipe.connect(prompt_builder, llm) result pipe.run({ prompt_builder: {query: query}, retriever: {query: query} }) print(result) {llm: {replies: [The capital of France is Paris.], meta: [{model: meta-llama/Llama-3.3-70B-Instruct-Turbo, ...}]}}序列化与 Pipeline YAML 的互操作两个组件都实现了标准的 Haystack 序列化接口to_dict() - dict[str, Any]将组件序列化为字典便于保存为 Pipeline YAML 或 JSONTogetherAIGenerator.from_dict(data: dict[str, Any]) - TogetherAIGenerator从字典反序列化重建组件实例TogetherAIChatGenerator同样支持反序列化。TogetherAIChatGenerator的 API 参考中给出了to_dict的签名TogetherAIGenerator则同时列出to_dict与from_dict。这意味着你可以把包含 Together AI 生成器的 Pipeline 完整地序列化到配置文件、在团队间共享或在服务启动时加载与 Haystack 的 Pipeline 序列化机制 无缝协作。底层原理基于 OpenAI 兼容协议的实现理解 Together AI 集成只需抓住一个关键事实Together AI 提供与 OpenAI 兼容的 APIOpenAI API Compatibility因此集成组件直接建立在 Haystack 核心的OpenAIChatGenerator之上haystack/components/generators/chat/openai.py。可以从源码确认以下几点客户端构建OpenAIChatGenerator的warm_up方法会构造OpenAI同步客户端、warm_up_async构造AsyncOpenAI异步客户端base_url由api_base_url注入——这正是TogetherAIChatGenerator默认指向https://api.together.xyz/v1的原因超时与重试_client_kwargs中的timeout/max_retries在未显式指定时分别读取OPENAI_TIMEOUT缺省 30.0与OPENAI_MAX_RETRIES缺省 5环境变量HTTP 客户端定制http_client_kwargs经由 haystack/utils/http_client.py 的init_http_client构造自定义httpx客户端用于代理、证书或连接池等高级场景消息流转换流式响应最终由_convert_streaming_chunks_to_chat_message等工具函数见 haystack/components/generators/utils聚合成完整的ChatMessage。对开发者而言这意味着任何对OpenAIChatGenerator生效的调用约定与调优经验参数语义、超时重试、工具调用都可以平滑迁移到 Together AI 集成组件上唯一需要改变的是api_key、默认模型与api_base_url。小结Together AI 集成以极低的接入成本为 Haystack 应用带来了开源模型的托管推理能力TogetherAIChatGenerator负责多轮对话支持工具调用与流式输出TogetherAIGenerator负责纯文本生成支持系统提示词与同步/异步调用两者都支持通过generation_kwargs全面调优生成行为并可无缝嵌入 Haystack 的检索增强与 Agent Pipeline。实践中的关键步骤可以归纳为四点安装togetherai-haystack并配置TOGETHER_API_KEY按场景选择对话或文本生成组件用generation_kwargs控制温度、top_p、惩罚系数与结构化输出最后将组件接入Pipeline实现端到端应用。更多模型列表与 API 细节建议以 Together AI 官方文档为最终依据。【免费下载链接】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创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考