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

本文主要是介绍LangChain(0.0.340)官方文档三:Prompts上——自定义提示模板、使用实时特征或少量示例创建提示模板,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 一、 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, content)创建
        • 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 --> PipelinePromptTemplateStringPromptTemplate --> PromptTemplateFewShotPromptTemplateFewShotPromptWithTemplatesBaseChatPromptTemplate --> AutoGPTPromptChatPromptTemplate --> AgentScratchPadChatPromptTemplateBaseMessagePromptTemplate --> MessagesPlaceholderBaseStringMessagePromptTemplate --> ChatMessagePromptTemplateHumanMessagePromptTemplateAIMessagePromptTemplateSystemMessagePromptTemplate

  先看一下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 PromptTemplateprompt_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 PromptTemplateprompt_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 PromptTemplatejinja2_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

  下面以百度文心一言为例进行演示。要调用文心一言 API,需要先获取文心一言调用秘钥。首先我们需要进入文心千帆服务平台,注册登录之后选择“应用接入”——“创建应用”。然后简单输入基本信息,选择默认配置,创建应用即可。

在这里插入图片描述

  创建完成后,点击应用的“详情”即可看到此应用的 AppID,API Key,Secret Key。然后在百度智能云在线调试平台-示例代码中心快速调试接口,获取AccessToken(不解之处,详见API文档)。最后在项目文件夹下使用vim .env(Linux)或type nul > .env(Windows cmd)创建.env文件,并在其中写入:

QIANFAN_AK="xxx"
QIANFAN_SK="xxx"
access_token="xxx"

下面将这些变量配置到环境中,后续就可以自动使用了。

# 使用openai、智谱ChatGLM、百度文心需要分别安装openai,zhipuai,qianfan
import os
import openai,zhipuai,qianfan
from langchain.llms import ChatGLM
from langchain.chat_models import ChatOpenAI,QianfanChatEndpointfrom dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key =os.environ['OPENAI_API_KEY']
zhipuai.api_key =os.environ['ZHIPUAI_API_KEY']
qianfan.qianfan_ak=os.environ['QIANFAN_AK']
qianfan.qianfan_sk=os.environ['QIANFAN_SK']
1.3.1 使用(role, content)创建

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

from langchain.prompts import ChatPromptTemplatechat_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,qianfanfrom 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']
  1. 使用MessagePromptTemplate
from langchain.chat_models import QianfanChatEndpoint
from langchain.prompts import HumanMessagePromptTemplate,SystemMessagePromptTemplatetemplate="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])chat = QianfanChatEndpoint()
chat(chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages())
AIMessage(content='编程是一项非常有趣和有挑战性的工作,我很羡慕你能够享受其中的乐趣。', additional_kwargs={'id': 'as-cxezsmtfga', 'object': 'chat.completion', 'created': 1701520678, 'result': '编程是一项非常有趣和有挑战性的工作,我很羡慕你能够享受其中的乐趣。', 'is_truncated': False, 'need_clear_history': False, 'usage': {'prompt_tokens': 4, 'completion_tokens': 18, 'total_tokens': 22}})
  1. 使用BaseMessage的实例
from langchain.schema.messages import SystemMessagechat_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}"),]
)chat(chat_template.format_messages(text="i dont like eating tasty things."))
AIMessage(content='很抱歉听到您不喜欢吃美味的食物。您有其他喜欢的食物类型吗?或许我们可以找到一些其他您喜欢吃的食物,您试试看是否能够喜欢呢?', additional_kwargs={'id': 'as-sdcbpxad11', 'object': 'chat.completion', 'created': 1701520841, 'result': '很抱歉听到您不喜欢吃美味的食物。您有其他喜欢的食物类型吗?或许我们可以找到一些其他您喜欢吃的食物,您试试看是否能够喜欢呢?', 'is_truncated': False, 'need_clear_history': False, 'usage': {'prompt_tokens': 8, 'completion_tokens': 34, 'total_tokens': 42}})
1.3.3 自定义MessagePromptTemplate

参考《Types of MessagePromptTemplate 》

  Chat models底层实现是LLMs,但它不使用“文本输入、文本输出”API,而是使用“聊天消息”作为输入和输出的界面,即chat model基于消息(List[BaseMessage] )而不是原始文本。在langchain中,消息接口由 BaseMessage 定义,它有两个必需属性:

  • content :消息的内容,通常为字符串。
  • role :消息来源(BaseMessage)的实体类别,比如:
    • HumanMessage:来自人类/用户的BaseMessage。
    • AIMessage:来自AI/助手的BaseMessage。
    • SystemMessage:来自系统的BaseMessage。
    • FunctionMessage / ToolMessage:包含函数或工具调用输出的BaseMessage。
    • ChatMessage:如果上述角色都不合适,可以自定义角色。
    • 消息也可以是 str (将自动转换为 HumanMessage )和 PromptValue(PromptTemplate的值) 。

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

