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

news2024/9/25 19:18:54

大语言模型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.coloradmin.cn/o/1517459.html

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

相关文章

lab3090连接

淘宝安装包&#xff0c;镜像包放在了F盘&#xff0c;文件夹名为“torch” 远程连接服务器 服务器&#xff0c;192.168.7.194&#xff0c;端口1324&#xff0c;账号&#xff0c;llf&#xff0c;密码123456 进入容器&#xff1a; docker attach llf_pytorch 创建后端jupyte…

【Claude 3】关于注册Claude 3模型的操作演示

文章目录 1. 登录Claude URL2. 海外手机号码验证3. 获取手机验证码4. 输入Claude用户名称5. 同意确认使用协议6. 点击去开始体验7. 注册登录成功8. 重新登录进入Claude9. 参考链接PS&#xff1a;所遇问题&#xff1a;⚠️注册即封号&#xff01;&#xff01;&#xff01; 1. 登…

Redis 除了做缓存,还能做什么?

分布式锁&#xff1a;通过 Redis 来做分布式锁是一种比较常见的方式。通常情况下&#xff0c;我们都是基于 Redisson 来实现分布式锁。关于 Redis 实现分布式锁的详细介绍&#xff0c;可以看我写的这篇文章&#xff1a;分布式锁详解open in new window 。限流&#xff1a;一般是…

机试:蛇形矩阵

问题描述: 代码示例: //蛇形矩阵 #include <bits/stdc.h> using namespace std;int main(){int n;cout << "输入样例" << endl; cin >> n;int k 1; for(int i 0; i < n; i){if( i %2 0){//单数行for(int j 0; j < n; j){ cout &…

Linux本地部署开源AI的PDF工具—Stirling PDF并实现公网随时访问

文章目录 1. 安装Docker2. 本地安装部署StirlingPDF3. Stirling-PDF功能介绍4. 安装cpolar内网穿透5. 固定Stirling-PDF公网地址 本篇文章我们将在Linux上使用Docker在本地部署一个开源的PDF工具——Stirling PDF&#xff0c;并且结合cpolar的内网穿透实现公网随时随地访问。 S…

88. 合并两个有序数组 (Swift版本)

题目 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2&#xff0c;另有两个整数 m 和 n &#xff0c;分别表示 nums1 和 nums2 中的元素数目。 请你 合并 nums2 到 nums1 中&#xff0c;使合并后的数组同样按 非递减顺序 排列。 注意&#xff1a;最终&#xff0c;合并…

Java高级编程—泛型

文章目录 1.为什么要有泛型 (Generic)1.1 泛型的概念1.2 使用泛型后的好处 2.在集合中使用泛型3.自定义泛型结构3.1 自定义泛型类、泛型接口3.2 自定义泛型方法 4.泛型在继承上的体现5.通配符的使用5.1 基本使用5.2 有限制的通配符的使用 1.为什么要有泛型 (Generic) Java中的…

为什么我接不到大单?

以前的领导创业多年&#xff0c;今天找我聊了一下想让我跟他一起做点事情&#xff0c;聊了一下我的现状&#xff0c;突然让我明白为何我一直都接不到大单了 说起来也不是完全没有好的机会&#xff0c;貌似有点像“公交车定律”&#xff0c;当我很忙碌的时候订单一个接一个&…

IP在网络通信中的重要作用

IP&#xff0c;全称Internet Protocol&#xff0c;即网际互连协议&#xff0c;是TCP/IP体系中的网络层协议。IP作为整个TCP/IP协议族的核心&#xff0c;是构成互联网的基础。它的作用重大且深远&#xff0c;下面将详细阐述IP的定义及其在网络通信中的重要作用。 首先&#xff0…

LVGL移植到ARM开发板(GEC6818开发板)

LVGL移植到ARM开发板&#xff08;GEC6818开发板&#xff09; 一、LVGL概述 LVGL&#xff08;Light and Versatile Graphics Library&#xff09;是一个开源的图形用户界面库&#xff0c;旨在提供轻量级、可移植、灵活和易于使用的图形用户界面解决方案。 它适用于嵌入式系统…

陈景东:集中与分布式拾音与声信号处理 | 演讲嘉宾公布

