大语言模型RAG-langchain models (二)

大语言模型RAG-langchain models (二)


往期文章:大语言模型RAG-技术概览 (一)

文章目录

  • 大语言模型RAG-langchain models (二)
    • **往期文章:[大语言模型RAG-技术概览 (一)](https://blog.csdn.net/tangbiubiu/article/details/136651625)**
    • 核心模块总览
    • Models
      • LLMs
      • chat
      • Embedding

核心模块总览

langchain的核心模块(Modules)如下图所示。

图片来自网络
图片来自网络

  • models语言模型的接口,是所有应用的核心。

  • prompts是构建提示词工程的接口,一般prompts的输出是models的输入,所以根据语言模型的不同,提示词工程也有不同的构造方法。

  • indexs构造文档的方法,以便语言模型能与文档交互。这里的文档一般是指非结构化的文档,如文本文档,PDF等等。

  • memory使语言模型在聊天中记住先前的交互,使每条对话具有上下文联系。

  • chains为调用多种工具相互串联提供了标准接口。

  • agents 有些应用需要根据用户输入来构造chain,它可以大大的提高chain的灵活性。

今天主要介绍models


Models

在介绍之前,先说设置API KEY的方法。
一劳永逸的方法是写在环境变量里:

export OPENAI_API_KEY="..."

在脚本中添加,源码中给出的Example:

import os

os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https://<your-endpoint.openai.azure.com/"
os.environ["OPENAI_API_KEY"] = "your AzureOpenAI key"
os.environ["OPENAI_API_VERSION"] = "2023-05-15"
os.environ["OPENAI_PROXY"] = "http://your-corporate-proxy:8080"

在调用供应商提供的模型时,也可以在参数中设置API KEY,如:

from langchain_community.chat_models import ChatZhipuAI

zhipuai_chat = ChatZhipuAI(
        temperature=0.5,
        api_key="xxx",  # 在这里传入KEY
        model="chatglm_turbo",
    )

models 一般是大模型供应商提供的大语言模型,langchain为不同的模型作了接口。主要分为三类:

LLMs

输入和输出都是字符串。封装在langchain.llms中。可以使用下面的属性获取LLMs列表.

>>> from langchain import llms
>>> llms.__all__
['AI21', 'AlephAlpha', 'AmazonAPIGateway', 'Anthropic', 'Anyscale', 
'Arcee', 'Aviary', 'AzureMLOnlineEndpoint', 'AzureOpenAI', 'Banana', 
'Baseten', 'Beam', 'Bedrock', 'CTransformers', 'CTranslate2', 'CerebriumAI', 
'ChatGLM', 'Clarifai', 'Cohere', 'Databricks', 'DeepInfra', 'DeepSparse', 
'EdenAI', 'FakeListLLM', 'Fireworks', 'ForefrontAI', 'GigaChat', 'GPT4All', 
'GooglePalm', 'GooseAI', 'GradientLLM', 'HuggingFaceEndpoint', 'HuggingFaceHub', 
'HuggingFacePipeline', 'HuggingFaceTextGenInference', 'HumanInputLLM', 
'KoboldApiLLM', 'LlamaCpp', 'TextGen', 'ManifestWrapper', 'Minimax', 
'MlflowAIGateway', 'Modal', 'MosaicML', 'Nebula', 'NIBittensorLLM', 'NLPCloud', 
'Ollama', 'OpenAI', 'OpenAIChat', 'OpenLLM', 'OpenLM', 'PaiEasEndpoint', 
'Petals', 'PipelineAI', 'Predibase', 'PredictionGuard', 'PromptLayerOpenAI', 
'PromptLayerOpenAIChat', 'OpaquePrompts', 'RWKV', 'Replicate', 'SagemakerEndpoint', 
'SelfHostedHuggingFaceLLM', 'SelfHostedPipeline', 'StochasticAI', 'TitanTakeoff', 
'TitanTakeoffPro', 'Tongyi', 'VertexAI', 'VertexAIModelGarden', 'VLLM', 
'VLLMOpenAI', 'WatsonxLLM', 'Writer', 'OctoAIEndpoint', 'Xinference', 
'JavelinAIGateway', 'QianfanLLMEndpoint', 'YandexGPT', 'VolcEngineMaasLLM']

假设你要使用OpenAI,仅需三行即可调用(前提是你有api key):

from langchain.llms import OpenAI
llm = OpenAI(model_name="text-ada-001", n=2, best_of=2)
llm("Tell me a joke")
'  Why did the chicken cross the road?  To get to the other side.'

也可以使用列表调用:

llm_result = llm.generate(["Tell me a joke", "Tell me a poem"])
llm_result.generations
[Generation(text='  Why did the chicken cross the road?  To get to the other side!'),
 Generation(text='  Why did the chicken cross the road?  To get to the other side.')]

调用之后可以查询llm模型提供的信息(不同的llm可能会提供不同的信息):

llm_result.llm_output
{'token_usage': {'completion_tokens': 3903,
  'total_tokens': 4023,
  'prompt_tokens': 120}}

因为大多数api是按照tekon收费的,所以查看一段文本的token数很有意义:

llm.get_num_tokens("what a joke")
3

chat

第二类model是聊天模型,虽然它是llm的包装,但它的接口基于消息而不是文本。

还是用.__all__方法可以获取聊天模型列表:

>>> langchain_community.chat_models.__all__
[
    "LlamaEdgeChatService",
    "ChatOpenAI",
         #...
       #省略若干行
         #...
    "ChatYuan2",
    "ChatZhipuAI",
]

使用中文聊天模型的实例:

>>> from langchain_community.chat_models import ChatZhipuAI
>>> from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
>>> zhipu_api_key = 'your apikey'

# 定义聊天模型。不同聊天模型的参数可能不同,请参照源码,后面会贴出一部分源码。
# 在模型定义中有流式输出的参数,可参照源码。
>>> chat = ChatZhipuAI(
...     temperature=0.5,
...     api_key=zhipu_api_key,
...     model="chatglm_turbo",
... )

# 定义聊天信息。以下的格式可以作为所有chat model的输入,langchain已经把接口统一了。
>>> messages = [
...     AIMessage(content="你好。"),
...     SystemMessage(content="你是一个知识渊博,耐心的导师。"),
...     HumanMessage(content='牛顿定律是什么?'),
... ]

>>> response = chat(messages)
>>> response.content  # 这里的response是AIMessage对象
"牛顿定律是...."  #输出省略


'''
messages也可以批量处理,将多个信息组成二维列表即可,模型的输出会是对应的列表形式
'''
batch_messages = [
    [
        SystemMessage(content="You are a helpful assistant that translates English to French."),
        HumanMessage(content="I love programming.")
    ],
    [
        SystemMessage(content="You are a helpful assistant that translates English to French."),
        HumanMessage(content="I love artificial intelligence.")
    ],
]
result = chat.generate(batch_messages)
# 这里的result是LLMResult对象,除了记录了输入和输出以外,还有诸如token使用量等统计
result.llm_outpuy  # 查看token统计

在打造专有大模型时,我们常常要使用提示词模板,langchain还贴心的准备了相应的接口,请看官网给出的示例:

from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain.schema import (
    AIMessage,
    HumanMessage,
    SystemMessage
)

template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

# get a chat completion from the formatted messages
chat(chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages())

# 输出
AIMessage(content="J'adore la programmation.", additional_kwargs={}# 或者更直接的构建MessagePromptTemplate
prompt=PromptTemplate(
    template="You are a helpful assistant that translates {input_language} to {output_language}.",
    input_variables=["input_language", "output_language"],
)
system_message_prompt = SystemMessagePromptTemplate(prompt=prompt)

不同的聊天模型怎么使用建议直接看源码,源码的注释可以说是非常友好了。下面贴一段ChatZhipuAI的源码浅浅感受一下:

class ChatZhipuAI(BaseChatModel):
    """
    `ZHIPU AI` large language chat models API.

    To use, you should have the ``zhipuai`` python package installed.

    Example:
    .. code-block:: python

    from langchain_community.chat_models import ChatZhipuAI

    zhipuai_chat = ChatZhipuAI(
        temperature=0.5,
        api_key="your-api-key",
        model="chatglm_turbo",
    )

    """

    zhipuai: Any
    zhipuai_api_key: Optional[str] = Field(default=None, alias="api_key")
    """Automatically inferred from env var `ZHIPUAI_API_KEY` if not provided."""

    model: str = Field("chatglm_turbo")
    """
    Model name to use.
    -chatglm_turbo:
        According to the input of natural language instructions to complete a 
        variety of language tasks, it is recommended to use SSE or asynchronous 
        call request interface.
    -characterglm:
        It supports human-based role-playing, ultra-long multi-round memory, 
        and thousands of character dialogues. It is widely used in anthropomorphic 
        dialogues or game scenes such as emotional accompaniments, game intelligent 
        NPCS, Internet celebrities/stars/movie and TV series IP clones, digital 
        people/virtual anchors, and text adventure games.
    """

    temperature: float = Field(0.95)
    """
    What sampling temperature to use. The value ranges from 0.0 to 1.0 and cannot 
    be equal to 0.
    The larger the value, the more random and creative the output; The smaller 
    the value, the more stable or certain the output will be.
    You are advised to adjust top_p or temperature parameters based on application 
    scenarios, but do not adjust the two parameters at the same time.
    """

    top_p: float = Field(0.7)
    """
    Another method of sampling temperature is called nuclear sampling. The value 
    ranges from 0.0 to 1.0 and cannot be equal to 0 or 1.
    The model considers the results with top_p probability quality tokens.
    For example, 0.1 means that the model decoder only considers tokens from the 
    top 10% probability of the candidate set.
    You are advised to adjust top_p or temperature parameters based on application 
    scenarios, but do not adjust the two parameters at the same time.
    """

    request_id: Optional[str] = Field(None)
    """
    Parameter transmission by the client must ensure uniqueness; A unique 
    identifier used to distinguish each request, which is generated by default 
    by the platform when the client does not transmit it.
    """

    streaming: bool = Field(False)
    """Whether to stream the results or not."""

    incremental: bool = Field(True)
    """
    When invoked by the SSE interface, it is used to control whether the content 
    is returned incremented or full each time.
    If this parameter is not provided, the value is returned incremented by default.
    """

    return_type: str = Field("json_string")
    """
    This parameter is used to control the type of content returned each time.
    - json_string Returns a standard JSON string.
    - text Returns the original text content.
    """

    ref: Optional[ref] = Field(None)
    """
    This parameter is used to control the reference of external information 
    during the request.
    Currently, this parameter is used to control whether to reference external 
    information.
    If this field is empty or absent, the search and parameter passing format 
    is enabled by default.
    {"enable": "true", "search_query": "history "}
    """
# 省略一万行...

Embedding

最后一类是文本嵌入模型(text-embedding-model)
从原理上来看,嵌入模型与以上的两种模型有本质不同。嵌入模型的思路是将字符串组成的空间映射到嵌入空间,这个嵌入空间是一个连续向量空间,且嵌入空间与原本的字符空间是同构的。这样做的目的有两点:

  1. 嵌入空间可以降维和升维,可以更好的提取语义特征。
  2. 连续向量空间的数学工具更多,可以更好的应用分类、预测、搜索等算法。比如前文的知识库搜索中用到的向量相似度就是利用连续向量空间中的距离来进行搜索的方法。

本文的重点不在原理上,原理的细节可自行搜索。知道Embedding模型在知识库中的作用即可:一方面知识库中的文档是以embedding的形式储存在向量库;另一方面是llm模型在检索知识库时是在embedding空间进行的,具体来说是用户的query和向量库进行向量相似度的计算,最终得出结果。
依然可以用__all__属性查看供应商提供的所有embedding。

>>> import langchain
>>> langchain.embeddings.__all__

使用方法官方示例:

from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])

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

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