1.3.3.1 自定义消息角色名

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

from langchain.prompts import ChatMessagePromptTemplateprompt = "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 MessagesPlaceholderhuman_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 inspectdef get_source_code(function_name):# Get the source code of the functionreturn 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 vdef 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 promptdef _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 functionreturn 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, StringPromptTemplatetemplate = """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 betterHere 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 betterHere are the drivers stats:
Conversation rate: 0.4745151400566101
Acceptance rate: 0.055561766028404236
Average Daily Trips: 936Your response:

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

from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAIchain = 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 PromptTemplateexamples = [{"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 AliQuestion: 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, 1952Question: 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 BallQuestion: 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: NoQuestion: 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 BallQuestion: 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,FewShotChatMessagePromptTemplateexamples = [{"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 ChatAnthropicfinal_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 Chromaexamples = [{"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 条来自 AIexample_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 ChatAnthropicchain = final_prompt | ChatAnthropic(temperature=0.0)
chain.invoke({"input": "What's 3+3?"})
AIMessage(content=' 3 + 3 = 6', additional_kwargs={}, example=False)

这篇关于LangChain(0.0.340)官方文档三:Prompts上——自定义提示模板、使用实时特征或少量示例创建提示模板的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/460917

相关文章

C语言中联合体union的使用

本文编辑整理自: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=179471 一、前言 “联合体”(union)与“结构体”(struct)有一些相似之处。但两者有本质上的不同。在结构体中,各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量

ESP32 esp-idf esp-adf环境安装及.a库创建与编译

简介 ESP32 功能丰富的 Wi-Fi & 蓝牙 MCU, 适用于多样的物联网应用。使用freertos操作系统。 ESP-IDF 官方物联网开发框架。 ESP-ADF 官方音频开发框架。 文档参照 https://espressif-docs.readthedocs-hosted.com/projects/esp-adf/zh-cn/latest/get-started/index

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

LangChain转换链:让数据处理更精准

1. 转换链的概念 在开发AI Agent(智能体)时,我们经常需要对输入数据进行预处理,这样可以更好地利用LLM。LangChain提供了一个强大的工具——转换链(TransformChain),它可以帮我们轻松实现这一任务。 转换链(TransformChain)主要是将 给定的数据 按照某个函数进行转换,再将 转换后的结果 输出给LLM。 所以转换链的核心是:根据业务逻辑编写合适的转换函

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

Vim使用基础篇

本文内容大部分来自 vimtutor,自带的教程的总结。在终端输入vimtutor 即可进入教程。 先总结一下,然后再分别介绍正常模式,插入模式,和可视模式三种模式下的命令。 目录 看完以后的汇总 1.正常模式(Normal模式) 1.移动光标 2.删除 3.【:】输入符 4.撤销 5.替换 6.重复命令【. ; ,】 7.复制粘贴 8.缩进 2.插入模式 INSERT

公共筛选组件(二次封装antd)支持代码提示

如果项目是基于antd组件库为基础搭建,可使用此公共筛选组件 使用到的库 npm i antdnpm i lodash-esnpm i @types/lodash-es -D /components/CommonSearch index.tsx import React from 'react';import { Button, Card, Form } from 'antd'

Lipowerline5.0 雷达电力应用软件下载使用

1.配网数据处理分析 针对配网线路点云数据,优化了分类算法,支持杆塔、导线、交跨线、建筑物、地面点和其他线路的自动分类;一键生成危险点报告和交跨报告;还能生成点云数据采集航线和自主巡检航线。 获取软件安装包联系邮箱:2895356150@qq.com,资源源于网络,本介绍用于学习使用,如有侵权请您联系删除! 2.新增快速版,简洁易上手 支持快速版和专业版切换使用,快速版界面简洁,保留主

如何免费的去使用connectedpapers?

免费使用connectedpapers 1. 打开谷歌浏览器2. 按住ctrl+shift+N,进入无痕模式3. 不需要登录(也就是访客模式)4. 两次用完,关闭无痕模式(继续重复步骤 2 - 4) 1. 打开谷歌浏览器 2. 按住ctrl+shift+N,进入无痕模式 输入网址:https://www.connectedpapers.com/ 3. 不需要登录(也就是

ROS话题通信流程自定义数据格式

ROS话题通信流程自定义数据格式 需求流程实现步骤定义msg文件编辑配置文件编译 在 ROS 通信协议中,数据载体是一个较为重要组成部分,ROS 中通过 std_msgs 封装了一些原生的数据类型,比如:String、Int32、Int64、Char、Bool、Empty… 但是,这些数据一般只包含一个 data 字段,结构的单一意味着功能上的局限性,当传输一些复杂的数据,比如: