【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处理字符串的能力 套用进来 完成数据的格式化…

datagridview合并单元格

private void dataGridView5_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { DataGridView dataGridView this.dataGridView5; // 假设你的DataGridView有至少三行三列 if (e.RowIndex 2 && e.ColumnIndex 2) //合并第三行最后两…

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配…

fuel无人机自主探索代码解读2——sdf_map.cpp【占据栅格地图、膨胀占据栅格地图、ESDF】

一、概述 sdf_map.cpp负责map_ros.cpp内部主体函数的具体实现&#xff0c;主要功能包括&#xff1a; 融合输入的深度或点云图生成全局占据栅格地图根据launch参数生成全局膨胀占据栅格地图基于膨胀占据栅格地图采用欧式距离传输生成局部的ESDF地图采用三线性插值的方式得到某…

深度学习面试题整理

文章目录 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…

韵搜坊 -- 前端整合Axios(联调后端)

文章目录 安装配置发送请求 官网&#xff1a;https://www.axios-http.cn/docs/intro 安装 npm install axios配置 坐标&#xff1a;plugins/myAxios.ts import axios from "axios";const instance axios.create({baseURL: "http://localhost:8101/api"…

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

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

Page对象的学习

在ASP.NET中&#xff0c;Page是一个核心对象&#xff0c;它代表了一个ASP.NET Web Forms页面。每一个.aspx文件在运行时都会被编译成一个Page类的实例&#xff0c;这个实例承载了页面的所有功能&#xff0c;包括处理用户输入、与数据库交互、渲染HTML输出等。 在ASP.NET Web F…

第 8 章 机器人底盘Arduino端编码器驱动(自学二刷笔记)

重要参考&#xff1a; 课程链接:https://www.bilibili.com/video/BV1Ci4y1L7ZZ 讲义链接:Introduction Autolabor-ROS机器人入门课程《ROS理论与实践》零基础教程 8.4.3 底盘实现_02Arduino端编码器驱动 测速是整个PID闭环控制中的必须环节&#xff0c;我们必须修改代码适配…

设计模式之策略模式(一)

背景: 下单时有很多情况,有的是用户下单,有的是卡密下单,有的是下游下单,有的是需要唤起支付,有的不需要支付,这样就需要写很多下单接口,下面使用策略模式优化这种情况 代码结构 com.example.order ├── controller │ └── OrderController.java ├── service │ …

使用frp通过SSH访问内网机器

frp是一个开源的内网穿透反向代理工具&#xff0c;支持传输层的tcp/udp协议&#xff0c;也支持应用层的http/https协议。 服务端 服务端下载安装 在有公网地址的机器上下载并解压。 wget -c https://github.com/fatedier/frp/releases/download/v0.58.0/frp_0.58.0_linux_a…

odoo16 银行对账单导入改造

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

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

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

通过vue2来类比学习vue3

需求&#xff1a;之前有vue2基础&#xff0c;需要学习使用vue3&#xff1b;当然小白也可以&#xff08;建议先学习vue2&#xff09; 思路&#xff1a;如果已经学习完vue2&#xff0c;那么vue3直接就是小case 一、vue3页面结构&#xff08;归纳为三种&#xff09; 1.传统的vu…

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)常量指…