首页 >后端开发 >Python教程 >使用 LangChain 和 OpenAI 构建智能代理:开发人员指南

使用 LangChain 和 OpenAI 构建智能代理:开发人员指南

Mary-Kate Olsen
Mary-Kate Olsen原创
2025-01-20 16:22:16163浏览

Building Intelligent Agents with LangChain and OpenAI: A Developer

人工智能的兴起使开发人员能够将智能功能集成到日常工作流程中。 一个关键方法涉及创建将推理与行动相结合的自主代理。本文演示了如何使用 LangChain、OpenAI 的 GPT-4 和 LangChain 的实验功能构建此类代理。这些代理将执行 Python 代码、与 CSV 文件交互并处理复杂的查询。让我们开始吧!


为什么选择浪链?

LangChain 擅长作为利用语言模型开发应用程序的框架。它的优势在于创建模块化、可重用的组件(例如代理),能够:

  • 执行Python代码。
  • 分析数据文件并与之交互。
  • 使用工具进行推理和决策。

将LangChain与OpenAI的GPT-4相结合,可以创建适合特定需求的代理,包括数据分析和代码调试。


入门:环境设置

编码之前,请确保您的环境已正确配置:

  • 安装 Python 库:
<code class="language-bash">pip install langchain langchain-openai python-dotenv</code>
  • 创建 .env 文件:安全存储您的 OpenAI API 密钥:
<code>OPENAI_API_KEY=your_api_key_here</code>

构建 Python 执行代理

一个重要的代理功能是执行 Python 代码。这是使用 LangChain 的 PythonREPLTool 来实现的。让我们定义代理:

教学设计

代理的操作依赖于一组指令。 提示如下:

<code>instruction = """
You are an agent tasked with writing and executing Python code to answer questions.
You have access to a Python REPL for code execution.
Debug your code if errors occur and retry.
Use only the code's output to answer.
If code cannot answer the question, respond with 'I don't know'.
"""</code>

代理设置

LangChain的REACT框架将构建这个代理:

<code class="language-python">from langchain import hub
from langchain_openai import ChatOpenAI
from langchain_experimental.tools import PythonREPLTool
from langchain.agents import create_react_agent, AgentExecutor

base_prompt = hub.pull("langchain-ai/react-agent-template")
prompt = base_prompt.partial(instructions=instruction)

tools = [PythonREPLTool()]
python_agent = create_react_agent(
    prompt=prompt,
    llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),
    tools=tools,
)
python_executor = AgentExecutor(agent=python_agent, tools=tools, verbose=True)</code>

该代理执行 Python 代码并返回结果。


向代理添加 CSV 分析

数据分析是一项常见的 AI 代理任务。 集成LangChain的create_csv_agent允许我们的代理查询和处理CSV文件中的数据。

CSV 代理设置

以下是添加 CSV 功能的方法:

<code class="language-python">from langchain_experimental.agents.agent_toolkits import create_csv_agent

csv_agent = create_csv_agent(
    llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),
    path="episode-info.csv",
    verbose=True,
    allow_dangerous_code=True,
)</code>

该代理回答有关 episode-info.csv 的问题,例如行/列计数以及剧集最多的季节。


组合工具实现统一代理

为了实现多功能性,我们将 Python 执行和 CSV 分析结合到一个代理中,允许根据任务无缝切换工具。

统一代理定义

<code class="language-python">from langchain.agents import Tool

def python_executor_wrapper(prompt: str):
    python_executor.invoke({"input": prompt})

tools = [
    Tool(
        name="Python Agent",
        func=python_executor_wrapper,
        description="""
        Transforms natural language to Python code and executes it.
        Does not accept code as input.
        """
    ),
    Tool(
        name="CSV Agent",
        func=csv_agent.invoke,
        description="""
        Answers questions about episode-info.csv using pandas calculations.
        """
    ),
]

grant_agent = create_react_agent(
    prompt=base_prompt.partial(instructions=""),
    llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),
    tools=tools,
)
grant_agent_executor = AgentExecutor(agent=grant_agent, tools=tools, verbose=True)</code>

该代理处理 Python 逻辑和 CSV 数据分析。


实例:电视节目剧集分析

让我们用episode-info.csv测试统一代理:

<code class="language-bash">pip install langchain langchain-openai python-dotenv</code>

代理利用 pandas 分析 CSV 并返回剧集最多的季节。


后续步骤和结论

  • 尝试更多工具和数据集。
  • 探索 LangChain 的文档以了解更高级的代理创建。

LangChain可以创建高度定制的智能代理,简化复杂的工作流程。 借助 Python REPL 和 CSV 代理等工具,从自动化数据分析到代码调试等,可能性是巨大的。从今天开始构建您的智能代理!

以上是使用 LangChain 和 OpenAI 构建智能代理:开发人员指南的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn