【LangChain系列 15】语言模型——LLMs(一)

原文地址:【LangChain系列 15】语言模型——LLMs(一)

本文速读:

  • 异步API

  • 自定义LLM

  • Fake LLM

  • HumanInput LLM

本文将介绍LLMs在LangChain中的一些用法,帮助我们更好地了解LLM模块。

01 异步API


LangChain通过异步库实现了对异步的支持,异步对于多LLM的并发调用是非常有用的。目前,OpenAI、PromptLayerOpenAI、ChatOpenAI、Anthropic、Cohere都是支持异步的,其它LLM的异步支持已经在规划中。

在LangChain中,可以通过agenerate方法去异步地调用OpenAI LLM。


import time
import asynciofrom langchain.llms import OpenAIdef generate_serially():llm = OpenAI(temperature=0.9)for _ in range(10):resp = llm.generate(["Hello, how are you?"])print(resp.generations[0][0].text)async def async_generate(llm):resp = await llm.agenerate(["Hello, how are you?"])print(resp.generations[0][0].text)async def generate_concurrently():llm = OpenAI(temperature=0.9)tasks = [async_generate(llm) for _ in range(10)]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(f"Concurrent executed in {elapsed:0.2f} seconds.")s = time.perf_counter()
generate_serially()
elapsed = time.perf_counter() - s
print(f"Serial executed in {elapsed:0.2f} seconds.")

执行代码,输出结果:

I'm doing well, thank you. How about you?I'm doing well, thank you. How about you?I'm doing well, how about you?I'm doing well, thank you. How about you?I'm doing well, thank you. How about you?I'm doing well, thank you. How about yourself?I'm doing well, thank you! How about you?I'm doing well, thank you. How about you?I'm doing well, thank you! How about you?I'm doing well, thank you. How about you?Concurrent executed in 1.39 seconds.I'm doing well, thank you. How about you?I'm doing well, thank you. How about you?I'm doing well, thank you. How about you?I'm doing well, thank you. How about you?I'm doing well, thank you. How about yourself?I'm doing well, thanks for asking. How about you?I'm doing well, thanks! How about you?I'm doing well, thank you. How about you?I'm doing well, thank you. How about yourself?I'm doing well, thanks for asking. How about you?Serial executed in 5.77 seconds.

02 自定义LLM


通过自定义LLM,你可以定义一个自己的LLM,也可以基于LangChain已有的LLM封装成一个新的LLM。

封装一个LLM,你唯一要实现的方法是_call,这个方法接收一个字符串和一些可选的停止词,然后返回一个字符串;另外,还有一个可选的_identifying_params属性,你可以根据需要决定是否实现,它主要作用是辅助这个类信息的打印输出。

下面我们动手实现一个自定义的LLM。

from typing import Any, List, Mapping, Optionalfrom langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLMclass CustomLLM(LLM):n: int@propertydef _llm_type(self) -> str:return "custom"def _call(self,prompt: str,stop: Optional[List[str]] = None,run_manager: Optional[CallbackManagerForLLMRun] = None,**kwargs: Any,) -> str:if stop is not None:raise ValueError("stop kwargs are not permitted.")return prompt[: self.n]@propertydef _identifying_params(self) -> Mapping[str, Any]:"""Get the identifying parameters."""return {"n": self.n}

​​​​​​​这样就定义好了一个LLM,接下来就可以使用它了。​​​​​​​

llm = CustomLLM(n=10)
llm("This is a foobar thing"

我们可以输出这个类的对象,查看它的打印输出:

print(llm)
  CustomLLMParams: {'n': 10}

​​​​​​​因为我们实现了_identifying_params,所以在打印输出这个对象时,输出了相应的属性。

03 Fake LLM


LangChain提供了一个伪造的LLM类可以用来调试,通过模拟调用LLM,当LLM以某种方式返回时,模拟后续会发生什么。

下面我们通过agent的方式使用FakeLLM。


from langchain.llms.fake import FakeListLLM
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentTypetools = load_tools(["python_repl"])
responses = ["Action: Python REPL\nAction Input: print(2 + 2)", "Final Answer: 4"]
llm = FakeListLLM(responses=responses)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
agent.run("whats 2 + 2")

​​​​​​​执行代码,输出结果:

  > Entering new AgentExecutor chain...Action: Python REPLAction Input: print(2 + 2)Observation: Python REPL is not a valid tool, try one of [Python_REPL].Thought:Final Answer: 4> Finished chain.

04 HumanInput LLM


和FakeLLM类似,HumanInput LLM也是一个伪LLM类,可以用来测试、调试等。也是通过模拟调用LLM,然后模拟人类会如何响应。

同样我们通过agent的方式使用HumanInputLLM。

由于需要用到wikipedia,首先安装一下:

pip install wikipedia

然后创建HumanInputLLM。


from langchain.llms.human import HumanInputLLM
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentTypetools = load_tools(["wikipedia"])
llm = HumanInputLLM(prompt_func=lambda prompt: print(f"\n===PROMPT====\n{prompt}\n=====END OF PROMPT======")
)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
agent.run("What is 'Bocchi the Rock!'?")

​​​​​​​运行代码,输出结果:

> Entering new AgentExecutor chain...===PROMPT====Answer the following questions as best you can. You have access to the following tools:Wikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, historical events, or other subjects. Input should be a search query.Use the following format:Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [Wikipedia]Action Input: the input to the actionObservation: the result of the action... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input questionBegin!Question: What is 'Bocchi the Rock!'?Thought:=====END OF PROMPT======I need to use a tool.Action: WikipediaAction Input: Bocchi the Rock!, Japanese four-panel manga and anime series.Observation: Page: Bocchi the Rock!Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.An anime television series adaptation produced by CloverWorks aired from October to December 2022. The series has been praised for its writing, comedy, characters, and depiction of social anxiety, with the anime's visual creativity receiving acclaim.Page: Manga Time KiraraSummary: Manga Time Kirara (まんがタイムきらら, Manga Taimu Kirara) is a Japanese seinen manga magazine published by Houbunsha which mainly serializes four-panel manga. The magazine is sold on the ninth of each month and was first published as a special edition of Manga Time, another Houbunsha magazine, on May 17, 2002. Characters from this magazine have appeared in a crossover role-playing game called Kirara Fantasia.Page: Manga Time Kirara MaxSummary: Manga Time Kirara Max (まんがタイムきららMAX) is a Japanese four-panel seinen manga magazine published by Houbunsha. It is the third magazine of the "Kirara" series, after "Manga Time Kirara" and "Manga Time Kirara Carat". The first issue was released on September 29, 2004. Currently the magazine is released on the 19th of each month.Thought:===PROMPT====Answer the following questions as best you can. You have access to the following tools:Wikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, historical events, or other subjects. Input should be a search query.Use the following format:Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [Wikipedia]Action Input: the input to the actionObservation: the result of the action... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input questionBegin!Question: What is 'Bocchi the Rock!'?Thought:I need to use a tool.Action: WikipediaAction Input: Bocchi the Rock!, Japanese four-panel manga and anime series.Observation: Page: Bocchi the Rock!Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.An anime television series adaptation produced by CloverWorks aired from October to December 2022. The series has been praised for its writing, comedy, characters, and depiction of social anxiety, with the anime's visual creativity receiving acclaim.Page: Manga Time KiraraSummary: Manga Time Kirara (まんがタイムきらら, Manga Taimu Kirara) is a Japanese seinen manga magazine published by Houbunsha which mainly serializes four-panel manga. The magazine is sold on the ninth of each month and was first published as a special edition of Manga Time, another Houbunsha magazine, on May 17, 2002. Characters from this magazine have appeared in a crossover role-playing game called Kirara Fantasia.Page: Manga Time Kirara MaxSummary: Manga Time Kirara Max (まんがタイムきららMAX) is a Japanese four-panel seinen manga magazine published by Houbunsha. It is the third magazine of the "Kirara" series, after "Manga Time Kirara" and "Manga Time Kirara Carat". The first issue was released on September 29, 2004. Currently the magazine is released on the 19th of each month.Thought:=====END OF PROMPT======These are not relevant articles.Action: WikipediaAction Input: Bocchi the Rock!, Japanese four-panel manga series written and illustrated by Aki Hamaji.Observation: Page: Bocchi the Rock!Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.An anime television series adaptation produced by CloverWorks aired from October to December 2022. The series has been praised for its writing, comedy, characters, and depiction of social anxiety, with the anime's visual creativity receiving acclaim.Thought:===PROMPT====Answer the following questions as best you can. You have access to the following tools:Wikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, historical events, or other subjects. Input should be a search query.Use the following format:Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [Wikipedia]Action Input: the input to the actionObservation: the result of the action... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input questionBegin!Question: What is 'Bocchi the Rock!'?Thought:I need to use a tool.Action: WikipediaAction Input: Bocchi the Rock!, Japanese four-panel manga and anime series.Observation: Page: Bocchi the Rock!Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.An anime television series adaptation produced by CloverWorks aired from October to December 2022. The series has been praised for its writing, comedy, characters, and depiction of social anxiety, with the anime's visual creativity receiving acclaim.Page: Manga Time KiraraSummary: Manga Time Kirara (まんがタイムきらら, Manga Taimu Kirara) is a Japanese seinen manga magazine published by Houbunsha which mainly serializes four-panel manga. The magazine is sold on the ninth of each month and was first published as a special edition of Manga Time, another Houbunsha magazine, on May 17, 2002. Characters from this magazine have appeared in a crossover role-playing game called Kirara Fantasia.Page: Manga Time Kirara MaxSummary: Manga Time Kirara Max (まんがタイムきららMAX) is a Japanese four-panel seinen manga magazine published by Houbunsha. It is the third magazine of the "Kirara" series, after "Manga Time Kirara" and "Manga Time Kirara Carat". The first issue was released on September 29, 2004. Currently the magazine is released on the 19th of each month.Thought:These are not relevant articles.Action: WikipediaAction Input: Bocchi the Rock!, Japanese four-panel manga series written and illustrated by Aki Hamaji.Observation: Page: Bocchi the Rock!Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.An anime television series adaptation produced by CloverWorks aired from October to December 2022. The series has been praised for its writing, comedy, characters, and depiction of social anxiety, with the anime's visual creativity receiving acclaim.Thought:=====END OF PROMPT======It worked.Final Answer: Bocchi the Rock! is a four-panel manga series and anime television series. The series has been praised for its writing, comedy, characters, and depiction of social anxiety, with the anime's visual creativity receiving acclaim.> Finished chain."Bocchi the Rock! is a four-panel manga series and anime television series. The series has been praised for its writing, comedy, characters, and depiction of social anxiety, with the anime's visual creativity receiving acclaim."

本文小结

本文是LLMs的第一部分,主要介绍了异步API、自定义LLM、FakeLLM和HumanInputLLM。

更多最新文章,请关注公众号:大白爱爬山

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/837635.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

大模型应用的最佳实践Chains, SequentialChain使用示例

各种chain的介绍 串联式编排调用链:SequentialChain 流水线 胶水代码逻辑处理具备编排逻辑 串行 one by one的调用上一个chain的输出 作为 下一个chain的输入 超长文本的转换 Transform Chain pdf文件处理提供了套壳的能力 将python处理字符串的能力 套用进来 完成数据的格式化…

java sql中 大于 小于 大于等于 小于等于 代替符号

在写java时sql会经常会忘记大于小于号的表示方法导致无法运行&#xff0c;总结一下 第一种方法&#xff1a; < &#xff1a;< < &#xff1a; < &#xff1a;> &#xff1a; > sql如下&#xff1a; create_at > #{startTime} and create_at < #{end…

MySQL innodb_buffer_pool_size 相关常用语句

对于MySQL速度慢的问题&#xff0c;除了优化 SQL 以外&#xff0c;应该必须优先想到的即使 MySQL 数据库的 innodb_buffer_pool_size 配置问题。 一般来说&#xff0c;innodb_buffer_pool_size 的默认大小都是很小的&#xff0c;尤其是 win 下其默认大小更是只有离谱的 8M。Li…

centos7中如何全局搜索一下nginx的配置文件?

在CentOS 7中搜索Nginx的配置文件&#xff0c;你可以使用一些常用的命令行工具&#xff0c;比如find、grep等。这些工具可以帮助你在文件系统中查找文件&#xff0c;也可以用来查找Docker容器内部的文件&#xff0c;只要你知道如何访问容器的文件系统。 1. 搜索系统中的Nginx配…

深度学习面试题整理

文章目录 1. TensorFlow是什么&#xff1f;2. 计算图3. pytorch tensorflow4. 节点与张量类型5. tensorboard6. tensflow三个工作组件7. 大多数 TensorFlow 算法的常用步骤是什么&#xff1f;8. 处理TensorFlow中过拟合的方法9. 为什么出现过拟合10. 交叉验证11. 学习率12. 特征…

Python SMTP发送邮件时如何设置邮件地址?

Python SMTP发送邮件如何添加附件&#xff1f;如何使用SMTP发信&#xff1f; Python则通过其内置的smtplib模块和email模块为我们提供了实现这一功能的工具。在发送邮件的过程中&#xff0c;正确设置邮件地址是至关重要的&#xff0c;AokSend就来详细探讨一下如何在Python SMT…

Python专题:十三、日期和时间(1)

Python 日期和时间处理模块 模块就是别人写好的代码&#xff0c;通过将模块引入到代码里&#xff0c;使用已经实现好的功能 math模块&#xff0c;import模块名 time模块 时间戳&#xff1a;从公元1970年1月1日0点0分0秒起&#xff0c;到现在总共经历过的秒杀

odoo16 银行对账单导入改造

解决问题: odoo原生功能的话 是不能在系统上临时处理文件内容的&#xff0c;只会提示文件内容格式不对。 原始文件格式 在头部与尾部 格式问题&#xff0c;例如csv文件和 C53 文件&#xff0c;做一个前置弹框处理数据之后再导入 camt效果: csv效果:

汇聚荣电商:拼多多开店需要多少费用?

想要在拼多多这个巨大的电商平台上开一家属于自己的店铺&#xff0c;很多创业者都会关心一个问题&#xff1a;开店需要多少费用?答案并不复杂&#xff0c;但背后的经营哲学和策略却值得深究。接下来&#xff0c;让我们从四个不同的方面来详细探讨这个问题。 一、开店成本分析 …

GPT-4o,AI实时视频通话丝滑如人类,Plus功能免费可用

不开玩笑&#xff0c;电影《她》真的来了。 OpenAI最新旗舰大模型GPT-4o&#xff0c;不仅免费可用&#xff0c;能力更是横跨听、看、说&#xff0c;丝滑流畅毫无延迟&#xff0c;就像在打一个视频电话。 现场直播的效果更是炸裂&#xff1a; 它能感受到你的呼吸节奏&#xf…

10G UDP协议栈 IP层设计-(6)IP TX模块

一、模块功能 1、上层数据封装IP报文头部 2、计算首部校验和 二、首部校验和计算方法 在发送方&#xff0c;先把IP数据报首部划分为许多16位字的序列&#xff0c;并把检验和字段置零。用反码算术运算把所有16位字相加后&#xff0c;将得到的和的反码写入检验和字段。接收方收…

C++(week2):C语言中高级

文章目录 (八) 指针0.概念1.指针基础(1)指针的声明(2)指针的两个基本操作①取地址运算符 &②解引用运算符 * (3)野指针①野指针②空指针③指针变量的赋值 vs 指针变量指向对象的赋值 (4)指针的应用①指针作为参数进行传递②指针作为返回值③拓展&#xff1a;栈帧 (5)常量指…

手撸XXL-JOB(一)——定时任务的执行

SpringBoot执行定时任务 对于定时任务的执行&#xff0c;SpringBoot提供了三种创建方式&#xff1a; 1&#xff09;基于注解(Scheduled) 2&#xff09;基于接口&#xff08;SchedulingConfigurer&#xff09; 3&#xff09;基于注解设定多线程定时任务 基于Scheduled注解 首…

基于51单片机的冰箱控制系统设计( proteus仿真+程序+设计报告+原理图+讲解视频)

基于51单片机冰箱控制系统设计( proteus仿真程序设计报告原理图讲解视频&#xff09; 基于51单片机冰箱控制系统设计 1. 主要功能&#xff1a;2. 讲解视频&#xff1a;3. 仿真4. 程序代码5. 设计报告6. 原理图7. 设计资料内容清单&&下载链接资料下载链接&#xff1a; …

【C++】学习笔记——继承_2

文章目录 十二、继承5. 继承与友元6. 继承与静态成员7. 复杂的菱形继承及菱形虚拟继承 未完待续 十二、继承 5. 继承与友元 友元关系不能继承&#xff0c;也就是说父类友元不能访问子类私有和保护成员 。除非子类也设置成友元。 6. 继承与静态成员 父类定义了 static 静态成…

pnpm:无法加载文件 C:\Users\PC\AppData\Roaming\npm\pnpm.ps1,因为在此系统上禁止运行脚本。

使用pnpm命令启动vue时报了个错&#xff1a; 解决起来也简单&#xff0c;右击开始菜单&#xff0c;用管理员身份打开终端。win11的如下图&#xff1a; win10我记得应该是PowerShell&#xff08;管理员&#xff09;&#xff0c;这样的。 打开之后执行命令&#xff1a; set-…

物联网平台之单体架构

介绍本文主要介绍平台的单体架构&#xff0c;包括各个组件之间的数据流描述以及所做的一些架构选择。在单体架构模式下&#xff0c;所有 ThingsKit 组件都在单个 Java 虚拟机 (JVM) 中启动&#xff0c;并共享相同的操作系统资源。由于 ThingsKit 是用 Java 编写的&#xff0c;因…

dnf手游攻略,新手入坑必备!

一、角色创建策略 在DNF手游中&#xff0c;角色创建是玩家初入游戏的首要步骤。为最大化游戏体验和收益&#xff0c;新手玩家通常建议创建三个角色&#xff1a;一个主账号和两个副账号。 主账号选择 主账号的选择应基于玩家个人的喜好和对职业的熟悉程度。无论选择哪个职业&a…

番外篇 | 手把手教你利用YOLOv8进行热力图可视化 | 针对视频

前言:Hello大家好,我是小哥谈。YOLOv8的热力图可视化可以帮助我们更加直观地了解模型在图像中的检测情况,同时也可以帮助我们进行模型的调试和优化。热力图是一种颜色渐变的图像,不同颜色的区域表示不同程度的关注度或者置信度。在YOLOv8中,可以通过设置阈值来控制热力图的…

电机控制杂谈——“双采样双更新模式”对模型预测控制/PI控制的提升有多大?

1.采样频率与PWM开关频率的关系 一般有以下两种采样模式。 如下图&#xff08;a&#xff09;所示&#xff0c;这种方式称之为单采单更模式&#xff0c;即在一个PWM周期内&#xff0c;采样一次&#xff0c;更新一次PWM占空比&#xff0c;在这种情况下&#xff0c;采样频率&…