开源工具自建AI大模型底座

链式调用黏合剂(Langchain)
首先,我们来为你的原型系统搭建一个“调度中心”。这个调度中心将帮助大语言模型(LLM)连接到我们之前学到的各种生态组件,如计划组件、记忆组件和工具组件等等。

目前最主流的做法是采用链式调用。链式调用可以让你的编码更高效,只需少量代码,就能让用户、LLM和组件之间进行复杂的互动。

接下来,我将使用Langchain,基于OpenAI的LLM制作一个简易的ChatGPT。ChatGPT你应该并不陌生,它是一个基于大语言模型的应用程序,可以与人类进行多轮对话。

为了让大语言模型能够实现与人类友好的多轮对话,我们需要额外引入两个组件。

第一个是ConversationBufferMemory,它将帮助LLM记录我们的对话过程。

第二个是ConversationChain,它会帮我们管理整个会话过程,通过调取BufferMemory中的对话信息,让无状态的LLM了解我们的对话上下文。

同时,ConversationChain还会通过补充一些“提示语”,确保LLM知道它在与人类进行交流。

from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

import os
os.environ["OPENAI_API_KEY"] = '...'

llm = OpenAI(temperature=0)
mem = ConversationBufferMemory()

Here it is by default set to "AI"

conversation = ConversationChain(llm=llm, verbose=True, memory=mem)

conversation.predict(input="Hi there!")
Entering new ConversationChain chain…
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

Current conversation:
Human: Hi there!
AI:

Finished chain.

Out[1]:
" Hi there! It’s nice to meet you. How can I help you today?"

在这个例子中,我们直接使用了ConversationChain的封装。以下是它的核心代码,可以看到整个流程非常简单。ConversationChain只是对你的对话内容进行了格式化的封装,告诉了LLM它正在和人类进行对话,并将历史聊天内容提供给LLM,让LLM更好地与用户进行交流。

from langchain.prompts.prompt import PromptTemplate

DEFAULT_TEMPLATE = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. I

关键词: