分類目錄:《大模型從入門到應(yīng)用》總目錄
LangChain系列文章:
- 基礎(chǔ)知識
- 快速入門
- 安裝與環(huán)境配置
- 鏈(Chains)、代理(Agent:)和記憶(Memory)
- 快速開發(fā)聊天模型
- 模型(Models)
- 基礎(chǔ)知識
- 大型語言模型(LLMs)
- 基礎(chǔ)知識
- LLM的異步API、自定義LLM包裝器、虛假LLM和人類輸入LLM(Human Input LLM)
- 緩存LLM的調(diào)用結(jié)果
- 加載與保存LLM類、流式傳輸LLM與Chat Model響應(yīng)和跟蹤tokens使用情況
- 聊天模型(Chat Models)
- 基礎(chǔ)知識
- 使用少量示例和響應(yīng)流式傳輸
- 文本嵌入模型
- Aleph Alpha、Amazon Bedrock、Azure OpenAI、Cohere等
- Embaas、Fake Embeddings、Google Vertex AI PaLM等
- 提示(Prompts)
- 基礎(chǔ)知識
- 提示模板
- 基礎(chǔ)知識
- 連接到特征存儲
- 創(chuàng)建自定義提示模板和含有Few-Shot示例的提示模板
- 部分填充的提示模板和提示合成
- 序列化提示信息
- 示例選擇器(Example Selectors)
- 輸出解析器(Output Parsers)
- 記憶(Memory)
- 基礎(chǔ)知識
- 記憶的類型
- 會話緩存記憶、會話緩存窗口記憶和實(shí)體記憶
- 對話知識圖譜記憶、對話摘要記憶和會話摘要緩沖記憶
- 對話令牌緩沖存儲器和基于向量存儲的記憶
- 將記憶添加到LangChain組件中
- 自定義對話記憶與自定義記憶類
- 聊天消息記錄
- 記憶的存儲與應(yīng)用
- 索引(Indexes)
- 基礎(chǔ)知識
- 文檔加載器(Document Loaders)
- 文本分割器(Text Splitters)
- 向量存儲器(Vectorstores)
- 檢索器(Retrievers)
- 鏈(Chains)
- 基礎(chǔ)知識
- 通用功能
- 自定義Chain和Chain的異步API
- LLMChain和RouterChain
- SequentialChain和TransformationChain
- 鏈的保存(序列化)與加載(反序列化)
- 鏈與索引
- 文檔分析和基于文檔的聊天
- 問答的基礎(chǔ)知識
- 圖問答(Graph QA)和帶來源的問答(Q&A with Sources)
- 檢索式問答
- 文本摘要(Summarization)、HyDE和向量數(shù)據(jù)庫的文本生成
- 代理(Agents)
- 基礎(chǔ)知識
- 代理類型
- 自定義代理(Custom Agent)
- 自定義MRKL代理
- 帶有ChatModel的LLM聊天自定義代理和自定義多操作代理(Custom MultiAction Agent)
- 工具
- 基礎(chǔ)知識
- 自定義工具(Custom Tools)
- 多輸入工具和工具輸入模式
- 人工確認(rèn)工具驗(yàn)證和Tools作為OpenAI函數(shù)
- 工具包(Toolkit)
- 代理執(zhí)行器(Agent Executor)
- 結(jié)合使用Agent和VectorStore
- 使用Agents的異步API和創(chuàng)建ChatGPT克隆
- 處理解析錯誤、訪問中間步驟和限制最大迭代次數(shù)
- 為代理程序設(shè)置超時時間和限制最大迭代次數(shù)和為代理程序和其工具添加共享內(nèi)存
- 計(jì)劃與執(zhí)行
- 回調(diào)函數(shù)(Callbacks)
創(chuàng)建自定義Chain
要實(shí)現(xiàn)自己的自定義鏈?zhǔn)竭B接,我們可以子類化Chain
并實(shí)現(xiàn)以下方法:
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain.chains.base import Chain
from langchain.prompts.base import BasePromptTemplate
class MyCustomChain(Chain):
"""
An example of a custom chain.
"""
prompt: BasePromptTemplate
"""Prompt object to use."""
llm: BaseLanguageModel
output_key: str = "text" #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_keys(self) -> List[str]:
"""Will be whatever keys the prompt expects.
:meta private:
"""
return self.prompt.input_variables
@property
def output_keys(self) -> List[str]:
"""Will always return text key.
:meta private:
"""
return [self.output_key]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
# 在這里編寫你的自定義鏈邏輯
# 下面的示例僅模仿了 LLMChain
prompt_value = self.prompt.format_prompt(**inputs)
# 當(dāng)調(diào)用語言模型或其他鏈時,應(yīng)該將回調(diào)管理器傳遞給它。
# 這樣可以讓內(nèi)部運(yùn)行受到外部運(yùn)行注冊的任何回調(diào)的跟蹤。
# 你可以通過調(diào)用 `run_manager.get_child()` 獲取回調(diào)管理器,如下所示。
response = self.llm.generate_prompt(
[prompt_value],
callbacks=run_manager.get_child() if run_manager else None
)
# 如果想要記錄此次運(yùn)行的某些信息,可以通過調(diào)用 `run_manager` 上的方法來實(shí)現(xiàn)。
# 這將觸發(fā)為該事件注冊的任何回調(diào)。
if run_manager:
run_manager.on_text("記錄此次運(yùn)行的一些信息")
return {self.output_key: response.generations[0][0].text}
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
# 在這里編寫你的自定義鏈邏輯
# 下面的示例僅模仿了 LLMChain
prompt_value = self.prompt.format_prompt(**inputs)
# 當(dāng)調(diào)用語言模型或其他鏈時,應(yīng)該將回調(diào)管理器傳遞給它。
# 這樣可以讓內(nèi)部運(yùn)行受到外部運(yùn)行注冊的任何回調(diào)的跟蹤。
# 你可以通過調(diào)用 `run_manager.get_child()` 獲取回調(diào)管理器,如下所示。
response = await self.llm.agenerate_prompt(
[prompt_value],
callbacks=run_manager.get_child() if run_manager else None
)
# 如果想要記錄此次運(yùn)行的某些信息,可以通過調(diào)用 `run_manager` 上的方法來實(shí)現(xiàn)。
# 這將觸發(fā)為該事件注冊的任何回調(diào)。
if run_manager:
await run_manager.on_text("記錄此次運(yùn)行的一些信息")
return {self.output_key: response.generations[0][0].text}
@property
def _chain_type(self) -> str:
return "my_custom_chain"
from langchain.callbacks.stdout import StdOutCallbackHandler
from langchain.chat_models.openai import ChatOpenAI
from langchain.prompts.prompt import PromptTemplate
chain = MyCustomChain(
prompt=PromptTemplate.from_template('tell us a joke about {topic}'),
llm=ChatOpenAI()
)
chain.run({'topic': 'callbacks'}, callbacks=[StdOutCallbackHandler()])
日志輸出:
> Entering new MyCustomChain chain...
Log something about this run
> Finished chain.
輸出:
Why did the callback function feel lonely? Because it was always waiting for someone to call it back!'
Chain 的異步 API
LangChain通過利用asyncio
模塊提供了對鏈?zhǔn)竭B接的異步支持。目前,LLMChain(通過 arun
、apredict
和acall
方法)、LLMMathChain(通過arun
和acall
方法)、ChatVectorDBChain
和問答鏈?zhǔn)竭B接支持異步方法。其他鏈?zhǔn)竭B接的異步支持正在計(jì)劃中。
import asyncio
import time
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
def generate_serially():
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
chain = LLMChain(llm=llm, prompt=prompt)
for _ in range(5):
resp = chain.run(product="toothpaste")
print(resp)
async def async_generate(chain):
resp = await chain.arun(product="toothpaste")
print(resp)
async def generate_concurrently():
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
chain = LLMChain(llm=llm, prompt=prompt)
tasks = [async_generate(chain) for _ in range(5)]
await asyncio.gather(*tasks)
s = time.perf_counter()
# If running this outside of Jupyter, use asyncio.run(generate_concurrently())
await generate_concurrently()
elapsed = time.perf_counter() - s
print('\033[1m' + f"Concurrent executed in {elapsed:0.2f} seconds." + '\033[0m')
s = time.perf_counter()
generate_serially()
elapsed = time.perf_counter() - s
print('\033[1m' + f"Serial executed in {elapsed:0.2f} seconds." + '\033[0m')
輸出:文章來源:http://www.zghlxwxcb.cn/news/detail-663360.html
BrightSmile Toothpaste Company
BrightSmile Toothpaste Co.
BrightSmile Toothpaste
Gleaming Smile Inc.
SparkleSmile Toothpaste
Concurrent executed in 1.54 seconds.
BrightSmile Toothpaste Co.
MintyFresh Toothpaste Co.
SparkleSmile Toothpaste.
Pearly Whites Toothpaste Co.
BrightSmile Toothpaste.
Serial executed in 6.38 seconds.
參考文獻(xiàn):
[1] LangChain官方網(wǎng)站:https://www.langchain.com/
[2] LangChain ????? 中文網(wǎng),跟著LangChain一起學(xué)LLM/GPT開發(fā):https://www.langchain.com.cn/
[3] LangChain中文網(wǎng) - LangChain 是一個用于開發(fā)由語言模型驅(qū)動的應(yīng)用程序的框架:http://www.cnlangchain.com/文章來源地址http://www.zghlxwxcb.cn/news/detail-663360.html
到了這里,關(guān)于自然語言處理從入門到應(yīng)用——LangChain:鏈(Chains)-[通用功能:自定義Chain和Chain的異步API]的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!