<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title><![CDATA[Neha Saini - Elasticsearch Labs]]></title>
    <description><![CDATA[Articles and tutorials from the Search team at Elastic]]></description>
    <copyright><![CDATA[© 2026. Elasticsearch B.V. All Rights Reserved]]></copyright>
    <image>
      <title><![CDATA[Neha Saini - Elasticsearch Labs]]></title>
      <url>https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt1121c0bf0e8a6e65/6a88da6340a1841030ef456f/search-labs-thumbnail.png</url>
      <link>https://www.elastic.co/cn/search-labs/author/neha-saini</link>
    </image>
    <link>https://www.elastic.co/cn/search-labs/author/neha-saini</link>
    <atom:link href="https://www.elastic.co/cn/search-labs/rss/author/neha-saini.xml" rel="self" type="application/rss+xml"/>
    <language><![CDATA[cn]]></language>
    <lastBuildDate>Sun, 20 Sep 2026 19:51:42 GMT</lastBuildDate>
  <item>
    <title><![CDATA[使用 LangGraph 和 Elasticsearch 构建 RAG 工作流程]]></title>
    <description><![CDATA[了解如何使用 Elasticsearch 配置和定制 LangGraph 检索代理模板，以构建 RAG 工作流，从而实现高效的数据检索和人工智能驱动的响应。]]></description>
    <content:encoded><![CDATA[<p><a href="https://github.com/langchain-ai/retrieval-agent-template">LangGraph 检索代理模板</a>是 LangChain 开发的一个启动项目，目的是方便在 LangGraph Studio 中使用 LangGraph 创建基于检索的问题解答系统。该模板经过预配置，可与 Elasticsearch 无缝集成，使开发人员能够快速构建可高效索引和检索文档的代理。</p><p>本博客主要介绍如何使用 LangGraph Studio 和 LangGraph CLI 运行和定制 LangChain 检索代理模板。该模板为利用 Elasticsearch 等各种检索后端构建检索增强生成 (RAG) 应用程序提供了一个框架。</p><p>我们将指导您设置、配置环境，并使用 Elastic 高效执行模板，同时定制代理流程。</p><h2>准备工作</h2><p>在继续之前，请确保已安装以下设备：</p><ul><li><p>Elasticsearch 云部署或内部部署（或在 Elastic Cloud 上创建 14 天<a href="https://www.elastic.co/cn/cloud/cloud-trial-overview">免费试用版 </a>）- 版本 8.0.0 或更高</p></li><li><p>Python 3.9+</p></li><li><p>访问 LLM 提供商，如<a href="https://cohere.com/">Cohere</a>（本指南中使用）、<a href="https://openai.com/">OpenAI</a> 或<a href="https://www.anthropic.com/claude">Anthropic/Claude</a></p></li></ul><h2>创建 LangGraph 应用程序</h2><h3>1.安装 LangGraph CLI</h3>pip install --upgrade "langgraph-cli[inmem]"<h3>2.根据检索代理模板创建 LangGraph 应用程序</h3>mkdir lg-agent-demo
cd lg-agent-demo
langgraph new lg-agent-demo <p><em>您将看到一个交互式菜单，可以从可用模板列表中进行选择。 </em>为检索代理选择 4，为 Python 选择 1，如下图所示：</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltd44177037ea46d45/6a17f86b3e9e45265fba1663/6a41a41f95c2477c67810adc7be46d91faf06878-1600x407.png" alt="交互式检索模板。" /><ul><li><p><strong>故障排除</strong>：如果遇到以下错误："urllib.error.URLError:&lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)&gt;"</p></li></ul><p>请运行 Python 的安装证书命令来解决问题，如下所示。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltbbe2d1d3a1af75b1/6a17f86d445de97c9c4d02e7/83ec238136c41738457299fd42c83aff32eb5b97-1407x75.png" alt="运行 Python 安装证书命令。" /><h3>3.安装依赖项</h3><p>在新 LangGraph 应用程序的根目录下创建虚拟环境，并以<code>edit</code> 模式安装依赖项，这样服务器就会使用本地更改：</p>#For Mac
python3 -m venv lg-demo
source lg-demo/bin/activate 
pip install -e .

#For Windows
python3 -m venv lg-demo
lg-demo\Scripts\activate 
pip install -e .<h2>设置环境</h2><h3>1.创建 .环境文件</h3><p><code>.env</code> 文件包含 API 密钥和配置，因此应用程序可以连接到您选择的 LLM 和检索提供商。复制示例配置，生成新的<code>.env</code> 文件：</p>cp .env.example .env<h3>2.配置 .env文件</h3><p><code>.env</code> 文件带有一组默认配置。您可以根据设置添加必要的 API 密钥和值来更新它。任何与使用案例无关的键都可以保持不变或删除。</p># To separate your traces from other applications
LANGSMITH_PROJECT=retrieval-agent

# LLM choice (set the API key for your selected provider):
ANTHROPIC_API_KEY=your_anthropic_api_key
FIREWORKS_API_KEY=your_fireworks_api_key
OPENAI_API_KEY=your_openai_api_key

# Retrieval provider (configure based on your chosen service):

## Elastic Cloud:
ELASTICSEARCH_URL=https://your_elastic_cloud_url
ELASTICSEARCH_API_KEY=your_elastic_api_key

## Elastic Local:
ELASTICSEARCH_URL=http://host.docker.internal:9200
ELASTICSEARCH_USER=elastic
ELASTICSEARCH_PASSWORD=changeme

## Pinecone:
PINECONE_API_KEY=your_pinecone_api_key
PINECONE_INDEX_NAME=your_pinecone_index_name

## MongoDB Atlas:
MONGODB_URI=your_mongodb_connection_string

# Cohere API key:
COHERE_API_KEY=your_cohere_api_key<ul><li><p><code>.env</code> 文件示例（使用弹性云和 Cohere）</p></li></ul><p>下面是<code>.env</code> 配置示例，用于将<strong>Elastic Cloud</strong>用作检索提供商，将<strong>Cohere</strong>用作 LLM，本博客对此进行了演示：</p># To separate your traces from other applications
LANGSMITH_PROJECT=retrieval-agent
#Retrieval Provider
# Elasticsearch configuration
ELASTICSEARCH_URL=elastic-url:443
ELASTICSEARCH_API_KEY=elastic_api_key
# Cohere API key
COHERE_API_KEY=cohere_api_key<p><em>注：本指南使用 Cohere 进行响应生成和嵌入，您也可以 </em>根据自己的使用情况使用 其他 LLM 提供商，如 <em><strong>OpenAI</strong></em><em>、 </em><em><strong>Claude</strong></em><em>，甚至本地 LLM 模型。请确保您打算使用的每个密钥都已存在，并在 </em><em><code>.env</code></em><em> 文件</em>中正确设置  。</p><h3>3.更新配置文件 -configuration.py </h3><p>使用适当的 API 密钥设置<code>.env</code> 文件后，下一步就是更新应用程序的默认模型配置。更新配置可确保系统使用您在<code>.env</code> 文件中指定的服务和模型。</p><p>导航至配置文件：</p> cd src/retrieval_graph<p><code>configuration.py</code> 文件包含检索代理用于三项主要任务的默认模型设置：</p><ul><li><p><strong>嵌入模型</strong>--将文件转换为矢量表示</p></li><li><p><strong>查询模型</strong>- 将用户的查询转化为矢量</p></li><li><p><strong>响应模型</strong>- 生成最终响应</p></li></ul><p>默认情况下，代码使用<strong>OpenAI</strong>（如<code>openai/text-embedding-3-small</code> ）和<strong>Anthropic</strong>（如<code>anthropic/claude-3-5-sonnet-20240620 and anthropic/claude-3-haiku-20240307</code> ）的模型。在本博客中，我们将改用 Cohere 模型。如果您已经在使用 OpenAI 或 Anthropic，则无需更改。</p><h4>更改示例（使用 Cohere）：</h4><p>打开<code>configuration.py</code> 并修改模型默认值，如下图所示：</p>…
 embedding_model: Annotated[
       str,
       {"__template_metadata__": {"kind": "embeddings"}},
   ] = field(
       default="cohere/embed-english-v3.0",
…
response_model: Annotated[str, {"__template_metadata__": {"kind": "llm"}}] = field(
       default="cohere/command-r-08-2024",
…
query_model: Annotated[str, {"__template_metadata__": {"kind": "llm"}}] = field(
       default="cohere/command-r-08-2024",
       metadata={<h2>使用 LangGraph CLI 运行检索代理</h2><h3>1.启动 LangGraph 服务器</h3>cd lg-agent-demo
langgraph dev<p>这将在本地启动 LangGraph API 服务器。如果运行成功，你应该会看到类似的内容：</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt46c7a703e715ef66/6a17f86eb1e113272d79f42e/e3c3344b24651067e2d0892d870feca505b3be35-1494x542.png" alt=" LangGraph API 服务器运行成功。" /><p>开放工作室用户界面 URL。</p><p>有两种图表可供选择：</p><ul><li><p><strong>检索图</strong>：从 Elasticsearch 中检索数据，并使用 LLM 响应查询。</p></li><li><p><strong>索引图</strong>：将文档索引到 Elasticsearch，并使用 LLM 生成嵌入。</p></li></ul><h3>2.配置索引图</h3><ul><li><p>打开索引图。</p></li><li><p>单击管理助手。</p><ul><li><p>点击<strong>"添加新助手</strong>"，输入指定的用户详细信息，然后关闭窗口。</p></li></ul></li></ul>{"user_id": "101"}<h3>3.为样本文件编制索引</h3><ul><li><p>为以下样本文件编制索引，这些文件是消费与工业专用技术公司的假设季度报告：</p></li></ul>[
  {    "page_content": "NoveTech Solutions Q1 2025 Report - Revenue: $120.5M, Net Profit: $18.2M, EPS: $2.15. Strong AI software launch and $50M government contract secured."
  },
  {
    "page_content": "NoveTech Solutions Business Highlights - AI-driven analytics software gained 15% market share. Expansion into Southeast Asia with two new offices. Cloud security contract secured."
  },
  {
    "page_content": "NoveTech Solutions Financial Overview - Operating expenses at $85.3M, Gross Margin 29.3%. Stock price rose from $72.5 to $78.3. Market Cap reached $5.2B."
  },
  {
    "page_content": "NoveTech Solutions Challenges - Rising supply chain costs impacting hardware production. Regulatory delays slowing European expansion. Competitive pressure in cybersecurity sector."
  },
  {
    "page_content": "NoveTech Solutions Future Outlook - Expected revenue for Q2 2025: $135M. New AI chatbot and blockchain security platform launch planned. Expansion into Latin America."
  },
  {
    "page_content": "NoveTech Solutions Market Performance - Year-over-Year growth at 12.7%. Stock price increase reflects investor confidence. Cybersecurity and AI sectors remain competitive."
  },
  {
    "page_content": "NoveTech Solutions Strategic Moves - Investing in R&amp;D to enhance AI-driven automation. Strengthening partnerships with enterprise cloud providers. Focusing on data privacy solutions."
  },
  {
    "page_content": "NoveTech Solutions CEO Statement - 'NoveTech Solutions continues to innovate in AI and cybersecurity. Our growth strategy remains strong, and we foresee steady expansion in the coming quarters.'"
  }
]<p>文件索引完成后，你会在线程中看到一条删除信息，如下图所示。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt38715eadffcb62f0/6a17f877faa9135f7393ca4c/fd3a1efd64cb54d54ea56ef5055249dd066d5708-1600x854.png" alt="为 LangGraph 和 Elasticsearch RAG 工作流文档编制索引。" /><h3>4.运行检索图</h3><ul><li><p>切换到检索图。</p></li><li><p>输入以下搜索查询：</p></li></ul>What was NovaTech Solutions total revenue in Q1 2025?<img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt5c0d070fca52e512/6a17f879505ac36d37ad8d12/eb4d8ddfe0effd7e1868fba921b8ef13f7baf27a-1600x755.png" alt="运行 LangGraph 和 Elasticsearch 检索图" /><p>系统将返回相关文件，并根据索引数据提供准确答案。</p><h2>自定义检索代理</h2><p>为了提升用户体验，我们在检索图中引入了一个定制步骤，以预测用户可能提出的下三个问题。这一预测的依据是</p><ul><li><p>从检索到的文件中获取上下文</p></li><li><p>以前的用户互动</p></li><li><p>最后一次用户查询</p></li></ul><p>实施查询预测功能需要更改以下代码：</p><h3>1.更新 graph.py</h3><ul><li><p>添加<code>predict_query</code> 功能：</p></li></ul>async def predict_query(
   state: State, *, config: RunnableConfig
) -&gt; dict[str, list[BaseMessage]]:
   logger.info(f"predict_query predict_querypredict_query predict_query predict_query predict_query")  # Log the query

   configuration = Configuration.from_runnable_config(config)
   prompt = ChatPromptTemplate.from_messages(
       [
           ("system", configuration.predict_next_question_prompt),
           ("placeholder", "{messages}"),
       ]
   )
   model = load_chat_model(configuration.response_model)
   user_query = state.queries[-1] if state.queries else "No prior query available"
   logger.info(f"user_query: {user_query}")
   logger.info(f"statemessage: {state.messages}")
   #human_messages = [msg for msg in state.message if isinstance(msg, HumanMessage)]

   message_value = await prompt.ainvoke(
       {
           "messages": state.messages,
           "user_query": user_query,  # Use the most recent query as primary input
           "system_time": datetime.now(tz=timezone.utc).isoformat(),
       },
       config,
   )

   next_question = await model.ainvoke(message_value, config)
   return {"next_question": [next_question]}<ul><li><p>修改<code>respond</code> 函数，以返回<strong><code>response</code></strong> 对象，而不是消息：</p></li></ul>async def respond(
   state: State, *, config: RunnableConfig
) -&gt; dict[str, list[BaseMessage]]:
   """Call the LLM powering our "agent"."""
   configuration = Configuration.from_runnable_config(config)
   # Feel free to customize the prompt, model, and other logic!
   prompt = ChatPromptTemplate.from_messages(
       [
           ("system", configuration.response_system_prompt),
           ("placeholder", "{messages}"),
       ]
   )
   model = load_chat_model(configuration.response_model)

   retrieved_docs = format_docs(state.retrieved_docs)
   message_value = await prompt.ainvoke(
       {
           "messages": state.messages,
           "retrieved_docs": retrieved_docs,
           "system_time": datetime.now(tz=timezone.utc).isoformat(),
       },
       config,
   )
   response = await model.ainvoke(message_value, config)
   # We return a list, because this will get added to the existing list
   return {"response": [response]}<ul><li><p>更新图结构，为 predict_query 添加新节点和边：</p></li></ul>builder.add_node(generate_query)
builder.add_node(retrieve)
builder.add_node(respond)
builder.add_node(predict_query)
builder.add_edge("__start__", "generate_query")
builder.add_edge("generate_query", "retrieve")
builder.add_edge("retrieve", "respond")
builder.add_edge("respond", "predict_query")<h3>2.更新 prompts.py</h3><ul><li><p>在<code>prompts.py</code> 中进行guery预测的工艺提示：</p></li></ul>PREDICT_NEXT_QUESTION_PROMPT = """Given the user query and the retrieved documents, suggest the most likely next question the user might ask.

**Context:**
- Previous Queries:
{previous_queries}

- Latest User Query: {user_query}

- Retrieved Documents:
{retrieved_docs}

**Guidelines:**
1. Do not suggest a question that has already been asked in previous queries.
2. Consider the retrieved documents when predicting the next logical question.
3. If the user's query is already fully answered, suggest a relevant follow-up question.
4. Keep the suggested question natural and conversational.
5. Suggest at least 3 question

System time: {system_time}"""<h3>3.更新 configuration.py</h3><ul><li><p>添加<code>predict_next_question_prompt</code> ：</p></li></ul>predict_next_question_prompt: str = field(
       default=prompts.PREDICT_NEXT_QUESTION_PROMPT,
       metadata={"description": "The system prompt used for generating responses."},
   )<h3>4.更新 state.py</h3><ul><li><p>添加以下属性</p></li></ul>response: Annotated[Sequence[AnyMessage], add_messages]
next_question : Annotated[Sequence[AnyMessage], add_messages]<h3>5.重新运行检索图</h3><ul><li><p>再次输入以下搜索查询：</p></li></ul>What was NovaTech Solutions total revenue in Q1 2025?<p>系统将处理输入信息，并预测用户可能提出的三个相关问题，如下图所示。</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltd8d4de9396ca4853/6a17f87be31791dc742d59c7/70e855a2e4edc0ba5a147588df0de30eb081d053-1600x777.png" alt="使用 LangGraph 和 Elasticsearch 运行包含 3 个用户问题的检索图" /><h2>结论</h2><p>在 LangGraph Studio 和 CLI 中集成检索代理模板有几个主要好处：</p><ul><li><p><strong>加速开发</strong>：模板和可视化工具简化了检索工作流的创建和调试，缩短了开发时间。</p></li><li><p><strong>无缝部署</strong>：对 API 和自动扩展的内置支持可确保跨环境的顺利部署。</p></li><li><p><strong>易于更新：</strong>修改工作流程、添加新功能和集成其他节点都很简单，从而更容易扩展和增强检索流程。</p></li><li><p><strong>持久记忆</strong>：系统保留代理状态和知识，提高一致性和可靠性。</p></li><li><p><strong>灵活的工作流程建模</strong>：开发人员可针对特定用例定制检索逻辑和通信规则。</p></li><li><p><strong>实时交互和调试</strong>：通过与运行中的代理互动，可以高效地进行测试和解决问题。</p></li></ul><p>利用这些功能，企业可以建立强大、高效和可扩展的检索系统，从而提高数据的可访问性和用户体验。</p><p>该项目的完整源代码可在<a href="https://github.com/elastic/elasticsearch-labs/tree/main/supporting-blog-content/langraph-retrieval-agent-template-demo">GitHub</a> 上获取。</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/build-rag-workflow-langgraph-elasticsearch</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/build-rag-workflow-langgraph-elasticsearch</guid>
    <category><![CDATA[AI]]></category>
    <dc:creator><![CDATA[Neha Saini]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt0c9f03d2c1a9cb4c/6a17f87d0b0bed3781dd377c/17b7e7b336f73e232375d1add582ae5f6c52a279-1440x840.png" length="0" type="image/png"/>
    <pubDate>Fri, 25 Apr 2025 00:00:00 GMT</pubDate>
  </item>
  </channel>
</rss>