相关文章

Css基础——精灵图(sprites)和字体图标

1、精灵图 1.1、精灵图的由来 一个网页中往往会应用很多小的背景图像作为修饰&#xff0c;当网页中的图像过多时&#xff0c;服务器就会频繁地接收和发送 请求图片&#xff0c;造成服务器请求压力过大&#xff0c;这将大大降低页面的加载速度。 因此&#xff0c;为了有效地减…

服务器数据恢复—raid5热备盘上线同步数据失败的如何恢复数据

服务器数据恢复环境&故障&分析&#xff1a; 一台存储上有一组由多块硬盘组建的raid5阵列&#xff0c;该raid5阵列中的一块硬盘掉线&#xff0c;热备盘自动上线同步数据的过程中&#xff0c;raid阵列中又有一块硬盘掉线&#xff0c;热备盘的数据同步被中断&#xff0c;r…

Pytorch入门实战 P2-CIFAR10彩色图片识别

目录 一、前期准备 1、数据集CIFAR10 2、判断自己的设备&#xff0c;是否可以使用GPU运行。 3、下载数据集&#xff0c;划分好训练集和测试集 4、加载训练集、测试集 5、取一个批次查看下 6、数据可视化 二、搭建简单的CNN网络模型 三、训练模型 1、设置超参数 2、编…

