Gemini API:使用 LangChain 和 Chroma 进行问答

本教程面向有编程基础的开发者,深入讲解如何利用 Gemini、LangChain 和 Chroma 构建一个基于检索增强生成(RAG)的问答系统。通过实际代码示例,你将学习如何加载网页数据、生成嵌入、存储到向量数据库,并构建检索与生成链路。教程涵盖环境配置、API 密钥管理、核心组件原理、架构设计、常见错误排查及生产环境优化建议,帮助你掌握构建 AI 工程应用的关键技能。

技术背景

大型语言模型(LLM)在训练时仅基于公开数据,无法直接回答关于私有或自定义数据的问题。RAG(检索增强生成)通过检索相关文档片段作为上下文,使 LLM 能够基于特定数据生成准确答案。本教程使用 Gemini 作为 LLM 和嵌入模型,LangChain 作为编排框架,Chroma 作为向量数据库,实现一个完整的 RAG 应用。该技术适用于客服问答、知识库检索、文档摘要等场景,但受限于检索质量、上下文长度和模型能力。

核心原理

RAG 架构包含两个核心阶段:检索器(Retriever)和生成器(Generator)。检索器将用户查询转换为嵌入向量,在向量数据库中查找最相似的文档片段;生成器将检索到的片段与用户问题组合成提示,交给 LLM 生成答案。本教程中,网页数据通过 WebBaseLoader 加载,使用 Gemini 的嵌入模型生成向量,存储在 Chroma 中。检索器通过相似度搜索返回相关文档,生成器使用 stuff 文档链将所有文档合并到提示中,由 Gemini 模型生成回答。

架构分析

系统架构分为数据层、检索层和生成层。数据层使用 WebBaseLoader 加载网页,并通过文本分割提取关键部分。检索层使用 GoogleGenerativeAIEmbeddings 生成嵌入,Chroma 存储向量并支持持久化。生成层使用 ChatGoogleGenerativeAI 初始化 Gemini 模型,通过 LCEL 构建链:检索器获取相关文档,格式化后与用户问题一起填充到 PromptTemplate,传递给 LLM,最后通过 StrOutputParser 解析输出。设计上采用模块化组件,便于替换和扩展。

完整实战教程

##### 版权所有 2026 Google LLC。

# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Gemini API:使用 LangChain 和 Chroma 进行问答

注意: 此笔记本需要付费层级速率限制才能正常运行。(更多详情请参阅定价)。

概述

Gemini 是一系列生成式 AI 模型,让开发者能够生成内容并解决问题。这些模型经过设计和训练,可以处理文本和图像作为输入。

LangChain 是一个数据框架,旨在让 Gemini 等大型语言模型(LLM)更容易集成到应用程序中。

Chroma 是一个开源的嵌入数据库,专注于简单性和开发人员生产力。Chroma 允许用户存储嵌入及其元数据,嵌入文档和查询,并快速搜索嵌入。

在本笔记本中,您将学习如何使用 Gemini、LangChain 和 Chroma 创建一个应用程序,该应用程序使用网站上的数据来回答问题。

环境设置

首先,你需要安装所需的软件包并设置必要的环境变量。

安装

安装 LangChain 的 Python 库 langchain 以及 LangChain 用于 Gemini 的集成包 langchain-google-genai。接下来,安装 Chroma 的 Python 客户端 SDK chromadb。

%pip install --quiet langchain-core==0.1.23
%pip install --quiet langchain==0.1.1
%pip install --quiet langchain-google-genai==0.0.6
%pip install --quiet -U langchain-community==0.0.20
%pip install --quiet chromadb
%pip install --quiet bs4
from langchain import PromptTemplate
from langchain import hub
from langchain.docstore.document import Document
from langchain.document_loaders import WebBaseLoader
from langchain.schema import StrOutputParser
from langchain.schema.prompt_template import format_document
from langchain.schema.runnable import RunnablePassthrough
from langchain.vectorstores import Chroma

配置你的 API 密钥

要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab 密钥中。如果你还没有 API 密钥,或者不确定如何创建 Colab 密钥,请参阅 身份验证 示例。

import os
from google.colab import userdata
GEMINI_API_KEY=userdata.get('GEMINI_API_KEY')

os.environ["GEMINI_API_KEY"] = GEMINI_API_KEY

基本步骤

LLM 是在大型公共数据语料库上离线训练的。因此,如果没有额外的上下文,它们无法基于自定义或私有数据准确回答问题。

如果你想利用 LLM 基于私有数据回答问题,你必须在提示词中提供相关文档作为上下文。这种方法称为检索增强生成(RAG)。

你将使用这种方法,通过 LangChain 集成的 Gemini 文本模型创建一个问答助手。该助手预期回答关于 Gemini 模型的问题。为了实现这一点,你将使用网站上的数据为助手添加更多上下文。

在本教程中,你将实现基于 RAG 架构的两个主要组件:

  1. 检索器(Retriever)

根据用户的查询,检索器检索相关的片段,这些片段从文档中添加上下文。在本教程中,文档是网站数据。

相关的片段作为上下文传递给下一阶段——“生成器”。

  1. 生成器(Generator)

