LangChain(0.0.340)官方文档三:Prompts上——自定义提示模板、使用实时特征或少量示例创建提示模板

news2024/10/6 4:14:04

文章目录

    • 一、 Prompt templates
      • 1.1 langchain_core.prompts
      • 1.2 PromptTemplate
        • 1.2.1 简介
        • 1.2.2 ICEL
        • 1.2.3 Validate template
      • 1.3 ChatPromptTemplate
        • 1.3.1 使用role创建
        • 1.3.2 使用MessagePromptTemplate创建
        • 1.3.3 自定义MessagePromptTemplate
          • 1.3.3.1 自定义消息角色名
          • 1.3.3.2 自定义消息
        • 1.3.4 LCEL
        • 1.3.5 chat_prompt输出的三种format方法
    • 二、 自定义PromptTemplate
    • 三、使用特征存储库(Feature Store)的实时特征创建模板
      • 3.1 What Is a Feature Store?
        • 3.1.1 Feature Store简介
        • 3.1.2 Feature Store的组成
      • 3.2 Feast
    • 四、使用少量示例创建 prompt templates
      • 4.1 使用示例集(example set)
        • 4.1.1 创建示例集
        • 4.1.2 创建示例格式化器
        • 4.1.3 创建FewShotPromptTemplate
      • 4.2 使用示例选择器​(example selector)
        • 4.2.1 根据示例集创建ExampleSelector ​
        • 4.2.2 将示例选择器输入 FewShotPromptTemplate
    • 五、使用少量示例创建ChatPromptTemplate
      • 5.1 使用示例集
      • 5.2 使用示例选择器

LangChain官网、LangChain官方文档 、langchain Github、langchain API文档、llm-universe

LangChain 提供了几个类和函数来帮助构建和使用提示:

  • Prompt templates:提示模板,可参数化的模型输入
  • Example selectors:如果你有大量示例,示例选择器可以动态选择要包含在提示中的示例

下面一一进行介绍。

一、 Prompt templates

参考文档《Prompt templates》

  LangChain提供了用于生成语言模型提示的预定义模板。这些模板包括指令、少量示例以及适用于特定任务的具体背景和问题。本质上有两种不同的提示模板可用 -——字符串提示模板PromptTemplate和聊天提示模板ChatPromptTemplate。前者提供字符串格式的简单提示,而后者生成更结构化的提示以与聊天 API 一起使用。

1.1 langchain_core.prompts

在 langchain_core.prompts文档中有介绍,其Class hierarchy为:

BasePromptTemplate --> PipelinePromptTemplate
                       StringPromptTemplate --> PromptTemplate
                                                FewShotPromptTemplate
                                                FewShotPromptWithTemplates
                       BaseChatPromptTemplate --> AutoGPTPrompt
                                                  ChatPromptTemplate --> AgentScratchPadChatPromptTemplate



BaseMessagePromptTemplate --> MessagesPlaceholder
                              BaseStringMessagePromptTemplate --> ChatMessagePromptTemplate
                                                                  HumanMessagePromptTemplate
                                                                  AIMessagePromptTemplate
                                                                  SystemMessagePromptTemplate

  先看一下BasePromptTemplate,它是所有prompt templates的基类,用于生成特定格式的提示。该类继承自RunnableSerializable类(泛型类,泛型参数是Dict和PromptValue)和ABC类(Abstract Base Class,抽象基类),包含以下参数:

参数类型必填描述
input_typesDict[str, Any]可选期望的提示模板变量类型的字典。如果未提供,则假定所有变量均为字符串。
input_variablesList[str]必选期望的提示模板变量的名称列表。
output_parserOptional[lBaseOutputParser] = None可选用于解析调用此格式化提示的LLM输出的方法。
partial_variablesMapping[str, Union[str, Callable[[], str]]]可选字典映射,包含部分变量的名称、类型或生成值的回调函数。

该类还包含以下方法:

  1. 异步方法:
    类中定义了多个异步方法,如abatchainvokeastream等,用于异步执行任务。这些方法提供了默认实现,但可以在子类中进行覆盖以实现更高效的批处理或异步执行。

  2. 配置相关的方法:

    • config_schema方法返回一个 Pydantic 模型,用于验证配置。
    • configurable_fields方法返回一个可配置字段的序列化对象。
  3. 输入输出相关的方法:

    • get_input_schemaget_output_schema方法返回 Pydantic 模型,用于验证输入和输出。
    • invoke方法用于将单个输入转换为输出。
  4. 流式处理相关方法:

    • astream_log方法用于流式处理运行输出,包括内部运行的日志等信息。
    • astream方法是astream_log方法的默认实现。
  5. 其他方法:

    • 包括一系列用于处理配置、模型序列化等的方法,如lc_idjsondict等。
  6. 属性:

    • 包括InputTypeOutputTypeconfig_specs等属性,用于获取输入类型、输出类型和配置规范。
  7. 类方法:

    • 包括用于解析对象、生成 JSON 表示、更新引用等类方法。

  总体而言,该类是一个通用的 Prompt 模板类,提供了一系列用于处理配置、输入输出、异步执行等功能的方法。如果需要使用该模板,可以通过继承该类并实现必要的方法来定制特定的 Prompt 行为。

  BaseMessagePromptTemplate继承自SerializableABC(Abstract Base Class),它是消息提示模板的基类,用于创建新模型并验证输入数据。

  1. 类方法 construct:创建一个新模型,通过解析和验证关键字参数中的输入数据。如果输入数据无法解析为有效模型,则引发ValidationError。参数有 _fields_set(可选的字段集合)和 **values(其他数值),返回新的模型实例。

  2. 类方法 copy:复制模型,可选择包含、排除、更改哪些字段,返回新的模型实例。

  3. 类方法 dict:生成模型的字典表示,可选择包含或排除特定字段。

  4. 抽象方法 format_messages:从关键字参数中格式化消息,应返回BaseMessage的列表。

    • 参数:kwargs,用于格式化的关键字参数。
    • 返回:BaseMessage的列表。
  5. 其他类方法和属性:略