【深入理解设计模式】命令设计模式

命令设计模式&#xff1a; 命令模式&#xff08;Command Pattern&#xff09;是一种行为型设计模式&#xff0c;它将请求封装为一个对象&#xff0c;从而使你可以用不同的请求对客户端进行参数化&#xff0c;对请求排队或记录请求日志&#xff0c;以及支持可撤销的操作。 概述…

onecloud刷CasaOS系统后如何安装内网穿透实现公网访问本地文件

文章目录 1. CasaOS系统介绍2. 内网穿透安装3. 创建远程连接公网地址4. 创建固定公网地址远程访问 2月底&#xff0c;玩客云APP正式停止运营&#xff0c;不再提供上传、云添加功能。3月初&#xff0c;有用户进行了测试&#xff0c;局域网内的各种服务还能继续使用&#xff0c;但…

国产化兼容问题与解决办法: java.lang.ClassNotFoundException: javafx.util.Pair

先说解决办法:找一个大版本相同的jdk将/jre/lib/ext中的所有jar包放到服务器jdk相同路径下,跳过相同名称. 下面是详细的问题分析,感觉啰嗦或者没有用,可以直接关闭 运行环境: 服务器:麒麟v10.x86_64 jdk:BiSheng (build 1.8.0_402-b11) 问题描述: 将程序部署在国产化服务器…

