在 Cloud Run 上部署 LangChain 智能体

1. 概览

智能体 是一种自主程序,它与 AI 模型对话,使用其拥有的工具和上下文执行基于目标的操作,并且能够根据事实做出自主决策!

智能体框架(例如智能体开发套件(ADK)、LangChain、smolagents)用于创建智能体。通过此类框架创建的智能体应用可以部署到 Cloud Run,并且可以作为无服务器应用提供给用户。

在此 Codelab 中,我们将使用 LangChain 构建智能体并将其部署到 Cloud Run。

构建内容

准备好从原型 PROMPT 转向构建智能体了吗?我们将使用 LangChain 创建智能体,以结构化格式获取有关历史人物的信息。在此实验中,您将:

  1. 使用 LangChain 构建一个简单的智能体,以结构化格式生成有关历史人物的信息
  2. 在本地运行智能体,并确保其按预期工作
  3. 将智能体部署到 Cloud Run,并使用 Cloud Run 网址调用它

要求

  • 浏览器,例如 ChromeFirefox
  • 启用了结算功能的 Google Cloud 项目。

2. 准备工作

创建项目

  1. Google Cloud 控制台的项目选择器页面上,选择或创建一个 Google Cloud 项目
  2. 确保您的云项目已启用结算功能。了解如何检查项目是否已启用结算功能
  3. 点击此链接以激活 Cloud Shell。您可以点击 Cloud Shell 中的相应按钮,在 Cloud Shell 终端 (用于运行 Cloud 命令)和编辑器(用于构建项目)之间切换。
  4. 连接到 Cloud Shell 后,您可以使用以下命令检查自己是否已通过身份验证,以及项目是否已设置为您的项目 ID:
gcloud auth list
  1. 在 Cloud Shell 中运行以下命令,以确认 gcloud 命令了解您的项目。
gcloud config list project
  1. 如果项目未设置,请使用以下命令进行设置:
gcloud config set project <YOUR_PROJECT_ID>
  1. 确保安装了 Python 3.13 或更高版本

如需了解其他 gcloud 命令和用法,请参阅文档

3. 创建 LangChain 智能体

项目结构

在 Cloud Shell 中,创建一个名为 langchain-app 的文件夹,并在其中添加以下文件:

langchain-gemini-fastapi-app/
├── main.py
├── requirements.txt

应用代码

以下是您应在 requirements.txt 中添加的依赖项:

fastapi
uvicorn
langchain
langchain-google-genai
python-dotenv

main.py 中,我们将编写使用 Gemini 模型的智能体代码,并检索有关历史人物的信息。检索后,按照指示将其格式化为结构化格式。

此实现使用现代 LCEL(LangChain 表达式语言)语法。

import os
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import JsonOutputParser

# Initialize FastAPI
app = FastAPI(title="LangChain App for Historical Figures")

# 1. Setup Gemini Model
# We expect GOOGLE_API_KEY to be set in the environment variables
llm = ChatGoogleGenerativeAI(
    model="gemini-2.5-flash",
    temperature=0.7
)

# 2. Define the Prompt
prompt = ChatPromptTemplate.from_template("You are an expert Historian. For the historical personality {name}, you are able to accurately tell their birth date and birth country. Return the output in the JSON format containing name, birthDate, birthCountry. In case you are unable to retrieve birthDate or birthCountry, just have the unknown values as null. ensure the response is a valid json object only.")
output_parser = JsonOutputParser()

# Chain: Prompt -> Model -> Json Output Parser
chain = prompt | llm | output_parser

# 3. Define Request Model
class QueryRequest(BaseModel):
    name: str

# 4. Define Endpoint
@app.post("/chat")
async def chat(request: QueryRequest):
    try:
        response = await chain.ainvoke({"name": request.name})
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
def health_check():
    return {"status": "ok", "service": "LangChain-Gemini-FastAPI"}

4. 测试智能体

在部署之前,您可以在本地对其进行测试。

  1. AI Studio 中创建 Gemini API 密钥。
  2. 将 Gemini API 密钥导出为:
export GOOGLE_API_KEY="AIzaSy..."
  1. 运行服务器。
uvicorn main:app --port 8080 --host 0.0.0.0
  1. 使用以下 curl 命令测试智能体:
curl -X POST http://localhost:8080/chat \
     -H "Content-Type: application/json" \
     -d '{"name": "Abraham Lincoln"}'

检查您是否获得了包含姓名、出生日期和出生国家/地区的 JSON 结构化输出。

5. 部署到 Cloud Run

我们将使用 gcloud run deploy 命令将智能体应用部署到 Cloud Run。以下命令使用 Cloud Build 构建容器,并一步将其部署到 Cloud Run。

YOUR_API_KEY 替换为您的实际 Gemini API 密钥。

gcloud run deploy gemini-fastapi-service \
  --source . \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated \
  --set-env-vars GOOGLE_API_KEY=<YOUR_API_KEY>

部署完成后,您应该会在终端中看到端点,该端点可供您使用。

6. 测试部署

使用 Cloud Run 端点,并执行 curl 以确保获得预期结果。

curl -X POST <CLOUD_RUN_ENDPOINT> \
     -H "Content-Type: application/json" \
     -d '{"name": "Abraham Lincoln"}'

您应该会获得与在本地运行的应用中获得的结果相同的结果。

7. 清理

为避免系统因本 Codelab 中使用的资源向您的 Google Cloud 账号收取费用,请按照以下步骤操作:

  1. 在 Google Cloud 控制台中,前往 管理资源 页面。
  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关停 以删除项目。

8. 恭喜

恭喜!您已成功创建并与部署在 Cloud Run 上的 LangChain 智能体进行了交互!