1.2 PromptTemplate

1.2.1 简介

  使用PromptTemplate可以为字符串提示创建模板。默认情况下,PromptTemplate使用Python的str.format语法进行模板化。

  • Python f-string template:
from langchain.prompts import PromptTemplate

prompt_template = PromptTemplate.from_template(
    "Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")
'Tell me a funny joke about chickens.'

该模板支持任意数量的变量,包括无变量:

from langchain.prompts import PromptTemplate

prompt_template = PromptTemplate.from_template("Tell me a joke")
prompt_template.format()
'Tell me a joke'

  PromptTemplate 默认使用 Python f-string 作为其模板格式,但目前也支持 jinja2格式。通过 template_format 参数可指定 jinja2 (参考《Template formats》)。

  • jinja2 template:
from langchain.prompts import PromptTemplate

jinja2_template = "Tell me a {{ adjective }} joke about {{ content }}"
prompt = PromptTemplate.from_template(jinja2_template, template_format="jinja2")

prompt.format(adjective="funny", content="chickens")
# Output: Tell me a funny joke about chickens.
1.2.2 ICEL

  PromptTemplateChatPromptTemplate 实现了Runnable接口,这是LangChain表达式语言(LCEL)的基本构建块。这意味着它们支持invokeainvokestreamastreambatchabatchastream_log等调用。

  PromptTemplate 接受一个字典(prompt变量)并返回一个StringPromptValue。ChatPromptTemplate 接受一个字典并返回一个 ChatPromptValue,这些value对象可以转换成不同的格式,为后续使用和处理提供了便利。

  根据StringPromptValue文档可知:StringPromptValue类继承自基类PromptValue,表示一个字符串prompt的值,有以下方法:

  • __init__方法:用于根据关键字参数构建一个StringPromptValue实例。需要一个必填的text参数,表示prompt的文本。还有可选的type参数,默认为’StringPromptValue’,表示值的类型。如果输入数据不合法会抛出ValidationError。
  • copy 方法:复制模型的方法,可以选择包含、排除或更新某些字段。deep=True时为深拷贝。
  • dict 方法:将模型转换为字典的方法,可以选择包含或排除某些字段。
  • to_messages 方法:将prompt的值转换为消息列表并返回。
  • to_string 方法:将prompt的值转换为字符串并返回。
prompt_val = prompt_template.invoke({"adjective": "funny", "content": "chickens"})

prompt_val     			  # 输出: StringPromptValue(text='Tell me a joke')
prompt_val.to_string()    # 输出:'Tell me a joke'
prompt_val.to_messages()  # 输出:[HumanMessage(content='Tell me a joke')]
prompt_val.copy(update={"text": "Hello! How are you?"})  	# 输出:StringPromptValue(text='Hello! How are you?')
prompt.dict()  			  # 输出:{'text': 'Tell me a funny joke about chickens.'}
prompt.json()   		  # 输出:'{"text": "Tell me a funny joke about chickens."}'
prompt.json().to_json()
{'lc': 1,
 'type': 'constructor',
 'id': ['langchain', 'prompts', 'base', 'StringPromptValue'],
 'kwargs': {'text': 'Tell me a funny joke about chickens.'}}
1.2.3 Validate template

参考《Validate template》

  PromptTemplate会通过检查输入的变量是否与模板中定义的变量相匹配来验证模板字符串。如果存在不匹配的变量,默认情况下会引发ValueError异常。你可以通过设置validate_template=False,禁用这种验证行为,因此不再会引发错误。

template = "I am learning langchain because {reason}."

prompt_template = PromptTemplate(template=template,
                                 input_variables=["reason", "foo"]) 	# ValueError due to extra variables
prompt_template = PromptTemplate(template=template,
                                 input_variables=["reason", "foo"],
                                 validate_template=False) 				# No error

1.3 ChatPromptTemplate

1.3.1 使用role创建

  ChatPromptTemplate是 chat models 的聊天消息列表。 每个聊天消息都与内容相关联,并具有一个称为role(角色)的额外参数。例如,在 OpenAI 聊天补全 API 中,聊天消息可以与 AI 助手、人类或系统角色相关联。

  创建一个聊天提示模板就像这样:

from langchain.prompts import ChatPromptTemplate

chat_template = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful AI bot. Your name is {name}."),
        ("human", "Hello, how are you doing?"),
        ("ai", "I'm doing well, thanks!"),
        ("human", "{user_input}"),
    ]
)

messages = chat_template.format_messages(name="Bob", user_input="What is your name?")
messages
[SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
 HumanMessage(content='Hello, how are you doing?'),
 AIMessage(content="I'm doing well, thanks!"),
 HumanMessage(content='What is your name?')]
1.3.2 使用MessagePromptTemplate创建

  ChatPromptTemplate.from_messages接受多种消息表示方式。比如除了使用上面提到的(type, content)的2元组表示法之外,你还可以传入MessagePromptTemplate或BaseMessage的实例,这为你在构建聊天提示时提供了很大的灵活性。下面用百度千帆进行演示:

import os
import openai,qianfan

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key =os.environ['OPENAI_API_KEY']
qianfan.qianfan_ak=os.environ['QIANFAN_AK']
qianfan.qianfan_sk=os.environ['QIANFAN_SK']
from langchain.chat_models import ChatOpenAI
from langchain.prompts import HumanMessagePromptTemplate
from langchain.schema.messages import SystemMessage

chat_template = ChatPromptTemplate.from_messages(
    [
        SystemMessage(
            content=(
                "You are a helpful assistant that re-writes the user's text to "
                "sound more upbeat."
            )
        ),
        HumanMessagePromptTemplate.from_template("{text}"),
    ]
)