STC89C52单片机 启动!!!(一)

跑马灯实现 直接上代码 #include<regx52.h> sbit D1P2^0; sbit D2P2^1; sbit D3P2^2; sbit D4P2^3; sbit D5P2^4; sbit D6P2^5; sbit D7P2^6; sbit D8P2^7; void delay(int num){while(num--){} } void led_running(){//从第1盏灯到第8盏灯依次点亮D10;delay(40000);D2…

unity2D生成9*9格子

1.创建一个空对象和格子 2将格子做成预制体&#xff08;直接将格子拖到这里即可&#xff0c;拖了过后删掉原来的格子&#xff09; 3.创建脚本并将脚本拖到空对象上 using System.Collections; using System.Collections.Generic; using UnityEngine;public class CreateMap : M…

2024年雪糕线上市场未来发展趋势分析(2024京东淘宝天猫雪糕数据分析报告)

据相关媒体报道&#xff0c;北京多位雪糕批发商称钟薛高停产了&#xff0c;从年前开始就已经不供货了。还有记者实探钟薛高的北京总部&#xff0c;发现有不少人离职&#xff0c;办公区内仅剩零星几人。 从60元到2.5元&#xff0c;钟薛高在这两年经历了不少风波&#xff0c;终究…

鸿蒙不再适合JS语言开发

ArkTS是鸿蒙生态的应用开发语言。它在保持TypeScript&#xff08;简称TS&#xff09;基本语法风格的基础上&#xff0c;对TS的动态类型特性施加更严格的约束&#xff0c;引入静态类型。同时&#xff0c;提供了声明式UI、状态管理等相应的能力&#xff0c;让开发者可以以更简洁、…

