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

news2024/11/20 15:36:13

原文地址:【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。

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

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

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

相关文章

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

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

Springboot+MybatisPlus如何实现分页和模糊查询

实现分页查询的时候我们需要创建一个config配置类 1、创建MybatisPlusConfig类 Configuration //表明这是一个配置类 ConditionalOnClass(Value{PaginationInterceptor.class} //ConditionalOnClass:当指定的类存在时,才会创建对应的Bean // 这里当PaginationInt…

解决springboot+vue静态资源刷新后无法访问的问题

一、背景 原项目是有前后端分离设计,测试环境是centos系统,采用nginx代理和转发,项目正常运行。 项目近期上线到正式环境,结果更换了系统环境,需要放到一台windows系统中,前后端打成一个jar包,…

最高可得 300 元现金!分享实操经验,即可轻松获得奖励

OpenBayes贝式计算平台第二期「创作者激励计划」上线啦,快来和 HyperAI超神经一起参加吧! 无论你是深度学习、数据科学或大模型的资深玩家,还是刚入门技术小白; 无论你是拥有丰富创作经验的老手,还是刚踏入社交媒体世…

(2024,MambaOut,Mamba 适合长序列,区分指标,不适合分类,适合检测和分割)视觉真的需要 Mamba 吗?

MambaOut: Do We Really Need Mamba for Vision? 公和众和号:EDPJ(进 Q 交流群:922230617 或加 VX:CV_EDPJ 进 V 交流群) 目录 0. 摘要 1. 简介 3. 概念讨论 3.1 Mamba 适合哪些任务? 3.2 视觉识别任…

【小笔记】streamlit使用笔记

【小笔记】streamlit使用笔记 1.streamlit是什么,为什么要用它? 一句话,这个东西是一个python的可视化库,当你想要给你的程序添加个web界面,而又不会或不想用前端技术时,你就可以考虑用它。 类似的可视化库…

惠普发布全新AI战略,重塑办公空间 引领企业智能化新浪潮

近日、全球知名科技公司惠普在北京隆重举办了以“用智能,开启无限可能”为主题的2024惠普商用AI战略暨AI PC新品发布会,此次盛会标志着惠普在人工智能领域迈出了重要一步,惠普紧跟时代步伐,推出了更高效、更安全、更灵活的AI PC产…

redis报错500

之前自己举一反三把value也给序列化了: 然后报错了: 原因是这里传入的是Integer类型,序列化的话就变为string类型了

web入门练手案例(一)

下面是一下web入门案例和实现的代码,带有部分注释,倘若代码中有任何问题或疑问,欢迎留言交流~ 新闻页面 案例描述: 互联网的发展使信息的传递变得方便、快捷,浏览新闻称为用户获取信息的重要渠道。下面将实现一个简…

云服务器和主机的区别

在今天的数字化时代,对于个人和企业来说,选择适当的服务器托管解决方案至关重要。然而,很多人对于云服务器和传统主机之间的区别不太清楚。本文将为您提供一个详细的指南,帮助您理解云服务器与主机之间的区别,以便您能…

Chatgpt教你使用Python开发iPhone风格计算器

上次使用Chatgpt写爬虫,虽然写出来的代码很多需要修改后才能运行,但Chatgpt提供的思路和框架都是没问题。 这次让Chatgpt写一写GUI程序,也就是你常看到的桌面图形程序。 由于第一次测试,就来个简单点的,用Python写用…

Linux防火墙iptalbes

1 iptalbes 1.1 概念 防火墙(Firewall)是一种隔离技术,用于安全管理与筛选的软件和硬件设备,使计算机内网和外网分开,可以防止外部网络用户以非法手段通过外部网络进入内部网络,保护内网免受外部非法用户的侵入。 1.2 SELinux …

【瑞萨RA6M3】2. UART 实验

https://blog.csdn.net/qq_35181236/article/details/132789258 使用 uart9 配置 打印 void hal_entry(void) {/* TODO: add your own code here */fsp_err_t err;uint8_t c;/* 配置串口 */err g_uart9.p_api->open(g_uart9.p_ctrl, g_uart9.p_cfg);while (1){g_uart9.…

有 10000 个 if else 该如何优化?被问懵了!

这个问题可以看作是一道场景题,它考察一个程序员在面对复杂逻辑判断时的优化能力,也是在考察一个程序员临场发挥技术能力。 方案1:策略模式 使用策略模式确实可以提升代码的优雅性,但也会存在以下问题: 如果是大量的…

代码随想录算法训练营Day 42| 动态规划part04 | 01背包问题理论基础I、01背包问题理论基础II、416. 分割等和子集

代码随想录算法训练营Day 42| 动态规划part04 | 01背包问题理论基础I、01背包问题理论基础II、416. 分割等和子集 文章目录 代码随想录算法训练营Day 42| 动态规划part04 | 01背包问题理论基础I、01背包问题理论基础II、416. 分割等和子集01背包问题理论基础一、01背包问题二、…

Transformer 模型

文章目录 前言一、模型结构 前言 Transformer 模型是由谷歌在 2017 年提出并首先应用于机器翻译的神经网络模型结构。机器翻译的目标是从源语言(Source Language)转换到目标语言(Target Language)。Transformer 结构完全通过注意力…

JS中的宏任务和微任务

JavaScript 引擎是建立在一个事件循环系统之上的,它实时监控事件队列,如果有事件就执行,如果没有事件就等待。事件系统是一个典型的生产消费模式,生产者发出事件,接收者监听事件,在UI 开发中是常见的一个设…

电源模块效率的正确测试方法

电源效率是评价电源性能的重要指标,它直接关系到设备的稳定性和能源的利用效率。因此,对电源进行效率测试显得尤为重要。电源在工作过程中,会有部分能量损耗,因此,电源效率的高低,不仅影响着设备的性能&…

CentOS 磁盘扩容与创建分区

文章目录 未分配空间创建新分区重启服务器添加物理卷扩展逻辑卷 操作前确认已给服务器增加硬盘或虚拟机已修改硬盘大小(必须重启服务才会生效)。 未分配空间 示例说明:原服务器只有40G,修改虚拟机硬盘大小再增加20G后硬盘变为60G。…

Python 机器学习 基础 之 监督学习 [朴素贝叶斯分类器] / [决策树] 算法 的简单说明 / [graphviz] 绘制决策树

Python 机器学习 基础 之 监督学习 [朴素贝叶斯分类器] / [决策树] 算法 的简单说明 / [graphviz] 绘制决策树 目录 Python 机器学习 基础 之 监督学习 [朴素贝叶斯分类器] / [决策树] 算法 的简单说明 / [graphviz] 绘制决策树 一、简单介绍 二、监督学习 算法 说明前的 数…