llm = ChatOpenAI()
llm(chat_template.format_messages(text="i dont like eating tasty things."))
AIMessage(content='没有什么是美味的食物不能使我们的身体得到营养和能量,尝试一些新的食物可能会改变你的观点,体验新事物可能帮助你更好地认识各种美味的食物,也可能带来很多有趣的发现。如果暂时不愿意尝试,也请不要有负罪感,相信有一天你可能会改变你的看法。', additional_kwargs={'id': 'as-ezqwy06ymf', 'object': 'chat.completion', 'created': 1700925548, 'result': '没有什么是美味的食物不能使我们的身体得到营养和能量,尝试一些新的食物可能会改变你的观点,体验新事物可能帮助你更好地认识各种美味的食物,也可能带来很多有趣的发现。如果暂时不愿意尝试,也请不要有负罪感,相信有一天你可能会改变你的看法。', 'is_truncated': False, 'need_clear_history': False, 'usage': {'prompt_tokens': 8, 'completion_tokens': 60, 'total_tokens': 68}})
1.3.3 自定义MessagePromptTemplate

参考《Types of MessagePromptTemplate 》

  LangChain提供了不同类型的 MessagePromptTemplate 。最常用的是 AIMessagePromptTemplate 、 SystemMessagePromptTemplate 和 HumanMessagePromptTemplate ,它们分别创建 AI 消息、系统消息和用户消息。

1.3.3.1 自定义消息角色名

  如果要创建任意角色获取聊天消息,可以使用 ChatMessagePromptTemplate,它允许用户指定角色名称。

from langchain.prompts import ChatMessagePromptTemplate

prompt = "May the {subject} be with you"

chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)
chat_message_prompt.format(subject="force")
ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')
1.3.3.2 自定义消息

  LangChain 还提供了 MessagesPlaceholder ,它使您可以完全控制格式化期间要呈现的消息。当您不确定消息提示模板应使用什么角色或希望在格式化期间插入消息列表时,这会很有用。

from langchain.prompts import MessagesPlaceholder

human_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name="conversation"), human_message_template])
human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""\
1. Choose a programming language: Decide on a programming language that you want to learn.

2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.

3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")

chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages()
[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}),
 AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn. \n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}),
 HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]
1.3.4 LCEL

  ChatPromptTemplate 也支持LCEL, ChatPromptValue和StringPromptValue的方法也基本一致:

chat_val = chat_template.invoke({"text": "i dont like eating tasty things."})
chat_val.to_messages()
[SystemMessage(content="You are a helpful assistant that re-writes the user's text to sound more upbeat."),
HumanMessage(content='i dont like eating tasty things.')]
chat_val.to_string()
 "System: You are a helpful assistant that re-writes the user's text to sound more upbeat.\nHuman: i dont like eating tasty things."
1.3.5 chat_prompt输出的三种format方法

参考《Format template output》

chat_prompt.format 方法的输出可以以三种形式获取:

  • 字符串形式:调用 chat_prompt.format() 或者 chat_prompt.format_prompt().to_string() 可以直接获取格式化后的字符串作为输出。
output = chat_prompt.format(input_language="English", output_language="French", text="I love programming.")
output
'System: You are a helpful assistant that translates English to French.\nHuman: I love programming.'
# or alternatively
output_2 = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_string()

assert output == output_2
  • 消息(Message)列表形式:调用 chat_prompt.format_prompt().to_messages() 可以获取格式化输出对应的一系列消息对象列表。
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
 HumanMessage(content='I love programming.', additional_kwargs={})]
  • ChatPromptValue 对象形式:直接调用 chat_prompt.format_prompt() 可以获取封装了格式化输出信息的 ChatPromptValue 对象。
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.")
ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})])

二、 自定义PromptTemplate

参考文档《Custom prompt template》

  LangChain提供了一组默认的提示模板,用于生成各种任务的提示。然而,有时默认模板可能无法满足特定需求,例如希望为语言模型创建具有特定动态指令的自定义模板。本节介绍使用PromptTemplate创建自定义提示。

  为了创建自定义字符串提示模板,需要满足两个要求:

  • 必须具有 input_variables 属性,指明模板需要什么输入变量;
  • 必须定义一个 format 方法,该方法接受与预期 input_variables 相对应的关键字参数,并返回格式化后的提示。

  示例:创建一个将函数名称作为输入的自定义提示模板,该模板将格式化提示,以提供函数的源代码。首先,需要创建一个函数,该函数将根据函数名称返回函数的源代码。

import inspect

def get_source_code(function_name):
    # Get the source code of the function
    return inspect.getsource(function_name)

inspect是python内置的模块,用于获取源代码等信息

  接下来,我们将创建一个自定义提示模板,该模板接受函数名称作为输入,并格式化提示以提供函数的源代码。另外,我们从 pydantic 模块中导入 BaseModel 类和 validator 装饰器,用于创建数据模型和验证输入。

from langchain.prompts import StringPromptTemplate
from pydantic import BaseModel,validator

# 根据给定的函数名称和源代码,生成一个关于函数的英语解释
PROMPT = """\
Given the function name and source code, generate an English language explanation of the function.
Function Name: {function_name}
Source Code:
{source_code}
Explanation:
"""

class FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel):
    """一个自定义的提示模板,接受函数名称作为输入,并格式化提示模板以提供函数的源代码。"""

    @validator("input_variables")		# 使用 validator 装饰器定义了一个用于验证输入变量的方法。
    def validate_input_variables(cls, v):
        """定义了验证输入变量的方法,确保只有一个名为 function_name 的输入变量。"""
        if len(v) != 1 or "function_name" not in v:
            raise ValueError("function_name 必须是唯一的输入变量。")
        return v

    def format(self, **kwargs) -> str:
        # 获取函数的源代码
        source_code = get_source_code(kwargs["function_name"])

        # 生成要发送到语言模型的提示
        prompt = PROMPT.format(
            function_name=kwargs["function_name"].__name__, source_code=source_code
        )
        return prompt

    def _prompt_type(self):
        return "function-explainer"
  • 自定义提示模板FunctionExplainerPromptTemplate,它接受函数名称作为输入变量,并通过inspect模块获取函数源代码,将源代码嵌入到提示文本中

  • 提示模板继承了StringPromptTemplate和pydantic的BaseModel,后者提供了输入验证功能

  • @validator("input_variables") :这是一个 pydantic 的 validator 装饰器。作用是对 input_variables 这个属性的值进行验证。一旦有代码给 input_variables 赋值,就会自动触发验证。

  • validate_input_variables方法:定义了对input_variables 验证逻辑,

    • cls 参数代表的是当前提示模板类自身,用于在类级别方法中访问类本身。这个方法被定义为类方法(使用了 @classmethod 装饰器),因此它的第一个参数是类自身而不是实例自身(self)。
    • v 参数则代表的是要验证的 input_variables 属性的值。
  • format方法生成最终的提示文本,包含函数名称和源代码(对于一个函数func,func.__name__ 可以获取到这个函数的名称,作为一个字符串,即func.__name__=“func”

  • _prompt_type方法返回提示类型的字符串标识

现在我们可以使用这个提示模板了:

fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])

# 根据"get_source_code"函数生成提示
prompt = fn_explainer.format(function_name=get_source_code)
prompt
Given the function name and source code, generate an English language explanation of the function.
Function Name: get_source_code
Source Code:
def get_source_code(function_name):
    # Get the source code of the function
    return inspect.getsource(function_name)

Explanation:
  • 创建实例 fn_explainer 时,通过构造函数参数传入了 input_variables 的值:[“function_name”],对应FunctionExplainerPromptTemplate 类方法validate_input_variables 的 v 参数。
  • format 方法签名为def format(self, **kwargs) -> str:,这里的 **kwargs 表示它可以接受任意多个关键字参数。这么做的好处是:
    • 灵活:调用者可以根据需要传入任意多个参数,没有数量和名称的限制。
    • 解耦:format 内部的代码不依赖任何具体的外部参数。即使外部参数改变也不影响内部实现,因为内部只需要通过 kwargs 访问需要的参数即可。

例如,我们可能后面需要加入一个新参数 description,用于生成prompt的函数描述。使用 **kwargs 的话Caller端只要:

prompt = fn_explainer.format(
  function_name=get_source_code,
  description="utility function"
)

而无需改动 format 内部的代码。如果是严格的参数签名,那么任何新增参数都需要修改 format,这是很大的耦合。

三、使用特征存储库(Feature Store)的实时特征创建模板

参考《Connecting to a Feature Store》

3.1 What Is a Feature Store?

参考《What Is a Feature Store?》

3.1.1 Feature Store简介

  在实际将机器学习系统投入生产中,团队面临着多个数据方面的挑战,涉及到获取正确的原始数据、构建特征、将特征组合成训练数据、在生产环境中计算和提供特征,以及监控生产环境中的特征。特征存储(Feature Store)通过减少数据工程工作的重复性、加速机器学习生命周期,并促进跨团队合作,为组织带来了多方面的益处。
在这里插入图片描述

  特征存储的核心作用是提供了一个高效、可靠且集中管理特征数据的平台,集中式的存储和管理特征数据。Feature stores具有以下特点:

  • 集中管理特征数据:当特征注册到特征存储中后,不同团队和模型都可以共享和重用这些特征,减少了数据工程工作的重复,还可以确保数据一致性和可靠性。

  • 数据版本控制和跟踪: 它允许对特征数据进行版本控制,记录数据的变化和更新历史。这对于追踪数据演变过程、复现实验以及监控模型性能变化都非常有用。

  • 实现训练数据和服务数据的一致性: 用于训练模型的特征定义必须与在线服务中提供的特征完全匹配,否则将引入训练-服务偏差,这可能会导致灾难性且难以调试的模型性能问题。

  • 特征实时性:在生产环境中,确保模型所使用的特征数据是最新且相关的是至关重要的。Feature Store 提供了机制来保证数据的实时性和一致性,以确保模型在推理时使用的是准确的数据。

  • 特征工程: Feature Store 通常集成了数据预处理和特征工程功能,自动化特征计算、回填和日志记录。使新的机器学习项目能够使用经过筛选、准备好用于生产的特征库。
    在这里插入图片描述

3.1.2 Feature Store的组成

  现代特征存储有五个主要组成部分:转换(Transformation)、存储(Storage)、提供(Serving)、监控(Monitoring)和特征注册(Feature Registry)。
在这里插入图片描述

  1. 转换(Transformation):负责对数据进行处理,生成特征值。支持批处理、流式处理和按需处理三种方式。重用代码,避免训练服务数据偏差。

  2. 存储(Storage):提供离线存储用于历史数据,方便模型训练;提供在线存储用于低延迟特征服务。通常与数据湖或数据库集成。使用实体为中心的数据模型。

  3. 服务(Serving):通过高性能API实时提供特征数据。确保训练和服务使用一致的特征视图,避免偏差。支持通过SDK访问用于模型训练。

  4. 监控(Monitoring):检测数据质量、一致性等问题,确保系统运行正常。可以聚合和关联多个指标,方便定位根源。

  5. 注册表(Registry):中心化管理特征定义和元数据。配置和调度特征转换、存储、服务等工作。提供接口与其他系统集成。可追踪来源和依赖,支持审计。

3.2 Feast

参考《Connecting to a Feature Store》、feast Github、Feast文档

  在生产LLM应用时,个性化用户体验非常关键。特征存储的核心概念是保持数据的新鲜度和相关性,特别适用于将大型语言模型(LLM)应用于实际生产环境中。LangChain提供了一种简单的方法来将这些数据与LLM结合使用。

  Feast是一个流行的开源特征存储框架。使用说明详见Feast文档。假设你已经按照Feast的README中的说明进行了设置和准备。接下来演示如何使用自定义了提示模板类,将Feast提供的特征数据注入到提示文本生成逻辑中,最终输出整合了实时特征的提示内容。

