Langchain的90k GitHub星星是它所需的所有信譽 - 現在,它是構建基於LLM的應用程序的最熱門框架。它的全面工具和組件集使您可以使用幾乎所有LLM構建端到端的AI解決方案。
>也許是蘭班鏈能力的核心是Langchain代理商。它們是可以執行任務,決策並與其他工具和API互動的自主或半自治工具。它們代表了與LLMS自動化複雜工作流程的重大飛躍。
>
在本文中,您將學習如何在當今的聊天應用程序(例如ChatGpt)中構建自己無法嚴格執行任務的蘭格鏈代理。>在進入任何內容之前,讓我們為教程設置環境。
>安裝Langchain的軟件包和其他一些必要的庫:
>將新創建的conda環境添加到jupyter中,作為內核:
$ conda create -n langchain python=3.9 -y $ conda activate langchain
$ pip install langchain langchain_openai langchain_community langgraph ipykernel python-dotenv
測試一切都可以通過查詢OpenAI的GPT-3.5(默認語言模型)來正確工作:
$ ipython kernel install --user --name=langchain
$ touch .env $ vim .env # Paste your OPENAI key
OPENAI_API_KEY='YOUR_KEY_HERE'
什麼是Langchain代理?
>讓我們花一些時間思考代理框架。具體而言,我們將考慮它與傳統的鏈條範式的不同以及代理的組成部分是什麼。了解為什麼我們需要選擇一種構建應用程序的新方法將為我們編寫代碼做好準備。import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv('OPENAI_API_KEY')
定義特徵的特徵是他們選擇最佳的行動順序解決問題的能力。
from langchain_openai import OpenAI llm = OpenAI(openai_api_key=api_key) question = "Is Messi the best footballer of all time?" output = llm.invoke(question) print(output[:75])
There is no definitive answer to this question, as it is subjective and de
天氣API
>圖像識別模型
語言模型(文本生成)
鏈2:基於天氣的自行車路線Suggester
>致電天氣API
>了解用戶的查詢或問題(通過語言模型通過自然語言)
評估哪些工具與問題(推理)>為每種唯一情況創建自定義工作流
>根據特定上下文和用戶需求
>創建Langchain代理有很多活動部件。第一個也是最明顯的是語言模型。
>語言模型,例如OpenAI的GPT-3.5 Turbo,拿起並生成字符串。它們通常年齡較大,最好回答單個用戶查詢。
>$ conda create -n langchain python=3.9 -y $ conda activate langchain
提出不同的方式,聊天模型允許我們以自然語言進行對話。在上面的示例中,我們正在使用系統消息,然後是用戶查詢的GPT-4O-MINI初始化。請注意使用SystemMessage和HumanMessage類。
輸出是一個消息對象,這是聊天模型的預期行為:
$ pip install langchain langchain_openai langchain_community langgraph ipykernel python-dotenv
$ ipython kernel install --user --name=langchain
$ touch .env $ vim .env # Paste your OPENAI key
OPENAI_API_KEY='YOUR_KEY_HERE'
import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv('OPENAI_API_KEY')
from langchain_openai import OpenAI llm = OpenAI(openai_api_key=api_key) question = "Is Messi the best footballer of all time?" output = llm.invoke(question) print(output[:75])
>提示模板
>在Langchain中,有許多類型的提示模板,其中最基本的模板是提示模板類。它可以與語言(純文本)模型一起使用:
There is no definitive answer to this question, as it is subjective and de
from langchain_openai import OpenAI llm = OpenAI(api_key=api_key, model="gpt-3.5-turbo-instruct") question = "What is special about the number 73?" output = llm.invoke(question) print(output[:100])
>呼叫.invoke()將顯示您的提示將如何傳遞給模型。
將此提示模板傳遞給語言模型需要我們使用管道操作員鏈接它:
>管道操作員(|)是Langchain Expression語言(LCEL)的一部分,旨在鏈多個Langchain組件和工具。
1. Prime Number: 73 is a prime number, which means it is only divisible by 1 and itself. This make
from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage, AIMessageChunk, SystemMessage # Initialize the model chat_model = ChatOpenAI(api_key=api_key, model='gpt-4o-mini') # Write the messages messages = [SystemMessage(content='You are a grumpy pirate.'), HumanMessage(content="What's up?")] output = chat_model.invoke(messages)
>在Langchain對像上使用管道操作員時,您可以創建一個RunnableSequence類的實例。可運行的序列代表支持.invoke()方法的對象鏈,例如提示模板和語言/聊天模型。
type(output)
langchain_core.messages.ai.AIMessage
>我們提到聊天模型需要一系列消息作為輸入。初始輸入通常是一個系統提示,告訴聊天模型如何表現。因此,使用ChatPromptTemplate類,我們可以輕鬆地創建具有不同個性的聊天模型:
print(output.content)
>準備好後,我們可以使用相同的管道操作員創建具有不同行為的聊天模型:
$ conda create -n langchain python=3.9 -y $ conda activate langchain
$ pip install langchain langchain_openai langchain_community langgraph ipykernel python-dotenv
>在上一節中,我們提到代理可以選擇可以使用的工具組合來解決特定問題,而LLMS作為引擎蓋下的推理引擎。 Langchain提供了與數十個流行的API和服務的集成,使代理商與世界其他地區互動。其中大多數都在langchain_community軟件包下可用,而有些則在langchain_core內部。
> 例如,您可以使用Arxiv工具在各種主題上檢索紙張摘要::
$ ipython kernel install --user --name=langchain
$ touch .env $ vim .env # Paste your OPENAI key
OPENAI_API_KEY='YOUR_KEY_HERE'
import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv('OPENAI_API_KEY')
from langchain_openai import OpenAI llm = OpenAI(openai_api_key=api_key) question = "Is Messi the best footballer of all time?" output = llm.invoke(question) print(output[:75])
There is no definitive answer to this question, as it is subjective and de
from langchain_openai import OpenAI llm = OpenAI(api_key=api_key, model="gpt-3.5-turbo-instruct") question = "What is special about the number 73?" output = llm.invoke(question) print(output[:100])
1. Prime Number: 73 is a prime number, which means it is only divisible by 1 and itself. This make
>逐步的工作流程如何構建Langchain Agents
from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage, AIMessageChunk, SystemMessage # Initialize the model chat_model = ChatOpenAI(api_key=api_key, model='gpt-4o-mini') # Write the messages messages = [SystemMessage(content='You are a grumpy pirate.'), HumanMessage(content="What's up?")] output = chat_model.invoke(messages)
type(output)
>讓我們開始。請記住要查看如何設置本文開頭涵蓋的環境。
配置我們的環境後的第一步是定義我們將提供給代理商的工具。讓我們導入它們:
我們正在導入五個類:
>> wikipediaqueryrun:要生成wikipedia頁面摘要
langchain_core.messages.ai.AIMessage
> YouTubesearchTool:要在主題上搜索YouTube視頻
>讓我們初始化它們,從Wikipedia工具開始:
$ conda create -n langchain python=3.9 -y $ conda activate langchain
$ pip install langchain langchain_openai langchain_community langgraph ipykernel python-dotenv
$ ipython kernel install --user --name=langchain
$ touch .env $ vim .env # Paste your OPENAI key
OPENAI_API_KEY='YOUR_KEY_HERE'
現在,我們將這些工具放入列表中:
import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv('OPENAI_API_KEY')
讓我們嘗試用簡單的消息調用模型:
from langchain_openai import OpenAI llm = OpenAI(openai_api_key=api_key) question = "Is Messi the best footballer of all time?" output = llm.invoke(question) print(output[:75])
There is no definitive answer to this question, as it is subjective and de
from langchain_openai import OpenAI llm = OpenAI(api_key=api_key, model="gpt-3.5-turbo-instruct") question = "What is special about the number 73?" output = llm.invoke(question) print(output[:100])
>我們可以看到沒有文本輸出,但是提到了Openai的Dalle。該工具尚未調用;該模型只是建議我們使用它。要實際稱呼它 - 要採取行動,我們需要創建一個代理。
1. Prime Number: 73 is a prime number, which means it is only divisible by 1 and itself. This make
from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage, AIMessageChunk, SystemMessage # Initialize the model chat_model = ChatOpenAI(api_key=api_key, model='gpt-4o-mini') # Write the messages messages = [SystemMessage(content='You are a grumpy pirate.'), HumanMessage(content="What's up?")] output = chat_model.invoke(messages)
定義模型和工具後,我們創建代理。 Langchain提供了從其langgraph軟件包中的高級create_react_agent()函數接口,以快速創建React(原因和ACT)代理:
type(output)
>
langchain_core.messages.ai.AIMessage
print(output.content)
>
Arrr, not much but the sound of waves and the creakin' of me ship. What do ye want? Make it quick, I've got treasure to hunt and rum to drink!
output.dict()
>讓我們快速創建一個函數,以模塊化我們採取的最後一步:
{'content': "Arrr, not much but the sound of waves and the creakin' of me ship. What do ye want? Make it quick, I've got treasure to hunt and rum to drink!", 'additional_kwargs': {}, 'response_metadata': {'token_usage': {'completion_tokens': 38, 'prompt_tokens': 21, 'total_tokens': 59}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_48196bc67a', 'finish_reason': 'stop', 'logprobs': None}, 'type': 'ai', 'name': None, 'id': 'run-fde829bf-8f5f-4926-a1ed-ab53609ce03a-0', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': {'input_tokens': 21, 'output_tokens': 38, 'total_tokens': 59}}
from langchain_core.prompts import PromptTemplate query_template = "Tell me about {book_name} by {author}." prompt = PromptTemplate(input_variables=["book_name", "author"], template=query_template) prompt.invoke({"book_name": "Song of Ice and Fire", "author": "GRRM"})
現在,讓我們使用有關代理如何行為的詳細說明更新系統提示
>讓我們通過新系統提示重新創建我們的代理:
StringPromptValue(text='Tell me about Song of Ice and Fire by GRRM.')
from langchain_openai import OpenAI llm = OpenAI(api_key=api_key) # Create a chain chain = prompt | llm # Invoke the chain output = chain.invoke({"book_name": "Deathly Hallows", "author": "J.K. Rowling"}) print(output[:100])
4。將內存添加到代理
Deathly Hallows is the seventh and final book in the popular Harry Potter series, written by J.K. R
type(chain)
$ conda create -n langchain python=3.9 -y $ conda activate langchain
$ pip install langchain langchain_openai langchain_community langgraph ipykernel python-dotenv
>將聊天消息歷史記錄添加到代理的最簡單方法是使用langgraph的sqlitesaver類:
$ ipython kernel install --user --name=langchain
>我們使用SQLITESAVER類的.from_conn_string()方法初始化存儲器,該方法創建了一個數據庫文件。然後,我們將存儲器傳遞到Create_react_agent()函數的Checkpointer參數。
>現在,我們需要創建一個配置字典:
$ touch .env $ vim .env # Paste your OPENAI key
>
OPENAI_API_KEY='YOUR_KEY_HERE'
import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv('OPENAI_API_KEY')
>
from langchain_openai import OpenAI llm = OpenAI(openai_api_key=api_key) question = "Is Messi the best footballer of all time?" output = llm.invoke(question) print(output[:75])
There is no definitive answer to this question, as it is subjective and de
未來的趨勢和發展
純蘭鏈代理可以開始使用,但是它們需要更多的代碼來構建相同的代理,而不是在langgraph中。另外,在某個點之後,AgensExecutor框架將無法提供Langgraph來構建複雜多工具代理的靈活性。
這就是為什麼現在是騎波浪並直接從langgraph開始的好時機。>
>我們強烈建議也開始使用Langsmith,這已成為Langchain生態系統的核心部分,用於建立生產級LLM應用程序。以下是其主要好處:
調試:Langsmith提供了代理執行的詳細痕跡,使識別和解決問題變得更容易。
>設置環境變量。
以下是一些相關資源來增加您的蘭鏈:
>使用Langchain課程開發LLM應用程序
> langchain
以上是構建Langchain代理以在Python中自動化任務的詳細內容。更多資訊請關注PHP中文網其他相關文章!