
llama-index-llms-you 集成指南在 LlamaIndex 中使用 You.com Smart 与 Research 对话 API【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index本指南围绕 API 参考文档 docs/api_reference/api_reference/llms/you.md 所指向的llama_index.llms.you模块系统讲解 You.com 对话式 LLM 集成包的安装、配置、两种工作模式、完整调用与流式输出并结合 base.py 源码剖析其底层请求与事件处理机制。读完本文你将掌握如何在 LlamaIndex 应用中接入 You.com 的 Smart快速应答与 Research深度研究两种对话 API并将其作为标准 LLM 组件用于检索增强生成等场景。集成概览You.com 对话 API 与 LlamaIndexllama-index-llms-you是 LlamaIndex 官方集成仓库llama-index-integrations/llms中的一个 LLM 集成包封装了 You.com 的两类对话端点Smart 模式面向多种问题类型提供快速、可靠的回答引用的是整个网页的 URL。Research 模式针对多种问题类型提供带大量引用的深度答案引用的是与论点直接相关的具体网页片段。两类端点都会在答案中生成内联引用inline citations与相关网页结果。从包描述pyproject.toml看该包版本为0.5.0要求 Python3.10,4.0依赖llama-index-core0.13.0,0.15与sseclient-py1.8.0,2。模块的公开入口非常简洁__init__.py仅导出一个核心类from llama_index.llms.you.base import You __all__ [You]也就是说You类就是整个集成的全部对外接口其余细节均由内部实现承担。安装与依赖该集成以独立包形式发布安装命令如下pip install llama-index-llms-you安装时会自动带上两个运行时依赖llama-index-core0.13.0,0.15提供CustomLLM、LLMMetadata、CompletionResponse等核心抽象sseclient-py1.8.0,2用于解析 You.com 接口返回的 Server-Sent EventsSSE流式响应。获取 API Key 与配置方式接入 You.com API 需要先在 You.com 开发者平台注册并获取 API Key。该 Key 有两种提供方式优先级从源码 base.py 第 123-125 行可以明确看出property def _api_key(self) - str: return self.ydc_api_key or os.environ[YDC_API_KEY]构造You实例时显式传入ydc_api_key参数设置环境变量YDC_API_KEY此时可以省略构造参数。# 方式一环境变量 # export YDC_API_KEYyour-api-key from llama_index.llms.you import You llm You() # 方式二构造参数优先级更高 llm You(ydc_api_keyyour-api-key)注意若两者都未提供_api_key属性会抛出KeyError因访问不存在的环境变量YDC_API_KEY因此至少需要配置其中一种。核心参数mode 与端点路由You类继承自CustomLLM其字段定义位于 base.py 第 78-85 行mode: Literal[smart, research] Field( smart, descriptionYou.com conversational endpoints. Choose from smart or research, ) ydc_api_key: Optional[str] Field( None, descriptionYou.com API key, if YDC_API_KEY is not set in the environment, )mode选择对话端点类型取值只能是smart或research默认smart。它是Literal类型传入非法值会在校验阶段被拒绝。ydc_api_keyAPI Key默认为None未设置时回退到环境变量。mode决定实际请求的 HTTP 端点路由逻辑在 base.py 第 117-121 行property def endpoint(self) - str: if self.mode smart: return SMART_ENDPOINT return RESEARCH_ENDPOINT两个端点在文件顶部以常量定义base.py 第 15-16 行SMART_ENDPOINT https://chat-api.you.com/smart RESEARCH_ENDPOINT https://chat-api.you.com/research即smart对应 Smart 快速应答端点research对应 Research 深度研究端点。选择哪种模式取决于你的场景需要低延迟的常规问答选smart需要严谨来源、逐条引证的研究型问题选research。模型元数据You的metadata属性base.py 第 87-93 行向 LlamaIndex 框架声明了该 LLM 的能力边界property def metadata(self) - LLMMetadata: return LLMMetadata( model_namefyou.com-{self.mode}, is_chat_modelTrue, is_function_calling_modelFalse, )model_name形如you.com-smart或you.com-research随mode动态变化is_chat_modelTrue声明为对话模型CustomLLM的chat/stream_chat等对话接口可用is_function_calling_modelFalse明确不支持函数调用tool calling在编排 Agent 时应避免依赖其函数调用能力。快速开始完成一次对话You是标准的补全式接口最基础的用法是调用completefrom llama_index.llms.you import You llm You(moderesearch, ydc_api_keyyour-api-key) response llm.complete(What is the latest breakthrough in solid-state batteries?) print(response.text)complete的实现base.py 第 95-102 行会以queryprompt为请求体调用所选端点并将返回 JSON 中的answer字段作为文本同时把完整原始响应保存在raw属性中llm_completion_callback() def complete(self, prompt: str, **kwargs: Any) - CompletionResponse: response _request( self.endpoint, api_keyself._api_key, queryprompt, ) return CompletionResponse(textresponse[answer], rawresponse)其中llm_completion_callback()装饰器来自 llama_index.core.llms.callbacks用于自动触发 LlamaIndex 的补全回调链路便于接入 instrumentation 观测。由于继承了 CustomLLM你还可以直接使用对话式接口chat与stream_chat。CustomLLM会先通过messages_to_prompt将ChatMessage序列转换为提示文本再委托给complete/stream_complete并通过completion_response_to_chat_response等工具转换为ChatResponse。流式输出与 SSE 事件解析stream_complete提供了逐 token 的流式生成能力实现位于 base.py 第 104-115 行llm_completion_callback() def stream_complete(self, prompt: str, **kwargs: Any) - CompletionResponseGen: response _request_stream( self.endpoint, api_keyself._api_key, queryprompt, ) completion for token in response: completion token yield CompletionResponse(textcompletion, deltatoken)它每次从生成器取到一个 token 就产出一个CompletionResponse其中delta为本次新增片段、text为累计完整文本适合打字机式输出。流式底层依赖 SSE 协议事件解析逻辑在_request_streambase.py 第 30-47 行client sseclient.SSEClient(response) for event in client.events(): if event.event in (search_results, done): pass elif event.event token: yield event.data elif event.event error: raise ValueError(fError in response: {event.data}) else: raise NotImplementedError(fUnknown event type {event.event})服务端推送的事件类型及其处理方式如下事件类型含义处理行为search_results携带检索到的网页结果含引文数据跳过不进入答案文本done流结束标记跳过流自然终止token一个答案文本片段作为生成 token 逐段产出error服务端错误信息抛出ValueError携带错误内容其他未知事件抛出NotImplementedError这一设计意味着检索结果与答案 token 在同一个 SSE 流中传输search_results事件被忽略只有token事件会被当作答案内容增量输出从而把边检索边回答的体验平滑地暴露给调用方。底层请求实现非流式与流式请求都通过requests库以POST方式发送携带x-api-key请求头完成鉴权base.py 第 19-27 行def _request(base_url: str, api_key: str, **kwargs) - Dict[str, Any]: headers {x-api-key: api_key} response requests.post(base_url, headersheaders, jsonkwargs) response.raise_for_status() return response.json()鉴权方式请求头x-api-key携带 API Key请求体以 JSON 形式传递关键字参数例如{query: ...}错误处理raise_for_status()会在 HTTP 状态码非 2xx 时抛出异常返回值直接解析 JSON 响应体complete从中读取answer字段。流式请求_request_stream则在参数中追加streamTrue并采用requests.post(..., streamTrue)随后交给sseclient.SSEClient逐事件读取。源码注释还提示未来该函数可能被 OpenAPI 生成的 Python SDK 替换以获得更完善的输入输出类型支持——这也说明当前实现是轻量级的直接 HTTP 封装便于理解和二次开发。作为检索增强RAG管线组件使用由于You实现了 LlamaIndex 的 LLM 接口你可以直接把它插入各类索引与查询引擎例如from llama_index.core import VectorStoreIndex from llama_index.llms.you import You llm You(modesmart) # 在索引构建/查询时指定 llm或在全局设置 index VectorStoreIndex.from_documents(documents, llmllm) query_engine index.as_query_engine(llmllm) response query_engine.query(Summarize the key findings in these documents.) print(response)在基于文档的问答场景中You.com 的在线检索与引文能力可作为补充信号同时需要注意其is_function_calling_modelFalse因此在需要工具调用的 Agent 工作流中应谨慎使用或搭配支持函数调用的模型完成工具调度。测试与验证集成包自带单元测试 tests/test_llms_you.py其核心断言是验证You类确实挂接在 LlamaIndex 的 LLM 类型体系之下from llama_index.core.base.llms.base import BaseLLM from llama_index.llms.you import You def test_llm_class(): names_of_base_classes [b.__name__ for b in You.__mro__] assert BaseLLM.__name__ in names_of_base_classes该测试通过检查You的 MRO方法解析顺序确认其祖先链中包含BaseLLM从而保证它满足 LlamaIndex 对 LLM 组件的契约要求。这一验证在 pyproject.toml 中还有配套的工程规范支撑项目启用了mypydisallow_untyped_defs true、ruff、pylint、codespell等检查工具类作者标注为You-OpenSource导入路径为llama_index.llms.you。小结本文从 API 参考文档出发完整覆盖了llama-index-llms-you的安装、鉴权、mode端点路由、同步/流式调用、SSE 事件处理、底层 HTTP 实现与测试验证。你可以据此快速将 You.com 的 Smart 与 Research 对话能力接入自己的 LlamaIndex 应用日常快速问答使用modesmart追求低延迟与整页 URL 引用深度研究型问题使用moderesearch获取片段级精确引证需要打字机体验时使用stream_complete/stream_chat由 SSE 流逐 token 驱动。【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考