from feast import FeatureStore

# You may need to update the path depending on where you stored it
feast_repo_path = "../../../../../my_feature_repo/feature_repo/"
# 初始化连接到 Feast 特征存储(Feature Store)。
store = FeatureStore(repo_path=feast_repo_path)

  FeatureStore 是 Feast 提供的用于访问特征存储的客户端类,初始化时需要指定 repo_path 参数,指向预先在本地搭建的 Feast 特征库存储路径,然后就可以通过 store实例访问远程存储中的特征数据。

  下面我们将建立一个自定义的FeastPromptTemplate。这个提示模板将接收一个driver id,查找他们的统计数据,并将这些统计数据格式化为一个提示信息。

  请注意,这个提示模板的输入仅是driver id,因为这是用户定义的唯一部分(所有其他变量都在提示模板内部查找)。

from langchain.prompts import PromptTemplate, StringPromptTemplate

template = """Given the driver's up to date stats, write them note relaying those stats to them.
If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel better

Here are the drivers stats:
Conversation rate: {conv_rate}
Acceptance rate: {acc_rate}
Average Daily Trips: {avg_daily_trips}

Your response:"""
prompt = PromptTemplate.from_template(template)

  这段prompt意思是生成最新的驾驶员统计数据(会话率、接收率和日均行程数)并提供给他们。如果转化率(conversation rate)大于0.5,就给予赞美,否则就在信息末尾讲一个关于鸡的傻笑笑话来逗他们开心(make them feel better)。

class FeastPromptTemplate(StringPromptTemplate):
	# **kwargs表示它可以接收任意多个关键字参数。
    def format(self, **kwargs) -> str:
        driver_id = kwargs.pop("driver_id")
        feature_vector = store.get_online_features(
            features=[
                "driver_hourly_stats:conv_rate",
                "driver_hourly_stats:acc_rate",
                "driver_hourly_stats:avg_daily_trips",
            ],
            entity_rows=[{"driver_id": driver_id}],
        ).to_dict()
        kwargs["conv_rate"] = feature_vector["conv_rate"][0]
        kwargs["acc_rate"] = feature_vector["acc_rate"][0]
        kwargs["avg_daily_trips"] = feature_vector["avg_daily_trips"][0]
        return prompt.format(**kwargs)
  • driver_id = kwargs.pop("driver_id") :从kwargs字典中取出"driver_id"对应的值,赋值到driver_id变量,且pop方法会从字典中移除这个键值对,此时kwargs是一个空字典。移除driver_id是因为此参数需要单独使用,而其他conv_rate等参数会传递给后续的prompt.format(**kwargs)方法。
  • feature_vector = store.get_online_features(...)get_online_features 方法获取实时特征。其中:
    • feature:是需要获取的特征列表(“项目:特征名”)
    • entity_rows::查询的实体行列表。
    • 这一段的意思是查询驾驶员ID(driver_id)的特征列表features 中所对应的特征数据
prompt_template = FeastPromptTemplate(input_variables=["driver_id"])
print(prompt_template.format(driver_id=1001))
Given the driver's up to date stats, write them note relaying those stats to them.
If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel better

Here are the drivers stats:
Conversation rate: 0.4745151400566101
Acceptance rate: 0.055561766028404236
Average Daily Trips: 936

Your response:

我们现在可以创建一个利用特征存储实现个性化的链条。

from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAI

chain = LLMChain(llm=ChatOpenAI(), prompt=prompt_template)
chain.run(1001)
 "Hi there! I wanted to update you on your current stats. Your acceptance rate is 0.055561766028404236 and your average daily trips are 936. While your conversation rate is currently 0.4745151400566101, I have no doubt that with a little extra effort, you'll be able to exceed that .5 mark! Keep up the great work! And remember, even chickens can't always cross the road, but they still give it their best shot."

四、使用少量示例创建 prompt templates

参考《Few-shot prompt templates》

  本章我们将学习如何创建使用少量示例的提示模板。少量示例的提示模板可以从一组示例或者一个示例选择器对象构建而成。后者只是多了一步从示例集中创建示例选择器example selector并进行相似性搜索来过滤示例的步骤。

4.1 使用示例集(example set)

4.1.1 创建示例集

首先创建一个示例集,每个示例都是一个字典,包含输入变量的键和对应的值。

from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate

examples = [
  {
    "question": "Who lived longer, Muhammad Ali or Alan Turing?",
    "answer":
"""
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
"""
  },
  {
    "question": "When was the founder of craigslist born?",
    "answer":
"""
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952
"""
  },
  {
    "question": "Who was the maternal grandfather of George Washington?",
    "answer":
"""
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
"""
  },
  {
    "question": "Are both the directors of Jaws and Casino Royale from the same country?",
    "answer":
"""
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate Answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate Answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate Answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate Answer: New Zealand.
So the final answer is: No
"""
  }
]
4.1.2 创建示例格式化器

  定义一个格式化器(PromptTemplate 对象),将示例格式化成字符串。

example_prompt = PromptTemplate(input_variables=["question", "answer"], template="Question: {question}\n{answer}")

print(example_prompt.format(**examples[0]))
Question: Who lived longer, Muhammad Ali or Alan Turing?

Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
4.1.3 创建FewShotPromptTemplate

创建 FewShotPromptTemplate 对象,该对象接收示例集和示例格式化器。

prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Question: {input}",
    input_variables=["input"]
)

