【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.man
### 使用 LangChain 结合大模型进行开发 LangChain个专门设计用于帮助开发者快速集成和利用大型语言模型(LLM)的应用程序框架。它通过提供系列工具和模块来简化 LLM 的使用流程,其中包括提示模板、记忆管理以及链式逻辑等功能[^2]。 #### 主要功能概述 1. **提示词管理** 提示词是与 LLM 交互的核心方式之LangChain 提供了套灵活的机制,允许开发者定义动态提示词并将其传递给目标模型。这可以通过 `PromptTemplate` 类实现,该类支持参数化输入以便于定制化的请求生成[^3]。 2. **记忆组件** 记忆组件解决了传统 LLM 缺乏上下文保持能力的问题。借助内存存储技术,LangChain 能够记录先前对话的历史信息,并在后续查询中自动附加这些背景数据,从而增强连续会话的质量。 3. **链式操作** 链是指多个步骤组成的序列化任务流,在实际应用场景里非常常见。比如先提取关键词再基于此生成文章摘要等多阶段作业都可以轻松地用链条形式表达出来。这种结构不仅提高了代码可读性和维护便利度,还促进了不同子任务间的协作效率提升。 4. **代理模式** 当面对复杂业务需求时,单调用可能无法满足全部要求。此时引入代理概念就显得尤为重要——即让某个中间层负责协调多方资源完成最终目的。例如搜索引擎加问答系统组合而成的知识检索服务就是典型例子。 #### 实际案例分析 假设我们希望创建个简单的聊天机器人应用,它可以记住用户的偏好并向用户提供个性化的建议: ```python from langchain import PromptTemplate, LLMChain from langchain.llms import Ollama # 或其他兼容的大模型接口如Kimi # 初始化OLLAMA实例或其他替代方案 ollama_model = Ollama(model="your-model-name") # 定义基础提示模板 template = """The user has previously mentioned they like {interest}. Given this context, what would be a good recommendation?""" prompt_template = PromptTemplate(input_variables=["interest"], template=template) # 构建链对象 conversation_chain = LLMChain(llm=ollama_model, prompt=prompt_template) # 执行具体询问过程 response = conversation_chain.run(interest="science fiction novels") print(response) ``` 上述脚本展示了如何设置基本的工作环境并通过指定兴趣领域获取相应推荐结果的过程。 --- #### 注意事项 尽管 LangChain 功能强大,但由于该项目正处于高速迭代更新之中,因此某些API可能会随时间推移有所变化。此外,考虑到国内外网络条件差异较大,如果原生依赖的服务不可达,则需寻找合适的本地解决方案或者调整配置文件以适配新环境下的运行状况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值