当前位置: 首页> 文旅> 旅游 > 构建LangChain应用程序的示例代码:1、AutoGPT

构建LangChain应用程序的示例代码:1、AutoGPT

时间:2025/7/13 10:33:36来源:https://blog.csdn.net/wangjiansui/article/details/139357925 浏览次数:0次

AutoGPT

实现https://github.com/Significant-Gravitas/Auto-GPT,但是使用了LangChain的基础组件(大型语言模型(LLMs)、提示模板(PromptTemplates)、向量存储(VectorStores)、嵌入(Embeddings)、工具(Tools))。

设置工具

我们将设置一个带有搜索工具、写文件工具和读文件工具的AutoGPT。

from langchain.agents import Tool
from langchain_community.tools.file_management.read import ReadFileTool
from langchain_community.tools.file_management.write import WriteFileTool
from langchain_community.utilities import SerpAPIWrappersearch = SerpAPIWrapper()
tools = [Tool(name="search",func=search.run,description="当你需要回答有关当前事件的问题时非常有用。你应该提出针对性的问题",),WriteFileTool(),ReadFileTool(),
]

设置内存

这里的内存用于代理的中间步骤。

from langchain.docstore import InMemoryDocstore
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings# 定义你的嵌入模型
embeddings_model = OpenAIEmbeddings()# 初始化向量存储为空
import faissembedding_size = 1536
index = faiss.IndexFlatL2(embedding_size)
vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})

设置模型和AutoGPT

初始化一切!我们将使用ChatOpenAI模型。

from langchain_experimental.autonomous_agents import AutoGPT
from langchain_openai import ChatOpenAIagent = AutoGPT.from_llm_and_tools(ai_name="Tom",ai_role="Assistant",tools=tools,llm=ChatOpenAI(temperature=0),memory=vectorstore.as_retriever(),
)# 设置详细模式为真
agent.chain.verbose = True

运行示例

这里我们将让它为旧金山今天的天气写一份报告。

agent.run(["write a weather report for SF today"])

聊天历史内存

除了保存代理即时步骤的内存外,我们还有一个聊天历史内存。默认情况下,代理将使用’ChatMessageHistory’,并且可以更改。当你想使用不同类型的内存时,例如’FileChatHistoryMemory’,这非常有用。

from langchain_community.chat_message_histories import FileChatMessageHistoryagent = AutoGPT.from_llm_and_tools(ai_name="Tom",ai_role="Assistant",tools=tools,llm=ChatOpenAI(temperature=0),memory=vectorstore.as_retriever(),chat_history_memory=FileChatMessageHistory("chat_history.txt"),
)
关键字:构建LangChain应用程序的示例代码:1、AutoGPT

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: