Haystack 集成 Together AI:TogetherAIChatGenerator 与 TogetherAIGenerator 实战指南
2026/9/15 22:29:41 网站建设 项目流程

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集成包提供TogetherAIChatGeneratorTogetherAIGenerator两个生成器组件,分别面向多轮对话与单轮文本生成场景。本文基于仓库中的 Together AI API 参考文档 与配套的 TogetherAIChatGenerator 使用指南、TogetherAIGenerator 使用指南,并结合 Haystack 核心源码,系统讲解两个组件的继承关系、完整参数、生成参数调优、流式输出、工具调用与 Pipeline 集成方式,帮助你快速构建基于 Together AI 的 RAG 与对话应用。

组件概览:两个生成器的定位与继承关系

Together AI 集成包含两个组件,它们都位于haystack_integrations.components.generators.togetherai模块下:

组件输入输出典型位置继承关系
TogetherAIChatGeneratormessagesChatMessage列表)repliesChatMessage列表)ChatPromptBuilder 之后继承自 Haystack 核心的OpenAIChatGenerator
TogetherAIGeneratorprompt(字符串)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 官方文档为准。

安装与最小可用示例

TogetherAIChatGeneratorTogetherAIGenerator位于独立的集成包中,需要先安装:

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_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环境变量,再否则为 5
http_client_kwargsdict[str, Any] \| NoneNone用于配置自定义httpx.Client/httpx.AsyncClient的关键字参数字典

其中timeoutmax_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 的混合列表 )

关于ToolToolset的详细定义可参考 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__中传入的同名参数,支持的参数包括temperaturemax_new_tokenstop_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

TogetherAIGenerator最常见的位置是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(content="Rome is the capital of Italy"), Document(content="Paris 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_store=docstore)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component("llm", TogetherAIGenerator(model="meta-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 或 JSON;
  • TogetherAIGenerator.from_dict(data: dict[str, Any]) -> TogetherAIGenerator:从字典反序列化重建组件实例(TogetherAIChatGenerator同样支持反序列化)。

TogetherAIChatGenerator的 API 参考中给出了to_dict的签名;TogetherAIGenerator则同时列出to_dictfrom_dict。这意味着你可以把包含 Together AI 生成器的 Pipeline 完整地序列化到配置文件、在团队间共享或在服务启动时加载,与 Haystack 的 Pipeline 序列化机制 无缝协作。

底层原理:基于 OpenAI 兼容协议的实现

理解 Together AI 集成只需抓住一个关键事实:Together AI 提供与 OpenAI 兼容的 API(OpenAI API Compatibility),因此集成组件直接建立在 Haystack 核心的OpenAIChatGenerator之上(haystack/components/generators/chat/openai.py)。可以从源码确认以下几点:

  • 客户端构建OpenAIChatGeneratorwarm_up方法会构造OpenAI同步客户端、warm_up_async构造AsyncOpenAI异步客户端,base_urlapi_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),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询