来自网站数据的相关片段与用户的查询一起传递给 LLM,以生成准确的答案。

在接下来的章节中,你将在实现应用程序时进一步了解这些阶段。

检索器

在此阶段,您将执行以下步骤:

  1. 使用 LangChain 读取并解析网站数据。
  1. 创建网站数据的嵌入。

嵌入是文本的数值表示(向量)。因此,具有相似含义的文本将具有相似的嵌入向量。您将使用 Gemini 的嵌入模型来创建网站数据的嵌入向量。

  1. 将嵌入存储在 Chroma 的向量存储中。

Chroma 是一个向量数据库。Chroma 向量存储有助于高效检索相似的向量。因此,为了向 LLM 的提示添加上下文,可以使用 Chroma 轻松检索与用户问题匹配的文本的相关嵌入。

  1. 从 Chroma 向量存储创建检索器。

检索器将用于将相关的网站嵌入与用户查询一起传递给 LLM。

读取并解析网站数据

LangChain 提供了多种多样的文档加载器。要将网站数据作为文档读取,你将使用 LangChain 中的 WebBaseLoader。

要了解更多关于如何使用 LangChain 的文档加载器从不同来源读取和解析输入数据的信息,请阅读 LangChain 的文档加载器指南。

loader = WebBaseLoader("https://blog.google/technology/ai/google-gemini-ai/")
docs = loader.load()

如果你只想选择网站数据中的特定部分来为提示添加上下文,可以使用正则表达式、文本切片或文本分割。

在本例中,你将使用 Python 的 split() 函数来提取所需部分的文本。提取的文本应转换回 LangChain 的 Document 格式。

# Extract the text from the website data document
text_content = docs[0].page_content

# The text content between the substrings "code, audio, image and video." to
# "Cloud TPU v5p" is relevant for this tutorial. You can use Python's `split()`
# to select the required content.
text_content_1 = text_content.split("code, audio, image and video.",1)[1]
final_text = text_content_1.split("Cloud TPU v5p",1)[0]

# Convert the text to LangChain's `Document` format
docs = [Document(page_content=final_text, metadata={"source": "local"})]

初始化 Gemini 的嵌入模型

为了从网站数据创建嵌入,你将使用 Gemini 的嵌入模型 gemini-embedding-001,该模型支持创建文本嵌入。

要使用此嵌入模型,你需要从 LangChain 导入 GoogleGenerativeAIEmbeddings。要了解更多关于嵌入模型的信息,请阅读 Google AI 的语言文档。

from langchain_google_genai import GoogleGenerativeAIEmbeddings

gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")

使用 Chroma 存储数据

要从网站数据创建 Chroma 向量数据库,您将使用 Chroma 的 from_documents 函数。在底层,此函数使用指定的嵌入模型从 LangChain 的文档加载器创建的文档中生成嵌入,并将它们存储在 Chroma 向量数据库中。

在调用 from_documents 函数从网站数据创建向量数据库时,您必须指定使用 LangChain 的 WebBasedLoader 从网站数据创建的 docs,并将 gemini_embeddings 作为嵌入模型。您还可以在 persist_directory 参数中指定一个目录,以将向量存储保存到磁盘。如果不指定目录,数据将仅保存在内存中。

# Save to disk
vectorstore = Chroma.from_documents(
                     documents=docs,                 # Data
                     embedding=gemini_embeddings,    # Embedding model
                     persist_directory="./chroma_db" # Directory to save data
                     )

使用 Chroma 创建检索器

现在,你将创建一个检索器,它可以从新创建的 Chroma 向量存储中检索网站数据嵌入。这个检索器稍后可用于传递嵌入,为 LLM 提供更多上下文以回答用户查询。

要加载之前存储在磁盘上的向量存储,你可以在 Chroma 初始化器的 persist_directory 参数中指定包含向量存储的目录名称,并在 embedding_function 参数中指定嵌入模型。

然后,你可以在向量存储上调用 Chroma 的 as_retriever 函数来创建检索器。

# Load from disk
vectorstore_disk = Chroma(
                        persist_directory="./chroma_db",       # Directory of db
                        embedding_function=gemini_embeddings   # Embedding model
                   )
# Get the Retriever interface for the store to use later.
# When an unstructured query is given to a retriever it will return documents.
# Read more about retrievers in the following link.
# https://python.langchain.com/docs/modules/data_connection/retrievers/
#
# Since only 1 document is stored in the Chroma vector store, search_kwargs `k`
# is set to 1 to decrease the `k` value of chroma's similarity search from 4 to
# 1. If you don't pass this value, you will get a warning.
retriever = vectorstore_disk.as_retriever(search_kwargs={"k": 1})

# Check if the retriever is working by trying to fetch the relevant docs related
# to the word 'MMLU' (Massive Multitask Language Understanding). If the length is greater than zero, it means that
# the retriever is functioning well.
print(len(retriever.get_relevant_documents("MMLU")))

生成器

当用户提问时,生成器会提示LLM给出答案。你在上一阶段从Chroma向量存储创建的检索器将用于将网站数据中的相关嵌入传递给LLM,从而为用户查询提供更多上下文。

