从手动到自动:Gemini与LangChain集成实现generative-ai项目工作流自动化

从手动到自动:Gemini与LangChain集成实现generative-ai项目工作流自动化

【免费下载链接】generative-ai Sample code and notebooks for Generative AI on Google Cloud 【免费下载链接】generative-ai 项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai

痛点与解决方案

你是否还在为Generative AI项目中的工作流繁琐而烦恼?手动调用API、处理数据、验证结果,这些重复劳动不仅耗时,还容易出错。本文将带你一文解决这些问题,通过Gemini与LangChain的集成,实现工作流自动化,提升开发效率。读完本文,你将能够:掌握Gemini与LangChain的集成方法、构建自动化工作流、处理实际业务场景中的问题。

核心概念

LangChain简介

LangChain是一个用于开发由大型语言模型(LLMs)驱动的应用程序的框架。它主要通过两种方式简化与语言模型的工作:一是集成外部数据,如文件、其他应用程序和API数据到LLMs;二是允许LLMs通过决策与环境交互,并使用LLMs帮助决定下一步行动。

要构建有效的生成式AI应用程序,关键是使LLMs能够与外部系统交互。这使模型具有数据感知能力和代理能力,意味着它们可以理解、推理并使用数据采取有意义的行动。外部系统可以是公共数据语料库、私有知识存储库、数据库、应用程序、API,或通过Google搜索访问公共互联网。

以下是LLMs可以通过其他系统增强的一些模式:

  • 将自然语言转换为SQL,在数据库上执行SQL,分析并呈现结果
  • 根据用户查询调用外部webhook或API
  • 综合多个模型的输出,或以特定顺序链接模型

虽然将这些调用连接在一起并进行编排看起来很简单,但为每个不同的数据连接器或新模型编写粘合代码变得非常繁琐。这就是LangChain的用武之地!

Gemini与LangChain集成优势

Vertex AI生成式AI模型(Gemini和Embeddings)与LangChain Python SDK正式集成,使使用Gemini模型构建应用程序变得更加方便,同时兼具LangChain的易用性和灵活性。

快速开始

环境准备

首先,安装Vertex AI SDK、LangChain及相关依赖:

%pip install --upgrade --quiet google-cloud-aiplatform langchain langchain-core langchain-text-splitters langchain-google-vertexai langchain-community faiss-cpu langchain-chroma pypdf

初始化Vertex AI

import os
import vertexai

PROJECT_ID = "[your-project-id]"  # 替换为你的项目ID
LOCATION = os.environ.get("GOOGLE_CLOUD_REGION", "us-central1")

vertexai.init(project=PROJECT_ID, location=LOCATION)

定义模型

from langchain_google_vertexai import ChatVertexAI, VertexAI, VertexAIEmbeddings

# LLM模型
llm = VertexAI(
    model_name="gemini-2.0-flash",
    verbose=True,
)

# Chat模型
chat = ChatVertexAI(model="gemini-2.0-flash")

# Embedding模型
embeddings = VertexAIEmbeddings("text-embedding-005")

核心组件

LangChain提供了多种模块,可用于创建语言模型应用程序。这些模块可以组合起来创建更复杂的应用程序,也可以单独用于更简单的应用程序。

模型(Models)

模型是LangChain的构建块,提供了与不同类型AI模型的接口。支持的模型类型包括大型语言模型(LLMs)、聊天模型和文本嵌入模型。

提示(Prompts)

提示是用于指导模型的文本。LangChain提供了轻松构建和使用提示的接口,包括提示模板、示例选择器和输出解析器。

提示模板

提示模板是一个对象,帮助基于用户输入、其他非静态信息和固定模板字符串的组合创建提示。可以将其视为Python中的f-string,但用于提示。

template = """
I really want to travel to {location}. What should I do there?

Respond in one short sentence
"""

prompt = PromptTemplate(
    input_variables=["location"],
    template=template,
)

final_prompt = prompt.format(location="Rome")
output = llm.invoke(final_prompt)

记忆(Memory)

记忆提供了在对话过程中存储和检索消息的结构,可以是短期的也可以是长期的。

索引(Indexes)

索引帮助LLMs与文档交互,提供了一种结构化文档的方式。LangChain提供了文档加载器来加载文档,文本分割器将文档分割成更小的块,向量存储将文档存储为嵌入,以及检索器来获取相关文档。

链(Chains)

链允许你按特定顺序组合模块化组件(或其他链)以完成任务。

代理(Agents)

代理是LangChain中一个强大的结构,允许LLMs通过工具与环境通信,观察并决定完成给定任务的最佳行动方案。

