Haystack 集成指南:使用 AIMLAPIChatGenerator 统一调用多供应商生成式模型
Haystack 集成指南使用 AIMLAPIChatGenerator 统一调用多供应商生成式模型【免费下载链接】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本篇技术指南围绕 Haystack 的 AIMLAPI 集成组件AIMLAPIChatGenerator展开讲解如何通过 AIMLAPI 这一统一 API 网关在 Haystack 管道中接入来自不同供应商OpenAI、Anthropic 等的生成式模型。读完本文你将掌握该组件的初始化参数、鉴权方式、结构化输出、工具调用Function Calling、流式输出、多模态输入以及如何将其放入 Pipeline 和 Agent 中构建生产级 LLM 应用。AIMLAPI 集成概览AIMLAPIChatGenerator是 Haystack 官方维护的 AIMLAPI 集成组件位于haystack_integrations.components.generators.aimlapi.chat.chat_generator模块其类定义直接继承自 Haystack 核心的OpenAIChatGenerator对应源码见 haystack/components/generators/chat/openai.py。它通过 AIMLAPI 的 chat completion 端点启用文本生成能力允许你在同一个 Pipeline 中使用来自不同提供商的模型而保持完全一致的接口。该组件在设计上有三个核心特征主兼容性Primary Compatibility与 AIMLAPI 的 chat completion 端点无缝对接流式支持Streaming Support支持从 AIMLAPI chat completion 端点流式接收响应高度可定制Customizability支持 AIMLAPI chat completion 端点支持的全部参数。组件输入输出统一使用 Haystack 的ChatMessage数据格式保证聊天式文本生成场景中消息上下文连贯、语义相关。ChatMessage是 Haystack 中表示 LLM 消息的核心抽象包含角色user、assistant、system、tool等与可选元数据详细说明可参考 ChatMessage 文档。AIMLAPI 的核心价值在于一个 API Key 即可访问所有提供商的模型你可以在不同模型之间随意切换或组合而无需分别管理多套凭证。例如你可以在一个 Pipeline 中同时使用anthropic/claude-3-5-sonnet处理复杂推理任务用openai/gpt-5-chat-latest处理简单任务。安装与最小示例AIMLAPIChatGenerator位于独立的aimlapi-haystack集成包中使用前需要先安装pip install aimlapi-haystack安装完成后即可像使用其他 Haystack 组件一样直接实例化并运行。参考 AIMLAPI 集成参考文档 中的最小示例from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator from haystack.dataclasses import ChatMessage messages [ChatMessage.from_user(Whats Natural Language Processing?)] client AIMLAPIChatGenerator(modelopenai/gpt-5-chat-latest) response client.run(messages) print(response)输出结果是一个包含replies键的字典每个回复都是一个携带完整元数据的ChatMessage实例{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: openai/gpt-5-chat-latest, index: 0, finish_reason: stop, usage: {prompt_tokens: 15, completion_tokens: 36, total_tokens: 51}})]}可以看到ChatMessage._meta中记录了模型名、结果索引、finish_reason以及 token 用量统计prompt_tokens、completion_tokens、total_tokens便于后续做成本核算与观测。从底层实现看这些元数据由OpenAIChatGenerator在转换 API 响应时写入——核心源码 openai.py 中的_convert_chat_completion_to_chat_message会把completion.model、choice.index、choice.finish_reason、completion.usage逐项组装进meta。初始化参数详解AIMLAPIChatGenerator.__init__的完整签名如下__init__( *, api_key: Secret Secret.from_env_var(AIMLAPI_API_KEY), model: str openai/gpt-5-chat-latest, streaming_callback: StreamingCallbackT | None None, api_base_url: str | None https://api.aimlapi.com/v1, generation_kwargs: dict[str, Any] | None None, tools: ToolsType | None None, timeout: float | None None, extra_headers: dict[str, Any] | None None, max_retries: int | None None, http_client_kwargs: dict[str, Any] | None None ) - None各参数说明如下参数类型说明api_keySecretAIMLAPI API Key。默认从AIMLAPI_API_KEY环境变量读取modelstr使用的 AIMLAPI chat completion 模型名默认openai/gpt-5-chat-lateststreaming_callbackStreamingCallbackT \| None流式回调函数收到新的 token 时被调用回调接收StreamingChunk作为参数api_base_urlstr \| NoneAIMLAPI API 基础地址默认https://api.aimlapi.com/v1generation_kwargsdict[str, Any] \| None其他生成参数全部直接透传给 AIMLAPI 端点toolsToolsType \| None供模型准备调用的工具列表或Toolset实例timeoutfloat \| NoneAIMLAPI API 调用的超时时间extra_headersdict[str, Any] \| None附加到请求中的 HTTP 头max_retriesint \| None内部错误后重试 AIMLAPI 的最大次数未设置时读取AIMLAPI_MAX_RETRIES环境变量默认 5http_client_kwargsdict[str, Any] \| None配置自定义httpx.Client或httpx.AsyncClient的关键字参数字典鉴权Authentication组件需要一个 AIMLAPI API Key 才能工作有两种配置方式环境变量方式推荐设置AIMLAPI_API_KEY环境变量组件默认会通过Secret.from_env_var(AIMLAPI_API_KEY)读取初始化参数方式在api_key参数中显式传入Secret遵循 Haystack 的 Secret 管理规范。生成参数 generation_kwargsgeneration_kwargs是组件灵活性的核心任何对 AIMLAPI chat completion API 合法的文本生成参数都可以直接传入。参考文档明确列出的常用参数包括max_tokens输出文本可包含的最大 token 数temperature采样温度。值越大模型越冒险0.9 适合创意型应用0argmax 采样适合有明确答案的任务top_p核采样nucleus sampling的替代方案。模型只考虑累积概率质量达到top_p的 token例如 0.1 表示只考虑概率质量前 10% 的 tokenstream是否流式返回部分进度。开启后 token 以>from pydantic import BaseModel from haystack.dataclasses import ChatMessage from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator class CityInfo(BaseModel): city_name: str country: str population: int famous_for: str client AIMLAPIChatGenerator( modelopenai/gpt-4o-2024-08-06, generation_kwargs{response_format: CityInfo} ) response client.run( messages[ ChatMessage.from_user( Berlin is the capital and largest city of Germany with a population of approximately 3.7 million. Its famous for its history, culture, and nightlife. ) ] ) print(response[replies][0].text) # {city_name:Berlin,country:Germany,population:3700000, # famous_for:history, culture, and nightlife}底层机制上基类OpenAIChatGenerator在序列化与发起请求时会做两件事见 openai.py 与 openai.py若response_format是 Pydantic 模型BaseModel子类会调用 OpenAI SDK 的to_strict_json_schema将其转换为严格的 JSON Schemastrict: True再随请求发出非流式场景下自动走chat.completions.parse端点流式场景下走create端点并把response_format一并传入。需要注意模型兼容性结构化输出能力取决于底层模型。OpenAI 从gpt-4o-2024-08-06起的模型支持 Pydantic 模型与 JSON Schema具体哪些模型支持该特性请查阅对应模型提供商的文档。工具调用与 ToolsetAIMLAPIChatGenerator通过tools参数支持 Function Calling该参数接受灵活的工具配置Tool 对象列表将单个工具作为列表传入单个 Toolset直接传入一个完整的ToolsetTool 与 Toolset 混用在同一个列表中组合多个 Toolset 与独立工具。from haystack.tools import Tool, Toolset from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator # Create individual tools weather_tool Tool( nameweather, descriptionGet weather info, parameters..., function... ) news_tool Tool( namenews, descriptionGet latest news, parameters..., function... ) # Group related tools into a toolset math_toolset Toolset([add_tool, subtract_tool, multiply_tool]) # Pass mixed tools and toolsets to the generator generator AIMLAPIChatGenerator( tools[math_toolset, weather_tool, news_tool] # Mix of Toolset and Tool objects )这种设计让你可以把相关工具组织成逻辑分组Toolset同时按需混入独立工具。关于Tool与Toolset的完整用法分别参见 Tool 文档 与 Toolset 文档。从源码角度看基类在初始化时会调用_check_duplicate_tool_names检查扁平化后的工具名是否重复openai.py在_prepare_api_call中tools运行时传入优先否则用初始化值会通过flatten_tools_or_toolsets扁平化再转换成 OpenAI 风格的{type: function, function: ...}定义列表openai.py。此外工具会在warm_up/warm_up_async阶段被预热warm_up_tools以保证首次调用时的性能。流式输出AIMLAPIChatGenerator支持将 LLM 的 token 直接流式输出。只需在初始化时传入一个streaming_callback回调函数from haystack.components.generators.utils import print_streaming_chunk from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator # Configure the generator with a streaming callback component AIMLAPIChatGenerator(streaming_callbackprint_streaming_chunk) # Pass a list of messages from haystack.dataclasses import ChatMessage component.run([ChatMessage.from_user(Your question here)])内置的print_streaming_chunk定义于 haystack/components/generators/utils.py会直接向 stdout 输出流式内容并且能够同时打印文本 token 与工具事件工具调用及工具结果输出时自动 flush 保证实时显示。默认情况下优先使用print_streaming_chunk只有在需要特定传输方式如 SSE/WebSocket或自定义 UI 格式化时才建议编写自定义回调。关于StreamingChunk的工作原理与自定义回调写法可参考 Haystack 的流式支持文档。需要注意一个限制流式只支持单个响应。如果提供商支持返回多个候选必须设置n1——这一点与基类中流式 n1 抛 ValueError的实现约束一致openai.py。多模态输入得益于ChatMessage对多模态内容的支持AIMLAPIChatGenerator也可以直接处理图像输入。选择多模态模型后将ImageContent作为消息内容的一部分传入即可from haystack.dataclasses import ChatMessage, ImageContent from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator # Use a multimodal model llm AIMLAPIChatGenerator(modelopenai/gpt-4o) image ImageContent.from_file_path(apple.jpg, detaillow) user_message ChatMessage.from_user( content_parts[What does the image show? Max 5 words., image] ) response llm.run([user_message])[replies][0].text print(response) # Red apple on straw.ImageContent支持从文件路径或 base64 构造detail参数可设为auto、high或low用于控制图像解析的精细度详见 ChatMessage 文档。图像会被编码进消息内容后通过 AIMLAPI 端点发送给底层多模态模型。在 Pipeline 中使用AIMLAPIChatGenerator在管道中最常见的位置是 ChatPromptBuilder 之后将构建好的消息列表通过prompt_builder.prompt连接到llm.messages。下面是一个典型的 RAG 式聊天管道from haystack.components.builders import ChatPromptBuilder from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator from haystack.dataclasses import ChatMessage from haystack import Pipeline # No parameter init, we dont use any runtime template variables prompt_builder ChatPromptBuilder() llm AIMLAPIChatGenerator() pipe Pipeline() pipe.add_component(prompt_builder, prompt_builder) pipe.add_component(llm, llm) pipe.connect(prompt_builder.prompt, llm.messages) location Berlin messages [ ChatMessage.from_system( Always respond in German even if some input data is in other languages. ), ChatMessage.from_user(Tell me about {{location}}), ] pipe.run( data{ prompt_builder: { template_variables: {location: location}, template: messages, } } )由于 AIMLAPI 用统一接口承载多个提供商的模型你可以在同一个 Pipeline 中混用不同模型为不同任务分配合适的模型from haystack.components.builders import ChatPromptBuilder from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator from haystack.dataclasses import ChatMessage from haystack import Pipeline # Create a pipeline that uses different models for different tasks prompt_builder ChatPromptBuilder() # Use one model for complex reasoning reasoning_llm AIMLAPIChatGenerator(modelanthropic/claude-3-5-sonnet) # Use another model for simple tasks simple_llm AIMLAPIChatGenerator(modelopenai/gpt-5-chat-latest) pipe Pipeline() pipe.add_component(prompt_builder, prompt_builder) pipe.add_component(reasoning, reasoning_llm) pipe.add_component(simple, simple_llm) # Feed the same prompt to both models pipe.connect(prompt_builder.prompt, reasoning.messages) pipe.connect(prompt_builder.prompt, simple.messages) messages [ChatMessage.from_user(Explain quantum computing in simple terms.)] result pipe.run(data{prompt_builder: {template: messages}}) print(Reasoning model:, result[reasoning][replies][0].text) print(Simple model:, result[simple][replies][0].text)与 Agent 结合AIMLAPIChatGenerator的工具调用能力可以无缝接入 Haystack 的 Agent由 Agent 负责完整的工具调用循环模型生成工具调用 → 执行工具 → 将结果回填 → 继续生成from haystack.components.agents import Agent from haystack.dataclasses import ChatMessage from haystack.tools import Tool from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator def weather(city: str) - str: Get weather for a given city. return fThe weather in {city} is sunny and 32°C tool Tool( nameweather, descriptionGet weather for a given city, parameters{ type: object, properties: {city: {type: string}}, required: [city], }, functionweather, ) agent Agent(chat_generatorAIMLAPIChatGenerator(), tools[tool]) result agent.run( messages[ChatMessage.from_user(Whats the weather like in Paris?)] ) print(result[last_message].text) # The weather in Paris is sunny and 32°C.这里只需把AIMLAPIChatGenerator实例传给Agent的chat_generator参数工具调用、消息循环、最终回答生成全部由 Agent 编排完成。序列化支持与其他 Haystack 组件一样AIMLAPIChatGenerator提供to_dict()方法to_dict() - dict[str, Any]它将组件序列化为字典返回的dict[str, Any]即组件的序列化表示。从基类实现看openai.py序列化过程中会保留model、generation_kwargs、api_base_url、tools经serialize_tools_or_toolset处理、streaming_callback经serialize_callable处理等关键配置特别地response_format若为 Pydantic 模型会先被转换为 JSON Schema 再存入字典。序列化结果可配合 Haystack 的 Pipeline 序列化机制YAML/JSON实现组件的持久化与共享例如导出到haystack.yaml后通过Pipeline.load恢复。总结与实践建议AIMLAPIChatGenerator把 AIMLAPI 的多模型网关能力完整封装进 Haystack 组件体系让你以单一 API Key、单一组件接口访问多个提供商的生成模型。实践中的关键要点模型选择默认模型为openai/gpt-5-chat-latest可通过model参数随时切换如anthropic/claude-3-5-sonnet、openai/gpt-4o等具体支持的模型清单以 AIMLAPI 官方文档为准鉴权优先用环境变量设置AIMLAPI_API_KEY避免在代码或配置中硬编码密钥参数透传所有 AIMLAPI chat completion 参数均可通过generation_kwargs传入运行时与初始化参数按 key 合并、运行时优先流式注意n1开启streaming_callback时如需多候选务必先设置n1否则基类会直接抛出异常结构化输出看模型response_format传 Pydantic 模型或 JSON Schema但能否生效取决于底层模型是否支持网络可靠性timeout、max_retries默认回退AIMLAPI_MAX_RETRIES再回退 5、extra_headers、http_client_kwargs可按需精细调优。更多关于该组件的关键信息管道位置、必填参数、输入输出变量可参考组件的 用户指南完整 API 参考见 integrations-api/aimlapi.md其基类实现细节可进一步阅读 haystack/components/generators/chat/openai.py。【免费下载链接】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),仅供参考