print(prompt.format(input="Who was the father of Mary Ball Washington?"))
  • suffix参数:指定了输入问题的格式。具体来说,suffix=“Question: {input}” 表示在几份学习的示例后面,会接上一个 "Question: " 的前缀和输入变量{input}。

      Question: Who lived longer, Muhammad Ali or Alan Turing?
      
      Are follow up questions needed here: Yes.
      Follow up: How old was Muhammad Ali when he died?
      Intermediate answer: Muhammad Ali was 74 years old when he died.
      Follow up: How old was Alan Turing when he died?
      Intermediate answer: Alan Turing was 41 years old when he died.
      So the final answer is: Muhammad Ali
      
      
      Question: When was the founder of craigslist born?
      
      Are follow up questions needed here: Yes.
      Follow up: Who was the founder of craigslist?
      Intermediate answer: Craigslist was founded by Craig Newmark.
      Follow up: When was Craig Newmark born?
      Intermediate answer: Craig Newmark was born on December 6, 1952.
      So the final answer is: December 6, 1952
      
      
      Question: Who was the maternal grandfather of George Washington?
      
      Are follow up questions needed here: Yes.
      Follow up: Who was the mother of George Washington?
      Intermediate answer: The mother of George Washington was Mary Ball Washington.
      Follow up: Who was the father of Mary Ball Washington?
      Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
      So the final answer is: Joseph Ball
      
      
      Question: Are both the directors of Jaws and Casino Royale from the same country?
      
      Are follow up questions needed here: Yes.
      Follow up: Who is the director of Jaws?
      Intermediate Answer: The director of Jaws is Steven Spielberg.
      Follow up: Where is Steven Spielberg from?
      Intermediate Answer: The United States.
      Follow up: Who is the director of Casino Royale?
      Intermediate Answer: The director of Casino Royale is Martin Campbell.
      Follow up: Where is Martin Campbell from?
      Intermediate Answer: New Zealand.
      So the final answer is: No
      
      
      Question: Who was the father of Mary Ball Washington?
    

4.2 使用示例选择器​(example selector)

  本节我们将使用 SemanticSimilarityExampleSelector 类,这个类根据输入和少数示例之间的相似性来选择少数示例。它使用一个嵌入模型来计算输入和少数示例之间的相似性,并使用向量存储(vectorstore)来执行最近邻搜索。

   SemanticSimilarityExampleSelector 类继承自BaseExampleSelectorBaseModel,详情如下:

参数类型描述
example_keysOptional[List[str]]可选参数,用于过滤示例的键列表。
input_keysOptional[List[str]]可选参数,用于过滤输入的键列表。如果提供,搜索将基于输入变量而不是所有变量。
kint选择的示例数量,默认为4。
vectorstorelangchain_core.vectorstores.VectorStore [Required]包含有关示例信息的VectorStore,必需。
方法描述
init(example_keys, input_keys, k, vectorstore)通过解析和验证关键字参数的输入数据创建新模型。如果输入数据无法解析为有效模型,则引发ValidationError。
add_example(example)将新示例添加到vectorstore中。
from_examples(examples, embeddings, vectorstore_cls, k, input_keys, **vectorstore_cls_kwargs)使用示例列表和嵌入创建k-shot示例选择器。根据查询相似性动态重新排列示例。
select_examples(input_variables)基于语义相似性选择要使用的示例。返回一个包含所选示例的列表。
4.2.1 根据示例集创建ExampleSelector ​

  首先我们将重用上一节中的示例集和格式化程序,但是,这次我们不会直接将这些示例馈送到 FewShotPromptTemplate 对象,而是先馈送到 ExampleSelector 对象进行选择。

  Example selectors需要定义的唯一方法是 select_examples,它根据输入示例,返回选择的示例列表。你可以Select by length、Select by MMR、Select by n-gram overlap、Select by similarity。

from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings

# 创建语义相似性示例选择器
example_selector = SemanticSimilarityExampleSelector.from_examples(
    # 可供选择的示例列表。
    examples,
    # 用于生成嵌入的嵌入类,用于测量语义相似性。
    OpenAIEmbeddings(),
    # 用于存储嵌入并进行相似性搜索的VectorStore类。
    Chroma,
    # 要生成的示例数量。
    k=1
)

# 选择与输入最相似的示例。
question = "Who was the father of Mary Ball Washington?"
selected_examples = example_selector.select_examples({"question": question})
print(f"与输入最相似的示例:{question}")
for example in selected_examples:
    print("\n")
    for k, v in example.items():
        print(f"{k}: {v}") 				# 打印example键值对,即question,answer及其对应的值
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
Examples most similar to the input: Who was the father of Mary Ball Washington?


question: Who was the maternal grandfather of George Washington?
answer:
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball

Chroma是一个向量存储库,详细信息见Vector stores。

4.2.2 将示例选择器输入 FewShotPromptTemplate

  最后,同4.1.3一样,创建一个 FewShotPromptTemplate 对象,该对象接受示例选择器和少数示例的格式化程序。

prompt = FewShotPromptTemplate(
    example_selector=example_selector,
    example_prompt=example_prompt,
    suffix="Question: {input}",
    input_variables=["input"]
)

print(prompt.format(input="Who was the father of Mary Ball Washington?"))
Question: Who was the maternal grandfather of George Washington?

Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball


Question: Who was the father of Mary Ball Washington?

五、使用少量示例创建ChatPromptTemplate

  few-shot prompting(少样本提示)的目的是根据输入动态选择相关的样本,并将这些样本格式化成提示给模型,使用 FewShotChatMessagePromptTemplate可以实现这一点。

5.1 使用示例集

最基本的少样本提示是使用固定的提示示例,这种方法最简单,在生产环境中也较为可靠。其基本组成部分是:

  • examples:包含在最终提示中的示例(字典类型)列表
  • example_prompt:通过examples的 format_messages 方法将每个示例转换为 1 条或多条消息,比如one human message and one AI message response,或者是a human message followed by a function call message(紧跟着一个函数调用消息)。

下面进行演示。首先导入样本:

from langchain.prompts import ChatPromptTemplate,FewShotChatMessagePromptTemplate