实战案例:构建货币分析代理

定义工具

from langchain_core.tools import tool
import requests

@tool
def get_exchange_rate(
    currency_from: str = "USD",
    currency_to: str = "EUR",
    currency_date: str = "latest",
):
    """Retrieves the exchange rate between two currencies on a specified date.

    Args:
        currency_from (str, optional): The base currency. Defaults to "USD".
        currency_to (str, optional): The target currency. Defaults to "EUR".
        currency_date (str, optional): The date for the exchange rate (YYYY-MM-DD).
                                      Use "latest" for the most recent rate. Defaults to "latest".
    """
    response = requests.get(
        f"https://api.frankfurter.app/{currency_date}",
        params={"from": currency_from, "to": currency_to},
    )
    return response.json()

定义状态和节点

from typing import Annotated, TypedDict
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode

# 定义代理状态
class AgentState(TypedDict):
    task: str
    messages: Annotated[list, add_messages]

# 初始化代理内存
memory = MemorySaver()

# 代理节点:查找汇率
def agent_node(state: AgentState):
    messages = state["messages"]
    model_with_tools = model.bind_tools(tools)
    response = model_with_tools.invoke(messages)
    return {"messages": [response]}

# 工具节点:基于API函数定义
tools = [get_exchange_rate]
tool_node = ToolNode(tools)

# 确定是否需要额外的工具调用
def should_continue(state: AgentState):
    messages = state["messages"]
    last_message = messages[-1]
    if last_message.tool_calls:
        return "tools"
    return "review"

# 审查节点:分析和审查结果
REVIEW_PROMPT = """You are a financial expert. Analyze the converted
rates and verify the correctness of the figures.
This is the conversation history so far:
{messages}"""

def review_node(state: AgentState):
    messages = [
        HumanMessage(content=REVIEW_PROMPT.format(messages=state["messages"])),
    ]
    response = model.invoke(messages)
    return {"messages": response}

# 报告节点:生成摘要报告
REPORT_PROMPT = """Construct a summary report for a financial news
reporter covering current exchange rates. Include a table of results
comparing the rates over time. Do not use currency symbols in the
output since they might break the rendering of the output.
This is the conversation history so far:
{messages}"""

def report_node(state: AgentState):
    messages = [
        HumanMessage(content=REPORT_PROMPT.format(messages=state["messages"])),
    ]
    response = model.invoke(messages)
    return {"messages": response}

构建和运行工作流

# 初始化LangGraph工作流,指定代理的状态模式
workflow = StateGraph(AgentState)

# 向工作流添加节点,将每个节点与其对应的函数关联
workflow.add_node("agent", agent_node)
workflow.add_node("tools", tool_node)
workflow.add_node("review", review_node)
workflow.add_node("report", report_node)

# 定义节点之间的执行流程,创建工作流逻辑
workflow.add_edge(START, "agent")
workflow.add_conditional_edges("agent", should_continue, ["tools", "review"])
workflow.add_edge("tools", "agent")
workflow.add_edge("review", "report")
workflow.add_edge("report", END)

# 编译LangGraph工作流,启用基于内存的状态管理
graph = workflow.compile(checkpointer=memory)

# 运行代理
SYSTEM_PROMPT = """Use the tools provided to answer the user's question.
Also look up the exchange rate for all currencies from three months prior
and compare the values."""

USER_PROMPT = """What's the exchange rate from USD to (SEK, EUR, and JPY)
as of today? And how much would $100 USD be worth in those currencies?"""

thread_config = {"configurable": {"thread_id": "1"}}
for state in graph.stream(
    {
        "messages": [
            SystemMessage(content=SYSTEM_PROMPT),
            HumanMessage(content=USER_PROMPT),
        ],
    },
    thread_config,
):
    for node_name, node_output in state.items():
        print(f"Agent Node: {node_name}\n")
        print("Agent Result:")
        print(str(node_output)[:1000])  # 截断输出以显示
    print("\n====================\n")

项目资源

总结

通过Gemini与LangChain的集成,我们可以构建强大的自动化工作流,简化Generative AI项目的开发流程。本文介绍了核心概念、快速开始步骤、核心组件及实战案例,希望能帮助你提升项目开发效率。

如果你觉得本文有帮助,请点赞、收藏并关注我们,获取更多Generative AI项目自动化的实战技巧和最佳实践。下期我们将介绍如何优化提示模板,进一步提升模型性能。

扩展阅读

【免费下载链接】generative-ai Sample code and notebooks for Generative AI on Google Cloud 【免费下载链接】generative-ai 项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值