搜尋
首頁後端開發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
為什麼數組通常比存儲數值數據列表更高?為什麼數組通常比存儲數值數據列表更高?May 05, 2025 am 12:15 AM

ArraySareAryallyMoremory-Moremory-forigationDataDatueTotheIrfixed-SizenatureAntatureAntatureAndirectMemoryAccess.1)arraysStorelelementsInAcontiguxufulock,ReducingOveringOverheadHeadefromenterSormetormetAdata.2)列表,通常

如何將Python列表轉換為Python陣列?如何將Python列表轉換為Python陣列?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

您可以將不同的數據類型存儲在同一Python列表中嗎?舉一個例子。您可以將不同的數據類型存儲在同一Python列表中嗎?舉一個例子。May 05, 2025 am 12:10 AM

Python列表可以存儲不同類型的數據。示例列表包含整數、字符串、浮點數、布爾值、嵌套列表和字典。列表的靈活性在數據處理和原型設計中很有價值,但需謹慎使用以確保代碼的可讀性和可維護性。

Python中的數組和列表之間有什麼區別?Python中的數組和列表之間有什麼區別?May 05, 2025 am 12:06 AM

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

通常使用哪種模塊在Python中創建數組?通常使用哪種模塊在Python中創建數組?May 05, 2025 am 12:02 AM

theSostCommonlyusedModuleForCreatingArraysInpyThonisnumpy.1)NumpyProvidEseffitedToolsForarrayOperations,Idealfornumericaldata.2)arraysCanbeCreatedDusingsnp.Array()for1dand2Structures.3)

您如何將元素附加到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,可以显著提升系统性能和可扩展性。

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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。