examples = [
    {"input": "2+2", "output": "4"},
    {"input": "2+3", "output": "5"},
]

创建FewShotChatMessagePromptTemplate:

# This is a prompt template used to format each individual example.
example_prompt = ChatPromptTemplate.from_messages(
    [
        ("human", "{input}"),
        ("ai", "{output}"),
    ]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
    example_prompt=example_prompt,
    examples=examples,
)

print(few_shot_prompt.format())
Human: 2+2
AI: 4
Human: 2+3
AI: 5

调用创建好的FewShotChatMessagePromptTemplate:

from langchain.chat_models import ChatAnthropic

final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human", "{input}"),
    ]
)

chain = final_prompt | ChatAnthropic(temperature=0.0)
chain.invoke({"input": "What's the square of a triangle?"})
AIMessage(content=' Triangles do not have a "square". A square refers to a shape with 4 equal sides and 4 right angles. Triangles have 3 sides and 3 angles.\n\nThe area of a triangle can be calculated using the formula:\n\nA = 1/2 * b * h\n\nWhere:\n\nA is the area \nb is the base (the length of one of the sides)\nh is the height (the length from the base to the opposite vertex)\n\nSo the area depends on the specific dimensions of the triangle. There is no single "square of a triangle". The area can vary greatly depending on the base and height measurements.', additional_kwargs={}, example=False)

  在构建最终推理prompt时,首先设置系统角色,然后提供少样本示例,最后传入用户的输入,让模型进行推理。final_prompt同时为模型提供上下文、示例和输入的作用,使其能够有针对性地生成响应。

5.2 使用示例选择器

  有时您可能希望根据输入来限制显示哪些示例,以达到Dynamic few-shot prompting的效果。为此,您可以将 examples 替换为 example_selector ,其他组件与上面相同(即包含example_selectorexample_prompt)。

  首先构建向量存储(vectorstore),存储输入和输出的embeddings,然后基于向量相似性实现动态示例选择。

from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import SemanticSimilarityExampleSelector
from langchain.vectorstores import Chroma

examples = [
    {"input": "2+2", "output": "4"},
    {"input": "2+3", "output": "5"},
    {"input": "2+4", "output": "6"},
    {"input": "What did the cow say to the moon?", "output": "nothing at all"},
    {
        "input": "Write me a poem about the moon",
        "output": "One for the moon, and one for me, who are we to talk about the moon?",
    },
]

to_vectorize = [" ".join(example.values()) for example in examples]
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)

之后,创建example_selector。此处,我们选择前 2 个示例最相似的示例。

example_selector = SemanticSimilarityExampleSelector(
    vectorstore=vectorstore,
    k=2,
)

# The prompt template will load examples by passing the input do the `select_examples` method
example_selector.select_examples({"input": "horse"})
 [{'input': 'What did the cow say to the moon?', 'output': 'nothing at all'},
     {'input': '2+4', 'output': '6'}]

创建FewShotChatMessagePromptTemplate:

from langchain.prompts import ChatPromptTemplate,FewShotChatMessagePromptTemplate,


# 定义few-shot prompt.
few_shot_prompt = FewShotChatMessagePromptTemplate(
    # input variables选择要传递给示例选择器的值
    input_variables=["input"],
    example_selector=example_selector,
    # 定义每个示例的格式。在这种情况下,每个示例将变成 2 条消息:
    # 1 条来自人类,1 条来自 AI
    example_prompt=ChatPromptTemplate.from_messages(
        [("human", "{input}"), ("ai", "{output}")]
    ),
)

print(few_shot_prompt.format(input="What's 3+3?"))
Human: 2+3
AI: 5
Human: 2+2
AI: 4

创建最终的提示模板:

final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human", "{input}"),
    ]
)

print(few_shot_prompt.format(input="What's 3+3?"))
Human: 2+3
AI: 5
Human: 2+2
AI: 4
from langchain.chat_models import ChatAnthropic

chain = final_prompt | ChatAnthropic(temperature=0.0)
chain.invoke({"input": "What's 3+3?"})
AIMessage(content=' 3 + 3 = 6', additional_kwargs={}, example=False)

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

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

相关文章

一线大厂Redis高并发缓存架构

场景1:秒杀库存场景, 10000人抢100个商品 如果用普通的分布式锁实现, 最后抢到的人,要等前面99个人抢完 优化方案:可用分段锁, 降低锁的粒度, 比如1-10库存用锁product:101_1,11-20库存用锁pr…

2023年AI时代中小企业智能化发展报告

今天分享的是AI系列深度研究报告:《2023年AI时代中小企业智能化发展报告》。 (报告出品方:创业邦) 报告共计:47页 AI——中小企业的智能化增长利器 继蒸汽机、电气化、信息化时代之后,由第四次工业革命开…

好价节有哪些提升幸福感好物值得入手?一篇总结到位!

往年双十一过后都会有一个双十二,今天就大有不同,双十二已经改名叫“好价节”了,虽然改名了但丝毫不影响一些商品的优惠。双十一没有购买痛快的朋友可以趁好价节抓紧入手心仪的好物,今天就给大家推荐几款口碑不错的智能家居&#…

VScode异常处理 (因为在此系统上禁止运行脚本)

在使用 VScode 自带程序终端的时候会报出"系统禁止脚本运行的错误" 这是由于 Windows PowerShell执行策略导致的 解决办法 管理员身份运行 Windows PowerShell执行:get-ExecutionPolicy1,显示Restricted2执行:Set-ExecutionPoli…

26. 深度学习进阶 - 深度学习的优化方法

Hi, 你好。我是茶桁。 上一节课中我们预告了,本节课是一个难点,同时也是一个重点,大家要理解清楚。 我们在做机器学习的时候,会用不同的优化方法。 SGD 上图中左边就是Batch Gradient Descent,中间是Mini-Batch Gra…

实验 elk+filebeat+kafka

