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

Building Intelligent Agents with LangChain and OpenAI: A Developer

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


为什么选择浪链?

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

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

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


入门:环境设置

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

  • 安装 Python 库:
pip install langchain langchain-openai python-dotenv
  • 创建 .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框架将构建这个代理:

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)

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


向代理添加 CSV 分析

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

CSV 代理设置

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

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,
)

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


组合工具实现统一代理

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

统一代理定义

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)

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


实例:电视节目剧集分析

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

pip install langchain langchain-openai python-dotenv

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


后续步骤和结论

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

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

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

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何将元素附加到Python列表中?您如何将元素附加到Python列表中?May 04, 2025 am 12:17 AM

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

您如何创建Python列表?举一个例子。您如何创建Python列表?举一个例子。May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

讨论有效存储和数值数据的处理至关重要的实际用例。讨论有效存储和数值数据的处理至关重要的实际用例。May 04, 2025 am 12:11 AM

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。 1)在金融中,使用内存映射文件和NumPy库可显着提升数据处理速度。 2)科研领域,HDF5文件优化数据存储和检索。 3)医疗中,数据库优化技术如索引和分区提高数据查询性能。 4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显着提升系统性能和可扩展性。

您如何创建Python数组?举一个例子。您如何创建Python数组?举一个例子。May 04, 2025 am 12:10 AM

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

使用Shebang系列指定Python解释器有哪些替代方法?使用Shebang系列指定Python解释器有哪些替代方法?May 04, 2025 am 12:07 AM

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。