【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 asyncio

from langchain.llms import OpenAI


def 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, Optional

from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM

class CustomLLM(LLM):
    n: int

    @property
    def _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]

    @property
    def _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)
  CustomLLM
  Params: {'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 AgentType

tools = 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 REPL
  Action 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 AgentType

tools = 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 answer
    Thought: you should always think about what to do
    Action: the action to take, should be one of [Wikipedia]
    Action Input: the input to the action
    Observation: the result of the action
    ... (this Thought/Action/Action Input/Observation can repeat N times)
    Thought: I now know the final answer
    Final Answer: the final answer to the original input question
    
    Begin!
    
    Question: What is 'Bocchi the Rock!'?
    Thought:
    =====END OF PROMPT======
    I need to use a tool.
    Action: Wikipedia
    Action 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 Kirara
    Summary: 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 Max
    Summary: 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 answer
    Thought: you should always think about what to do
    Action: the action to take, should be one of [Wikipedia]
    Action Input: the input to the action
    Observation: the result of the action
    ... (this Thought/Action/Action Input/Observation can repeat N times)
    Thought: I now know the final answer
    Final Answer: the final answer to the original input question
    
    Begin!
    
    Question: What is 'Bocchi the Rock!'?
    Thought:I need to use a tool.
    Action: Wikipedia
    Action 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 Kirara
    Summary: 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 Max
    Summary: 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: Wikipedia
    Action 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 answer
    Thought: you should always think about what to do
    Action: the action to take, should be one of [Wikipedia]
    Action Input: the input to the action
    Observation: the result of the action
    ... (this Thought/Action/Action Input/Observation can repeat N times)
    Thought: I now know the final answer
    Final Answer: the final answer to the original input question
    
    Begin!
    
    Question: What is 'Bocchi the Rock!'?
    Thought:I need to use a tool.
    Action: Wikipedia
    Action 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 Kirara
    Summary: 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 Max
    Summary: 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: Wikipedia
    Action 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。

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

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

楼宇智慧公厕建设新方案-集成更简单!成本价更低!

在当今的大厦和写字楼中,公厕面临着诸多痛点。 办公楼公厕常常存在厕位难找的问题,使用者不得不花费时间逐一查看,导致效率低下;环境质量也令人担忧,异味、脏污等情况时有发生,影响使用者的心情和健康&…

深入探索Android签名机制:从v1到v3的演进之旅

引言 在Android开发的世界中,APK的签名机制是确保应用安全性的关键环节。随着技术的不断进步,Android签名机制也经历了从v1到v3的演进。本文将带你深入了解Android签名机制的演变过程,揭示每个版本背后的技术细节,并探讨它们对开…

创意无限!AI一键生成漫画视频,每天轻松收入300+,粘贴复制简单操作!

AI项目算是2023到2024一直都非常火爆的项目,这次的AI漫画项目也是相当暴利的项目了,我知道一个老铁通过AI漫画半年已经获利100W了,真的是相当暴利了。 不再多说,直接上手拆解项目。 项目获取: https://zzmbk.com/htt…

linux 任务管理(临时任务定时任务) 实验

目录 任务管理临时任务管理周期任务管理 任务管理 临时任务管理 执行如下命令添加单次任务,输入完成后按组合键Ctrl-D。 [rootopenEuler ~]# at now5min warning: commands will be executed using /bin/sh at> echo "aaa" >> /tmp/at.log at&g…

C++|二叉搜索树

一、二叉搜索树的概念 二叉搜索树又称为二叉排序树,它或者是一颗空树,或者是具有以下性质的二叉树: 若它的左子树不为空,则左子树上所有节点的值小于根节点的值若它的右子树不为空,则右子树上所有节点的值都大于根结…

AVL树、红黑树

数据结构、算法总述:数据结构/算法 C/C-CSDN博客 AVL树 定义 空二叉树是一个 AVL 树如果 T 是一棵 AVL 树,那么其左右子树也是 AVL 树,并且 ,h 是其左右子树的高度树高为 平衡因子:右子树高度 - 左子树高度 创建节点…

图片标签 以及 常见的图片的格式

1.图片的基本使用 2.图片的常见格式 3.bmp格式

易我分区大师18.5发布上线:全方位提升您的磁盘管理体验

近期,易我分区大师18.5版本正式发布上线! 新版本在原有基础上进行了升级和优化,不仅继承了前版本的强大功能,还新增了C盘数据迁移、清除Windows PIN码以及蓝屏问题助手等实用功能,帮助用户更轻松、更高效地管理电脑磁…

HTML的使用(中)

文章目录 前言一、HTML表单是什么&#xff1f;二、HTML表单的使用 &#xff08;1&#xff09;<form>...</form>表单标记&#xff08;2&#xff09;<input>表单输入标记总结 前言 在许多网页平台上浏览&#xff0c;大多逃不了登录账号。此时在网页中填写的用户…

数据库SQL编写规范-SQL书写规范整理(SQL语句书写规范全解-Word原件)

编写本文档的目的是保证在开发过程中产出高效、格式统一、易阅读、易维护的SQL代码。 1 编写目 2 SQL书写规范 3 SQL编写原则 软件全套精华资料包清单部分文件列表&#xff1a; 工作安排任务书&#xff0c;可行性分析报告&#xff0c;立项申请审批表&#xff0c;产品需求规格说…

吴恩达深度学习笔记:优化算法 (Optimization algorithms)2.3-2.5

目录 第二门课: 改善深层神经网络&#xff1a;超参数调试、正 则 化 以 及 优 化 (Improving Deep Neural Networks:Hyperparameter tuning, Regularization and Optimization)第二周&#xff1a;优化算法 (Optimization algorithms)2.3 指数加权平均数&#xff08;Exponential…

unity 学习笔记

一、 事件顺序 gameObjet Instantiate gameObjet.自定义函数 gameObjet.Start 二、预设体使用 例子&#xff1a;Button 点击创建 预设体 BagPanel

【MIT6.S081】Lab7: Multithreading(详细解答版)

实验内容网址:https://xv6.dgs.zone/labs/requirements/lab7.html 本实验的代码分支:https://gitee.com/dragonlalala/xv6-labs-2020/tree/thread2/ Uthread: switching between threads 关键点:线程切换、swtch 思路: 本实验完成的任务为用户级线程系统设计上下文切换机制…

windows平台Visual Studio2022编译libuvc调试usb摄像头

一、下载libuv源码&#xff0c;源码地址&#xff1a;libuvc/libuvc: a cross-platform library for USB video devices (github.com) 二、新建vs工程&#xff0c;将libuvc源码中的include和src目录下的文件拷贝到工程中。 1.include源码修改 ①libuvc头文件修改 将 #includ…

自动删除 PC 端微信缓存数据,包括从所有聊天中自动下载的大量文件、视频、图片等数据内容,解放你的空间。

Clean My PC Wechat 自动删除 PC 端微信自动下载的大量文件、视频、图片等数据内容&#xff0c;解放一年几十 G 的空间占用。 该工具不会删除文字的聊天记录&#xff0c;请放心使用。请给个 Star 吧&#xff0c;非常感谢&#xff01; 现已经支持 Windows 系统中的所有微信版本…

Java进阶11 IO流、功能流

Java进阶11 IO流-功能流 一、字符缓冲流 字符缓冲流在源代码中内置了字符数组&#xff0c;可以提高读写效率 1、构造方法 方法说明BufferedReader(new FileReader(文件路径))对传入的字符输入流进行包装BufferedWriter(new FileWriter(文件路径))对传入的字符输出流进行包装…

基于Springboot+Vue的Java项目-宠物商城网站系统开发实战(附演示视频+源码+LW)

大家好&#xff01;我是程序员一帆&#xff0c;感谢您阅读本文&#xff0c;欢迎一键三连哦。 &#x1f49e;当前专栏&#xff1a;Java毕业设计 精彩专栏推荐&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb; &#x1f380; Python毕业设计 &am…

暗区突围TWITCH掉宝领测试资格后,steam激活显示是无效激活码

自《暗区突围》测试启动以来&#xff0c;吸引了大量玩家关注&#xff0c;特别是通过在Twitch平台上观看直播即可获得测试资格的活动&#xff0c;更是掀起了热潮。然而&#xff0c;部分玩家在成功获得激活码后&#xff0c;在Steam平台激活时遭遇了“无效激活码”的问题。本文将提…

勒索软件漏洞?在不支付赎金的情况下解密文件

概述 在上一篇文章中&#xff0c;笔者对BianLian勒索软件进行了研究剖析&#xff0c;并且尝试模拟构建了一款针对BianLian勒索软件的解密工具&#xff0c;研究分析过程中&#xff0c;笔者感觉构建勒索软件的解密工具还挺有成就感&#xff0c;因此&#xff0c;笔者准备再找一款…

排序-归并排序(merge sort)

归并排序&#xff08;Merge Sort&#xff09;是一种分而治之的算法&#xff0c;它将原始数组分成越来越小的子数组&#xff0c;直到每个子数组只有一个元素&#xff0c;然后将这些子数组两两合并&#xff0c;过程中保持排序状态&#xff0c;最终合并成一个完全有序的数组。归并…