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 与 LlamaIndex
llama-index-llms-you是 LlamaIndex 官方集成仓库(llama-index-integrations/llms)中的一个 LLM 集成包,封装了 You.com 的两类对话端点:
- Smart 模式:面向多种问题类型提供快速、可靠的回答,引用的是整个网页的 URL。
- Research 模式:针对多种问题类型提供带大量引用的深度答案,引用的是与论点直接相关的具体网页片段。
两类端点都会在答案中生成内联引用(inline citations)与相关网页结果。从包描述(pyproject.toml)看,该包版本为0.5.0,要求 Python>=3.10,<4.0,依赖llama-index-core>=0.13.0,<0.15与sseclient-py>=1.8.0,<2。
模块的公开入口非常简洁,__init__.py仅导出一个核心类:
from llama_index.llms.you.base import You __all__ = ["You"]也就是说,You类就是整个集成的全部对外接口,其余细节均由内部实现承担。
安装与依赖
该集成以独立包形式发布,安装命令如下:
pip install llama-index-llms-you安装时会自动带上两个运行时依赖:
llama-index-core>=0.13.0,<0.15:提供CustomLLM、LLMMetadata、CompletionResponse等核心抽象;sseclient-py>=1.8.0,<2:用于解析 You.com 接口返回的 Server-Sent Events(SSE)流式响应。
获取 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_KEY="your-api-key" from llama_index.llms.you import You llm = You() # 方式二:构造参数(优先级更高) llm = You(ydc_api_key="your-api-key")注意:若两者都未提供,_api_key属性会抛出KeyError(因访问不存在的环境变量YDC_API_KEY),因此至少需要配置其中一种。
核心参数:mode 与端点路由
You类继承自CustomLLM,其字段定义位于 base.py 第 78-85 行:
mode: Literal["smart", "research"] = Field( "smart", description='You.com conversational endpoints. Choose from "smart" or "research"', ) ydc_api_key: Optional[str] = Field( None, description="You.com API key, if `YDC_API_KEY` is not set in the environment", )mode:选择对话端点类型,取值只能是"smart"或"research",默认"smart"。它是Literal类型,传入非法值会在校验阶段被拒绝。ydc_api_key:API 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_name=f"you.com-{self.mode}", is_chat_model=True, is_function_calling_model=False, )model_name形如you.com-smart或you.com-research,随mode动态变化;is_chat_model=True:声明为对话模型,CustomLLM的chat/stream_chat等对话接口可用;is_function_calling_model=False:明确不支持函数调用(tool calling),在编排 Agent 时应避免依赖其函数调用能力。
快速开始:完成一次对话
You是标准的补全式接口,最基础的用法是调用complete:
from llama_index.llms.you import You llm = You(mode="research", ydc_api_key="your-api-key") response = llm.complete("What is the latest breakthrough in solid-state batteries?") print(response.text)complete的实现(base.py 第 95-102 行)会以query=prompt为请求体调用所选端点,并将返回 JSON 中的answer字段作为文本,同时把完整原始响应保存在raw属性中:
@llm_completion_callback() def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: response = _request( self.endpoint, api_key=self._api_key, query=prompt, ) return CompletionResponse(text=response["answer"], raw=response)其中@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_key=self._api_key, query=prompt, ) completion = "" for token in response: completion += token yield CompletionResponse(text=completion, delta=token)它每次从生成器取到一个 token 就产出一个CompletionResponse,其中delta为本次新增片段、text为累计完整文本,适合打字机式输出。
流式底层依赖 SSE 协议,事件解析逻辑在_request_stream(base.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(f"Error in response: {event.data}") else: raise NotImplementedError(f"Unknown 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, headers=headers, json=kwargs) response.raise_for_status() return response.json()- 鉴权方式:请求头
x-api-key携带 API Key; - 请求体:以 JSON 形式传递关键字参数,例如
{"query": "..."}; - 错误处理:
raise_for_status()会在 HTTP 状态码非 2xx 时抛出异常; - 返回值:直接解析 JSON 响应体,
complete从中读取answer字段。
流式请求(_request_stream)则在参数中追加stream=True并采用requests.post(..., stream=True),随后交给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(mode="smart") # 在索引构建/查询时指定 llm,或在全局设置 index = VectorStoreIndex.from_documents(documents, llm=llm) query_engine = index.as_query_engine(llm=llm) response = query_engine.query("Summarize the key findings in these documents.") print(response)在基于文档的问答场景中,You.com 的在线检索与引文能力可作为补充信号;同时需要注意其is_function_calling_model=False,因此在需要工具调用的 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 中还有配套的工程规范支撑:项目启用了mypy(disallow_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 应用:
- 日常快速问答使用
mode="smart",追求低延迟与整页 URL 引用; - 深度研究型问题使用
mode="research",获取片段级精确引证; - 需要打字机体验时使用
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),仅供参考