mysql事务(MVCC机制:undo日志)(mysql执行过程:redo日志,Buffer Pool缓存池)

事务 目的&#xff1a;保证数据的最终一致性## 事务的目的 事务的4大特性&#xff08;ACID&#xff09; 1.原子性(Atomicity):由undo log日志来保证 2.一致性(Consistency):使用事务的最终目的&#xff0c;由业务代码正确逻辑保证,比如错误的try-catch 3.隔离性(Isolation):…

在任意一个文件下,进入cmd

直接在界面上输入cmd&#xff0c;回车就出来了

安卓六大布局

LinearLayout&#xff08;线性布局&#xff09; 1.简介 线性布局在开发中使用最多&#xff0c;具有垂直方向与水平方向的布局方式。LinearLayout 默认是垂直排列的&#xff0c;但是可以通过设置 android:orientation 属性来改变为水平排列。 2.常用属性 orientation&#xf…

Windows系统下载安装Emby结合内网穿透实现公网访问本地影音网站

文章目录 1.前言2. Emby网站搭建2.1. Emby下载和安装2.2 Emby网页测试 3. 本地网页发布3.1 注册并安装cpolar内网穿透3.2 Cpolar云端设置3.3 Cpolar内网穿透本地设置 4.公网访问测试5.结语 1.前言 在现代五花八门的网络应用场景中&#xff0c;观看视频绝对是主力应用场景之一&…

3.2 RK3399项目开发实录-初次使用的环境搭建(物联技术666)

通过百度网盘分享的文件&#xff1a;嵌入式物联网单片… 链接:https://pan.baidu.com/s/1Zi9hj41p_dSskPOhIUnu9Q?pwd8qo1 提取码:8qo1 复制这段内容打开「百度网盘APP 即可获取」 1. 用户和密码 1.1. Ubuntu Desktop 系统 Ubuntu Desktop 系统开机启动后&#xff0c;自动登录…

权限管理和操作指令

文章目录 前言一、文件的权限分类二、操作时无相应权限解决办法1.使用sudo指令2.修改文档权限 总结 前言 &#x1f4a6; Linux操作系统中&#xff0c;主要都是对文件进行操作&#xff0c;完成读写或者执行功能。Ubuntu 下我们会常跟用户权限打交道&#xff0c;权限就是用户对于…

python操作dataframe--打乱df的顺序

在Python中&#xff0c;可以使用Pandas库来操作DataFrame。要打乱DataFrame的顺序&#xff0c;可以使用sample方法来实现。以下是一个示例代码&#xff1a; import pandas as pd# 创建一个示例DataFrame data {A: [1, 2, 3, 4, 5],B: [10, 20, 30, 40, 50]} df pd.DataFrame…

为什么ERP与MES集成那么难搞?怎么有效解决这一难题

在现代企业信息化进程中&#xff0c;ERP&#xff08;企业资源规划&#xff09;和MES&#xff08;制造执行系统&#xff09;作为企业管理的核心信息系统&#xff0c;它们之间的深度集成是提升生产效率、实现精益管理和智能决策的关键环节。然而&#xff0c;ERP与MES集成并非易事…

【Python】成功解决NameError: name ‘sns‘ is not defined

【Python】成功解决NameError: name ‘sns’ is not defined &#x1f308; 个人主页&#xff1a;高斯小哥 &#x1f525; 高质量专栏&#xff1a;Matplotlib之旅&#xff1a;零基础精通数据可视化、Python基础【高质量合集】、PyTorch零基础入门教程&#x1f448; 希望得到您…

1个二维码能包含多个视频吗?制作视频二维码的方法

二维码在生活中现在随处可见&#xff0c;除了用于支付之外&#xff0c;展示内容也可以通过二维码来展现&#xff0c;比如常见的视频、图片、文件、音频等内容都可以通过二维码来展现。那么当我们需要将多个视频存入一个二维码中展示时&#xff0c;该如何利用二维码生成器的工具…
最新文章