在此阶段,你将执行以下步骤:

  1. 将以下内容链接在一起:
  2. * 一个用于使用检索器提取相关嵌入的提示。

    * 一个用于使用LangChain回答任何问题的提示。

    * 一个来自Gemini的LLM模型,用于提示。

  1. 以问题作为输入运行创建的链,以提示模型给出答案。

初始化 Gemini

您必须从 LangChain 导入 ChatGoogleGenerativeAI 来初始化您的模型。

在此示例中,您将使用 gemini-3.7-flash,因为它支持文本摘要。要了解更多关于文本模型的信息,请阅读 Google AI 的语言文档。

您可以通过在初始化 ChatGoogleGenerativeAI LLM 时传递适当的值来配置模型参数,例如 *temperature* 或 *top_p*。要了解更多关于这些参数及其用途的信息,请阅读 Google AI 的概念指南。

from langchain_google_genai import ChatGoogleGenerativeAI

# To configure model parameters use the `generation_config` parameter.
# eg. generation_config = {"temperature": 0.7, "topP": 0.8, "topK": 40}
# If you only want to set a custom temperature for the model use the
# "temperature" parameter directly.

llm = ChatGoogleGenerativeAI(model="gemini-3.7-flash")

创建提示模板

你将使用 LangChain 的 PromptTemplate 来生成向 LLM 提问的提示。

在 llm_prompt 中,变量 question 稍后将被输入的问题替换,变量 context 将被从 Chroma 向量存储中检索到的网站相关文本替换。

# Prompt template to query Gemini
llm_prompt_template = """You are an assistant for question-answering tasks.
Use the following context to answer the question.
If you don't know the answer, just say that you don't know.
Use five sentences maximum and keep the answer concise.\n
Question: {question} \nContext: {context} \nAnswer:"""

llm_prompt = PromptTemplate.from_template(llm_prompt_template)

print(llm_prompt)

创建 stuff 文档链

LangChain 提供了 Chains,用于将 LLM 与其他组件或彼此链接,以构建复杂应用。在此应用中,你将创建一个 stuff 文档链。stuff 文档链允许你合并所有相关文档,将其插入提示中,并将该提示传递给 LLM。

你可以使用 LangChain 表达式语言 (LCEL) 创建 stuff 文档链。

要了解不同类型的文档链,请阅读 LangChain 的 chains 指南。

此应用的 stuff 文档链会检索相关网站数据,并将其作为上下文与输入问题一起传递给 LLM 提示。

# Combine data from documents to readable string format.
def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

# Create stuff documents chain using LCEL.
#
# This is called a chain because you are chaining together different elements
# with the LLM. In the following example, to create the stuff chain, you will
# combine the relevant context from the website data matching the question, the
# LLM model, and the output parser together like a chain using LCEL.
#
# The chain implements the following pipeline:
# 1. Extract the website data relevant to the question from the Chroma
#    vector store and save it to the variable `context`.
# 2. `RunnablePassthrough` option to provide `question` when invoking
#    the chain.
# 3. The `context` and `question` are then passed to the prompt where they
#    are populated in the respective variables.
# 4. This prompt is then passed to the LLM (`gemini-3.7-flash`).
# 5. Output from the LLM is passed through an output parser
#    to structure the model's response.
rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | llm_prompt
    | llm
    | StrOutputParser()
)

提示模型

现在,你可以通过向之前创建的 stuff documents 链的 invoke() 函数传递任何问题来查询 LLM。

from IPython.display import Markdown

Markdown(rag_chain.invoke("What is Gemini?"))

结论

至此,你已经成功创建了一个 LLM 应用程序,它借助 Gemini、LangChain 和 Chroma,使用网站中的数据来回答问题。

常见问题

常见错误包括:1. API 密钥未正确设置,导致认证失败;2. 嵌入模型或 LLM 模型名称错误,导致调用失败;3. Chroma 持久化目录权限问题;4. 检索结果为空,可能因文档分割不当或相似度阈值过高。排查方法:检查环境变量、确认模型名称、查看日志、调整 search_kwargs 中的 k 值。生产环境优化:使用异步加载、批量嵌入、缓存、向量索引优化(如 HNSW)、监控和日志记录。

企业应用扩展

可扩展方向:1. 支持多种数据源(PDF、数据库、API);2. 使用更高级的检索策略(如混合检索、重排序);3. 集成对话记忆,实现多轮问答;4. 部署为 REST API 或微服务;5. 使用向量数据库集群(如 Milvus、Weaviate)提升扩展性;6. 引入评估机制,持续优化提示和检索质量。

总结

本教程面向有编程基础的开发者,深入讲解如何利用 Gemini、LangChain 和 Chroma 构建一个基于检索增强生成(RAG)的问答系统。通过实际代码示例,你将学习如何加载网页数据、生成嵌入、存储到向量数据库,并构建检索与生成链路。教程涵盖环境配置、API 密钥管理、核心组件原理、架构设计、常见错误排查及生产环境优化建议,帮助你掌握构建 AI 工程应用的关键技能。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部RAG 与知识库教程