就有公司域名怎么建设网站,进出口贸易公司取名大全,海外域名网站,wifi管理网站1. 简介
1.1 大语言模型技术栈 大语言模型技术栈由四个主要部分组成#xff1a;
数据预处理流程#xff08;data preprocessing pipeline#xff09;嵌入端点#xff08;embeddings endpoint #xff09;向量存储#xff08;vector store#xff09;LLM 终端#xff…1. 简介
1.1 大语言模型技术栈 大语言模型技术栈由四个主要部分组成
数据预处理流程data preprocessing pipeline嵌入端点embeddings endpoint 向量存储vector storeLLM 终端LLM endpointsLLM 编程框架LLM programming framework
1.2 Langchain的简介和部署
LangChain 就是一个 LLM 编程框架你想开发一个基于 LLM 应用需要什么组件它都有直接使用就行甚至针对常规的应用流程它利用链(LangChain中Chain的由来)这个概念已经内置标准化方案了。
安装langchain包
pip install langchain调用openai接口
pip install openai在代码里调用需要设置openai的api key有两种方法一种是在bashrc的文件中配置另一种直接在调用的函数里设置openai的key值配置
openai的key可以通过https://platform.openai.com/api-keys 官网的连接获取
2. 大模型交互
openai接口代码调用示例
# openai_api_key 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
# Importing modules
from langchain.llms import OpenAI
# Here we are using text-ada-001 but you can change it
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParseroutput_parser StrOutputParser()
prompt ChatPromptTemplate.from_messages([(system, You are world class technical documentation writer.),(user, {input})
])
llm ChatOpenAI(openai_api_key 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)
# chain prompt | llm
# print(prompt:, prompt)
# print(chain:, chain)
chain prompt | llm | output_parser
res chain.invoke(how can langsmith help with testing?)
print(res)输出
contentLangsmith can help with testing in several ways:\n\n1. Test Automation: Langsmith can generate automated test scripts that cover various test scenarios and execute them repeatedly. This helps in reducing manual effort and time required for testing.\n\n2. Test Data Generation: Langsmith can generate test data that covers a wide range of input values and boundary conditions. This helps in testing the robustness and reliability of the system.\n\n3. Test Case Generation: Langsmith can generate test cases based on the specifications or requirements provided. These test cases can cover various combinations of inputs and expected outputs, ensuring comprehensive testing.\n\n4. Regression Testing: Langsmith can automate the execution of regression tests, which are performed to ensure that existing functionality is not impacted by any new changes or updates.\n\n5. Performance Testing: Langsmith can generate test scripts to simulate high loads and stress on the system, enabling performance testing and identifying potential bottlenecks or performance issues.\n\n6. Security Testing: Langsmith can help in identifying security vulnerabilities by generating test cases that simulate different attack scenarios, such as SQL injection or cross-site scripting.\n\nOverall, Langsmiths capabilities in generating automated test scripts, test data, test cases, and supporting various types of testing can significantly improve the efficiency and effectiveness of the testing process.”3. Chain
3.1 LLM Chain
最基本的链为 LLMChain由 PromptTemplate、LLM 和 OutputParser 组成。LLM 的输出一般为文本OutputParser 用于让 LLM 结构化输出并进行结果解析方便后续的调用。 from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
# from azure_chat_llm import llm
from langchain.chat_models import ChatOpenAI#output parser
keyword_schema ResponseSchema(namekeyword, description评论的关键词列表)
emotion_schema ResponseSchema(nameemotion, description评论的情绪正向为1中性为0负向为-1)
response_schemas [keyword_schema, emotion_schema]
output_parser StructuredOutputParser.from_response_schemas(response_schemas)
format_instructions output_parser.get_format_instructions()#prompt template
prompt_template_txt
作为资深客服请针对 和 中间的文本识别其中的关键词以及包含的情绪是正向、负向还是中性。{text}
RESPONSE:
{format_instructions}
prompt PromptTemplate(templateprompt_template_txt, input_variables[text],partial_variables{format_instructions: format_instructions})
llm ChatOpenAI(openai_api_key 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)
#llmchain
llm_chain LLMChain(promptprompt, llmllm)
comment 京东物流没的说速度态度都是杠杠滴这款路由器颜值贼高怎么说呢就是泰裤辣这线条这质感这速度嘎嘎快以后妈妈再也不用担心家里的网速了
result llm_chain.run(comment)
data output_parser.parse(result)
print(ftype{type(data)}, keyword{data[keyword]}, emotion{data[emotion]})3.2 Sequential Chain
SequentialChains 是按预定义顺序执行的链。SimpleSequentialChain 为顺序链的最简单形式其中每个步骤都有一个单一的输入 / 输出一个步骤的输出是下一个步骤的输入。SequentialChain 为顺序链更通用的形式允许多个输入 / 输出。
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.chains import SimpleSequentialChain
from langchain.chat_models import ChatOpenAIllm ChatOpenAI(openai_api_key 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)
first_prompt PromptTemplate.from_template(翻译下面的内容到中文:\n\n{content}
)
# chain 1: 输入Review 输出 英文的 Review
chain_trans LLMChain(llmllm, promptfirst_prompt, output_keycontent_zh)second_prompt PromptTemplate.from_template(一句话总结下面的内容:\n\n{content_zh}
)chain_summary LLMChain(llmllm, promptsecond_prompt)
overall_simple_chain SimpleSequentialChain(chains[chain_trans, chain_summary],verboseTrue)
content In a blog post authored back in 2011, Marc Andreessen warned that, “Software is eating the world.” Over a decade later, we are witnessing the emergence of a new type of technology that’s consuming the world with even greater voracity: generative artificial intelligence (AI). This innovative AI includes a unique class of large language models (LLM), derived from a decade of groundbreaking research, that are capable of out-performing humans at certain tasks. And you don’t have to have a PhD in machine learning to build with LLMs—developers are already building software with LLMs with basic HTTP requests and natural language prompts.
In this article, we’ll tell the story of GitHub’s work with LLMs to help other developers learn how to best make use of this technology. This post consists of two main sections: the first will describe at a high level how LLMs function and how to build LLM-based applications. The second will dig into an important example of an LLM-based application: GitHub Copilot code completions.
Others have done an impressive job of cataloging our work from the outside. Now, we’re excited to share some of the thought processes that have led to the ongoing success of GitHub Copilot.result overall_simple_chain.run(content)
print(fresult{result})3.3 RouterChain 4. 外部文档检索
索引和外部数据进行集成用于从外部数据获取答案。
通过 Document Loaders 加载各种不同类型的数据源
LangChain 通过 Loader 加载外部的文档转化为标准的 Document 类型。Document 类型主要包含两个属性page_content 包含该文档的内容。meta_data 为文档相关的描述性数据类似文档所在的路径等。
通过 Text Splitters 进行文本语义分割
LLM 一般都会限制上下文窗口的大小有 4k、16k、32k 等。针对大文本就需要进行文本分割常用的文本分割器为 RecursiveCharacterTextSplitter可以通过 separators 指定分隔符。其先通过第一个分隔符进行分割不满足大小的情况下迭代分割。
著作权归作者所有。商业转载请联系作者获得授权非商业转载请注明出处。
通过 Vectorstore 进行非结构化数据的向量存储
通过 Text Embedding models将文本转为向量可以进行语义搜索在向量空间中找到最相似的文本片段。目前支持常用的向量存储有 Faiss、Chroma 等。
通过 Retriever 进行文档数据检索
Retriever 接口用于根据非结构化的查询获取文档一般情况下是文档存储在向量数据库中。可以调用 get_relevant_documents 方法来检索与查询相关的文档。 from langchain import FAISS
from langchain.document_loaders import WebBaseLoader
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter#通过 Document Loaders 加载各种不同类型的数据源
#LangChain 通过 Loader 加载外部的文档转化为标准的 Document 类型。
# Document 类型主要包含两个属性page_content 包含该文档的内容。meta_data 为文档相关的描述性数据类似文档所在的路径等。
loader WebBaseLoader(https://in.m.jd.com/help/app/register_info.html)
data loader.load()#针对大文本就需要进行文本分割常用的文本分割器为 RecursiveCharacterTextSplitter可以通过 separators 指定分隔符。
# 其先通过第一个分隔符进行分割不满足大小的情况下迭代分割。
text_splitter RecursiveCharacterTextSplitter.from_tiktoken_encoder(model_namegpt-3.5-turbo,allowed_specialall,separators[\n\n, \n, 。, ],chunk_size800,chunk_overlap0
)
docs text_splitter.split_documents(data)
#通过cache_folder设置自己的本地模型路径
#embeddings HuggingFaceEmbeddings(model_nametext2vec-base-chinese, cache_foldermodels)#通过 Text Embedding models将文本转为向量可以进行语义搜索在向量空间中找到最相似的文本片段。
# 目前支持常用的向量存储有 Faiss、Chroma 等。
embeddings HuggingFaceEmbeddings()vectorstore FAISS.from_documents(docs, embeddings)#Retriever 接口用于根据非结构化的查询获取文档一般情况下是文档存储在向量数据库中。
# 可以调用 get_relevant_documents 方法来检索与查询相关的文档。
result vectorstore.as_retriever().get_relevant_documents(用户注册资格)
print(result)
print(len(result))5. 外部文档交互
5.1 Stuff
StuffDocumentsChain 这种链最简单直接是将所有获取到的文档作为 context 放入到 Prompt 中传递到 LLM 获取答案
这种方式可以完整的保留上下文调用 LLM 的次数也比较少建议能使用 stuff 的就使用这种方式。其适合文档拆分的比较小一次获取文档比较少的场景不然容易超过 token 的限制。 5.2 Refine
RefineDocumentsChain 是通过迭代更新的方式获取答案。先处理第一个文档作为 context 传递给 llm获取中间结果 intermediate answer。然后将第一个文档的中间结果以及第二个文档发给 llm 进行处理后续的文档类似处理。
Refine 这种方式能部分保留上下文以及 token 的使用能控制在一定范围。 5.3 MapReduce
MapReduceDocumentsChain 先通过 LLM 对每个 document 进行处理然后将所有文档的答案在通过 LLM 进行合并处理得到最终的结果。
MapReduce 的方式将每个 document 单独处理可以并发进行调用。但是每个文档之间缺少上下文。 5.4 MapRerank
MapRerankDocumentsChain 和 MapReduceDocumentsChain 类似先通过 LLM 对每个 document 进行处理每个答案都会返回一个 score最后选择 score 最高的答案。
MapRerank 和 MapReduce 类似会大批量的调用 LLM每个 document 之间是独立处理 6. Memory
正常情况下 Chain 无状态的每次交互都是独立的无法知道之前历史交互的信息。LangChain 使用 Memory 组件保存和管理历史消息这样可以跨多轮进行对话在当前会话中保留历史会话的上下文。Memory 组件支持多种存储介质可以与 Monogo、Redis、SQLite 等进行集成以及简单直接形式就是 Buffer Memory。常用的 Buffer Memory 有:
ConversationSummaryMemory 以摘要的信息保存记录ConversationBufferWindowMemory以原始形式保存最新的 n 条记录ConversationBufferMemory以原始形式保存所有记录
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemoryfrom langchain.chat_models import ChatOpenAIllm ChatOpenAI(openai_api_key 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)memory ConversationBufferMemory()
conversation ConversationChain(llmllm, memorymemory, verboseTrue)
print(conversation.prompt)
print(conversation.predict(input我的姓名是tiger))
print(conversation.predict(input11?))
print(conversation.predict(input我的姓名是什么))7. Agents
传统使用 LLM需要给定 Prompt 一步一步的达成目标通过 Agent 是给定目标其会自动规划并达到目标。
目前这个领域特别活跃诞生了类似 AutoGPT、BabyAGI、AgentGPT 等一堆优秀的项目。
目前的大模型一般都存在知识过时、逻辑计算能力低等问题通过 Agent 访问工具可以去解决这些问题。
Agent代理负责调用 LLM 以及决定下一步的 Action。其中 LLM 的 prompt 必须包含 agent_scratchpad 变量记录执行的中间过程Tools工具Agent 可以调用的方法。LangChain 已有很多内置的工具也可以自定义工具。注意 Tools 的 description 属性LLM 会通过描述决定是否使用该工具。ToolKits工具集为特定目的的工具集合。类似 Office365、Gmail 工具集等Agent ExecutorAgent 执行器负责进行实际的执行。
from langchain.agents import load_tools, initialize_agent, tool
from langchain.agents.agent_types import AgentType
from datetime import date
from langchain.chat_models import ChatOpenAIllm ChatOpenAI(openai_api_key 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)#有多种方式可以自定义 Tool最简单的方式是通过 tool 装饰器将一个函数转为 Tool。
# 注意函数必须得有 docString其为 Tool 的描述。
tool
def time(text: str) - str:返回今天的日期。return str(date.today())tools load_tools([llm-math], llmllm)
tools.append(time)
#一般通过 initialize_agent 函数进行 Agent 的初始化除了 llm、tools 等参数还需要指定 AgentType。
#该 Agent 为一个 zero-shot-react-description 类型的 Agent其中 zero-shot 表明只考虑当前的操作不会记录以及参考之前的操作。react 表明通过 ReAct 框架进行推理description 表明通过工具的 description 进行是否使用的决策。
agent_math initialize_agent(agentAgentType.ZERO_SHOT_REACT_DESCRIPTION,toolstools,llmllm,verboseTrue)
print(agent_math(计算45 * 54))
print(agent_math(今天是哪天))
#可以通过 agent.agent.llm_chain.prompt.template 方法获取其推理决策所使用的模板。
print(agent_math.agent.llm_chain.prompt.template)参考文献 【知乎】langchain到底该怎么使用大家在项目中实践有成功的案例吗?https://www.zhihu.com/question/609483833/answer/3146379316?utm_psn1725522909580394496 【知乎】小白入门大模型LangChain https://zhuanlan.zhihu.com/p/656646499