一、声音与音乐技术专题论坛 声音与音乐技术专题论坛将于3月28日同期举办&#xff01; 声音的应用领域广泛而深远&#xff0c;从场所识别到乐器音响质量评估&#xff0c;从机械故障检测到心肺疾病诊断&#xff0c;声音都发挥着重要作用。在互联网、大数据、人工智能的时代浪潮中…

爬虫逆向实战(35)-MyToken数据(MD5加盐)

一、数据接口分析 主页地址&#xff1a;MyToken 1、抓包 通过抓包可以发现数据接口是/ticker/currencyranklist 2、判断是否有加密参数 请求参数是否加密&#xff1f; 通过查看“载荷”模块可以发现有一个code参数 请求头是否加密&#xff1f; 无 响应是否加密&#xf…

【OpenCV实战】基于OpenCV中DNN(深度神经网络)使用OpenPose模型实现手势识别详解

一、手部关键点检测 如图所示,为我们的手部关键点所在位置。第一步,我们需要检测手部21个关键点。我们使用深度神经网络DNN模块来完成这件事。通过使用DNN模块可以检测出手部21个关键点作为结果输出,具体请看源码。 二,openpose手势识别模型 OpenPose的原理基于卷积神经网…

Arcgis新建位置分配求解最佳商店位置

背景 借用Arcgis帮助文档中的说明:在本练习中,您将为连锁零售店选择可以获得最大业务量的商店位置。主要目标是要将商店定位在人口集中地区附近,因为这种区域对商店的需求量较大。设立这一目标的前提是假设人们往往更多光顾附近的商店,而对于距离较远的商店则较少光顾。您…

构建用户身份基础设施,推动新能源汽车高质量发展

随着市场进入智能电动汽车时代&#xff0c;车企们发现&#xff0c;在激烈竞争的市场中不断增长&#xff0c;并不是一件容易的事。《麻省理工科技评论》&#xff0c;前段时间写了一篇报道&#xff1a;中国是如何称霸电动汽车世界的&#xff1f;“过去两年&#xff0c;中国电动汽…

学点Java打小工——Day2Day3一点作业

1 猜数字&#xff08;10次机会&#xff09; 随机生成[1,1000]的一个数&#xff0c;输入你猜的数程序会给出反馈&#xff0c;直到猜对或次数用尽(10次)。 //猜数字 10次机会Testpublic void guessNumber() {Random random new Random();// [0, 1000) 1// [1, 1000]int num ra…

【JavaScript】JavaScript 简介 ④ ( 解释型语言 和 编译型语言 | 计算机程序本质 | 编译器 和 解释器 )

文章目录 一、 解释型语言 和 编译型语言1、计算机程序本质2、编译器 和 解释器3、编译器 分析4、解释器 分析 一、 解释型语言 和 编译型语言 1、计算机程序本质 计算机 的 程序 是在 CPU 上执行的 , CPU 上执行的只有匹配该 CPU 的机器码指令 , 不同类型的 CPU 执行的 机器码…

【django framework】ModelSerializer+GenericAPIView,如何获取HTTP请求头中的信息(远程IP、UA等)

【django framework】ModelSerializerGenericAPIView&#xff0c;如何获取HTTP请求头中的信息(远程IP、UA等) 某些时候&#xff0c;我们不得不获取调用当前接口的客户端IP、UA等信息&#xff0c;如果是第一次用Django Restframework&#xff0c;可能会有点懵逼&#xff0c;那么…

【分布式websocket】群聊中的各种难点以及解决推拉结合【第16期】

前言 群聊中未读消息如何设计&#xff0c;以及是推消息还是拉去消息如何选择是需要讨论的。推送消息是推送全量消息还是推送信号消息让客户端再去拉取。其中方案如何选型会比较纠结。 首先基本的推拉结合思路是在线用户推送消息。用户离线的话上线去拉取消息。这是简单的推拉结…

Nginx、LVS、HAProxy工作原理和负载均衡架构

当前大多数的互联网系统都使用了服务器集群技术&#xff0c;集群是将相同服务部署在多台服务器上构成一个集群整体对外提供服务&#xff0c;这些集群可以是 Web 应用服务器集群&#xff0c;也可以是数据库服务器集群&#xff0c;还可以是分布式缓存服务器集群等等。 在实际应用…