該教程展示了使用Langchain建立多功能對話AI代理,該代理是將大型語言模型(LLM)與外部工具和API集成的強大框架。該代理可以執行各種任務,從生成隨機數,提供哲學沉思到從網頁中動態檢索和處理信息。預先構建和自定義工具的組合可以實時,上下文感知和內容豐富的響應。
*本文是***數據科學博客馬拉鬆的一部分。
Tool
類進行網絡刮擦Langchain,Openai和Duckduckgo的協同作用允許進行精緻的對話AI。 Openai的LLM提供了自然語言處理,而DuckDuckgo則提供以隱私為中心的搜索API。這種組合使AI能夠生成上下文相關的響應並檢索實時數據,從而增強其適應性和準確性。這個功能強大的工具包非常適合創建能夠處理各種用戶查詢的智能聊天機器人或虛擬助理。
首先使用PIP安裝所需的Python軟件包:
<code>!pip -q install langchain==0.3.4 openai pip install langchain !pip -q install duckduckgo-search</code>
驗證Langchain的安裝:
<code>!pip show langchain</code>
獲取您的OpenAI API密鑰並將其設置為環境變量:
<code>import os os.environ["OPENAI_API_KEY"] = "your_openai_key_here"</code>
用實際鍵替換"your_openai_key_here"
。這對於與GPT-3.5-Turbo模型相互作用至關重要。
使用Langchain建立與OpenAI模型的連接:
<code>from langchain import OpenAI from langchain.chat_models import ChatOpenAI from langchain.chains.conversation.memory import ConversationBufferWindowMemory # Configure the GPT-4o LLM turbo_llm = ChatOpenAI( temperature=0, model_name='gpt-4o' )</code>
低溫(溫度= 0)可確保一致的響應。
通過添加DuckDuckgo搜索工具來增強代理的功能:
<code>from langchain.tools import DuckDuckGoSearchTool from langchain.agents import Tool from langchain.tools import BaseTool search = DuckDuckGoSearchTool() # Define the tool tools = [ Tool( name = "search", func=search.run, description="Best for questions about current events. Use precise queries." ) ]</code>
該工具被描述為當前事件的理想選擇,被添加到代理商的工具包中。
使用自定義工具擴展代理的功能:
此功能對生活意義問題提供了有趣的回應:
<code>def meaning_of_life(input=""): return 'The meaning of life is 42 (approximately!)' life_tool = Tool( name='Meaning of Life', func= meaning_of_life, description="Use for questions about the meaning of life. Input: 'MOL'" )</code>
該工具在0到5之間生成隨機整數:
<code>import random def random_num(input=""): return random.randint(0,5) random_tool = Tool( name='Random number', func= random_num, description="Use to get a random number. Input: 'random'" )</code>
使用自定義工具創建對話代理可以進行高度量身定制的交互。
導入initialize_agent
並定義工具:
<code>from langchain.agents import initialize_agent tools = [search, random_tool, life_tool]</code>
使用ConversationBufferWindowMemory
實現內存:
<code>from langchain.chains.conversation.memory import ConversationBufferWindowMemory memory = ConversationBufferWindowMemory( memory_key='chat_history', k=3, return_messages=True )</code>
這使經紀人可以回憶起最近的對話轉彎(最多3)。
初始化代理:
<code>conversational_agent = initialize_agent( agent='chat-conversational-react-description', tools=tools, llm=turbo_llm, verbose=True, max_iterations=3, early_stopping_method='generate', memory=memory )</code>
參數指定代理類型,工具,LLM,冗長,迭代限制,早期停止和內存。
與代理互動:
<code>conversational_agent("What time is it in London?") conversational_agent("Can you give me a random number?") conversational_agent("What is the meaning of life?")</code>
通過調整系統提示來完善代理的行為:
<code># system prompt conversational_agent.agent.llm_chain.prompt.messages[0].prompt.template</code>
<code>fixed_prompt = '''Assistant is a large language model... [modified prompt instructing the agent to use tools appropriately]'''</code>
應用修改的提示:
<code>conversational_agent.agent.llm_chain.prompt.messages[0].prompt.template = fixed_prompt</code>
重新測試代理。
Tool
類進行網絡刮擦創建一個自定義工具以從網頁中提取純文本:
<code>from bs4 import BeautifulSoup import requests from langchain.agents import Tool def stripped_webpage(webpage): # ... (function to fetch and clean webpage text) ... web_scraper_tool = Tool( name='Web Scraper', func=stripped_webpage, description="Fetches and cleans webpage text (limited to 4000 characters)." )</code>
將此工具集成到您的代理中。
WebPageTool
類一個更強大的解決方案涉及創建自定義WebPageTool
類:
來自langchain.tools進口基座 來自BS4進口美麗的小組 導入請求 類WebPagetool(basetool): #...(類似於原始響應中的類定義)...
使用新工具和更新的系統提示重新初始化代理。測試示例:
convertinational_agent.run(“ https://techcrunch.com/?今天是否有有關會所的文章”) convertitation_agent.run(“ www.cbsnews.com/上的頂級故事是什麼?”)
該教程展示了使用Langchain建立高度適應性的對話劑。模塊化設計可輕鬆擴展和自定義。該代理展示了將AI與實時數據訪問相結合的功能。
(與原始響應相同的常見問題解答,改寫以獲得更好的流動和簡潔性。)
以上是在Langchain中設置自定義工具和代理的詳細內容。更多資訊請關注PHP中文網其他相關文章!