kafka 3.4.1 elkfilebeatkafka 实现日志收集 httpd1 mysql1 topic 2.7 3.0 关闭防火墙 systemctl stop firewalld systemctl disable firewalld setenforce 0 安装 JDK yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel java -version 安装 Zookeeper cd /…

Selenium+Python自动化测试之验证码处理

两种方式: 验证码识别技术 (很难达到100%) 添加Cookie (*****五星推荐) 方式一:验证码识别技术 逻辑方式: 1:打开验证码所在页面,截图。获取验证码元素坐标,剪切出验证码图片&…

xss漏洞后端进行html消毒

import org.jsoup.Jsoup;public static String sanitizeHtml(String input) {// 使用 Jsoup 消毒 HTMLreturn Jsoup.clean(input, Safelist.relaxed());}public static void main(String[] args) {String userInput "<p><script>alert(1)</script>Safe…

震坤行:数字驱动食品农副行业采购的新兴趋势与实践

震坤行&#xff1a;数字驱动食品农副行业采购的新兴趋势与实践 近年来消费者对于营养价值和健康的追求日益凸显&#xff0c;促使各类有机食品、低糖低脂食品、素食等健康食品受到热烈追捧。同时&#xff0c;以往单一的产品也被各家企业“卷”出了个性化&#xff0c;光是卖水&a…

机器学习笔记 - 基于百度飞桨PaddleSeg的人体分割模型以及TensorRT部署说明

一、简述 虽然Segment Anything用于图像分割的通用大模型看起来很酷(飞桨也提供分割一切的模型),但是个人感觉落地应用的时候心里还是更倾向于飞桨这种场景式的,因为需要用到一些人体分割的需求,所以这里主要是对飞桨高性能图像分割开发套件进行了解和使用,但是暂时不训练…

初识Linux(下).妈妈再也不用担心我Linux找不到门了

文章目录 前言1. date时间相关的指令1.1 date1.2 在设定时间方面示例如下&#xff1a; 1.3 时间戳示例如下&#xff1a; 2. Cal指令示例如下&#xff1a;类似windows 3. find指令&#xff1a;&#xff08;非常重要&#xff09; -name示例如下&#xff1a;类似windows 4. grep指…

【HuggingFace Transformer库学习笔记】基础组件学习:Tokenizer

基础组件——Tokenizer &#xff08;1&#xff09;模型加载 from transformers import AutoTokenizersen "弱小的我也有大梦想!" # 从HuggingFace加载&#xff0c;输入模型名称&#xff0c;即可加载对于的分词器 tokenizer AutoTokenizer.from_pretrained("m…

数据结构:图文详解单链表的各种操作(头插法,尾插法,任意位置插入,删除节点,查询节点,求链表的长度,清空链表)

目录 一.什么是链表 二.链表的实现 节点的插入 头插法 尾插法 指定位置插入 节点的删除 删除第一次出现的关键字节点 删除所有关键字节点 节点的查找 链表的清空 链表的长度 前言&#xff1a;在上一篇文章中&#xff0c;我们认识了线性数据结构中的顺序表&#xff0…

CKafka 一站式搭建数据流转链路,助力长城车联网平台降低运维成本

关于长城智能新能源 长城汽车是一家全球化智能科技公司&#xff0c;业务包括汽车及零部件设计、研发、生产、销售和服务&#xff0c;旗下拥有魏牌、哈弗、坦克、欧拉及长城皮卡。2022年&#xff0c;长城汽车全年销售1,067,523辆&#xff0c;连续7年销量超100万辆。长城汽车面向…

兼容jlink OB arm仿真器使用(杜邦线过长导致烧写总是失败)

一、兼容jlink OB的使用&#xff1a; 1、设置中要选择jlink&#xff1b; 2、模式选择SWD模式&#xff08;接三根线&#xff09;&#xff1b; 二、杜邦线过长导致stm32的stlink烧写总是失败 用ST-link烧写提示的错误信息有&#xff1a; Error while accessing a target reso…

【开源】基于Vue和SpringBoot的快递管理系统

项目编号&#xff1a; S 007 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S007&#xff0c;文末获取源码。} 项目编号&#xff1a;S007&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、研究内容2.1 数据中心模块2.2 快递类型模块2.3 快…

思维模型 逆向思维

本系列文章 主要是 分享 思维模型&#xff0c;涉及各个领域&#xff0c;重在提升认知。弱者道之用反者道之动。 1 逆向思维的应用 1.1 历史典故 1 曹冲称象 这个故事讲述的是曹操的儿子曹冲如何利用逆向思维解决了称大象重量的难题。曹冲没有直接去称大象的重量&#xff0c;…

图解「差分」入门(“前缀和“ 到 “差分“ 丝滑过渡)

题目描述 这是 LeetCode 上的 「1094. 拼车」 &#xff0c;难度为 「中等」。 Tag : 「差分」、「前缀和」 车上最初有 capacity 个空座位&#xff0c;车只能向一个方向行驶&#xff08;不允许掉头或改变方向&#xff09;。 给定整数 capacity 和一个数组 trips, 表示第 i 次旅…

神经网络 表述(Neural Networks: Representation)

神经网络 表述(Neural Networks: Representation) 1 非线性假设 我们之前学的&#xff0c;无论是线性回归还是逻辑回归都有这样一个缺点&#xff0c;即&#xff1a;当特征太多时&#xff0c;计算的负荷会非常大。 下面是一个例子&#xff1a; 当我们使用 x 1 x_1 x1​, x 2…

Docker下安装Tomcat

目录 Tomcat简介 Tomcat安装 免修改版Tomcat安装 Tomcat简介 Tomcat是Apache软件基金会&#xff08;Apache Software Foundation&#xff09;的Jakarta 项目中的一个核心项目&#xff0c;由Apache、Sun 和其他一些公司及个人共同开发而成。由于有了Sun 的参与和支持&#x…