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创建
- 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_types | Dict[str, Any] | 可选 | 期望的提示模板变量类型的字典。如果未提供,则假定所有变量均为字符串。 |
input_variables | List[str] | 必选 | 期望的提示模板变量的名称列表。 |
output_parser | Optional[lBaseOutputParser] = None | 可选 | 用于解析调用此格式化提示的LLM输出的方法。 |
partial_variables | Mapping[str, Union[str, Callable[[], str]]] | 可选 | 字典映射,包含部分变量的名称、类型或生成值的回调函数。 |
该类还包含以下方法:
-
异步方法:
类中定义了多个异步方法,如abatch
、ainvoke
、astream
等,用于异步执行任务。这些方法提供了默认实现,但可以在子类中进行覆盖以实现更高效的批处理或异步执行。 -
配置相关的方法:
config_schema
方法返回一个 Pydantic 模型,用于验证配置。configurable_fields
方法返回一个可配置字段的序列化对象。
-
输入输出相关的方法:
get_input_schema
和get_output_schema
方法返回 Pydantic 模型,用于验证输入和输出。invoke
方法用于将单个输入转换为输出。
-
流式处理相关方法:
astream_log
方法用于流式处理运行输出,包括内部运行的日志等信息。astream
方法是astream_log
方法的默认实现。
-
其他方法:
- 包括一系列用于处理配置、模型序列化等的方法,如
lc_id
、json
、dict
等。
- 包括一系列用于处理配置、模型序列化等的方法,如
-
属性:
- 包括
InputType
、OutputType
、config_specs
等属性,用于获取输入类型、输出类型和配置规范。
- 包括
-
类方法:
- 包括用于解析对象、生成 JSON 表示、更新引用等类方法。
总体而言,该类是一个通用的 Prompt 模板类,提供了一系列用于处理配置、输入输出、异步执行等功能的方法。如果需要使用该模板,可以通过继承该类并实现必要的方法来定制特定的 Prompt 行为。
BaseMessagePromptTemplate继承自Serializable
和ABC
(Abstract Base Class),它是消息提示模板的基类,用于创建新模型并验证输入数据。
-
类方法
construct
:创建一个新模型,通过解析和验证关键字参数中的输入数据。如果输入数据无法解析为有效模型,则引发ValidationError
。参数有_fields_set
(可选的字段集合)和**values
(其他数值),返回新的模型实例。 -
类方法
copy
:复制模型,可选择包含、排除、更改哪些字段,返回新的模型实例。 -
类方法
dict
:生成模型的字典表示,可选择包含或排除特定字段。 -
抽象方法
format_messages
:从关键字参数中格式化消息,应返回BaseMessage
的列表。- 参数:
kwargs
,用于格式化的关键字参数。 - 返回:
BaseMessage
的列表。
- 参数:
-
其他类方法和属性:略
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
PromptTemplate
和 ChatPromptTemplate
实现了Runnable接口,这是LangChain表达式语言(LCEL)的基本构建块。这意味着它们支持invoke
、ainvoke
、stream
、astream
、batch
、abatch
、astream_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 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']
from langchain.chat_models import ChatOpenAI
from langchain.prompts import HumanMessagePromptTemplate
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}"),]
)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 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)。
-
转换(Transformation):负责对数据进行处理,生成特征值。支持批处理、流式处理和按需处理三种方式。重用代码,避免训练服务数据偏差。
-
存储(Storage):提供离线存储用于历史数据,方便模型训练;提供在线存储用于低延迟特征服务。通常与数据湖或数据库集成。使用实体为中心的数据模型。
-
服务(Serving):通过高性能API实时提供特征数据。确保训练和服务使用一致的特征视图,避免偏差。支持通过SDK访问用于模型训练。
-
监控(Monitoring):检测数据质量、一致性等问题,确保系统运行正常。可以聚合和关联多个指标,方便定位根源。
-
注册表(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 类继承自BaseExampleSelector
和BaseModel
,详情如下:
参数 | 类型 | 描述 |
---|---|---|
example_keys | Optional[List[str]] | 可选参数,用于过滤示例的键列表。 |
input_keys | Optional[List[str]] | 可选参数,用于过滤输入的键列表。如果提供,搜索将基于输入变量而不是所有变量。 |
k | int | 选择的示例数量,默认为4。 |
vectorstore | langchain_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_selector
和example_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上——自定义提示模板、使用实时特征或少量示例创建提示模板
文章目录 一、 Prompt templates1.1 langchain_core.prompts1.2 PromptTemplate1.2.1 简介1.2.2 ICEL1.2.3 Validate template 1.3 ChatPromptTemplate1.3.1 使用role创建1.3.2 使用MessagePromptTemplate创建1.3.3 自定义MessagePromptTemplate1.3.3.1 自定义消息角色名1.3.3.…...

【算法】合并K个升序链表
这道题主要考察的是归并排序,因为已经升序过了,更好理解了。 当然也可以采用分治的思路;或采用最小堆的思路;面试中校招同学写出一种即可,如果能全概览讲一下,就更加分了。 #############################…...

持续集成交付CICD:GitLab Webhook触发Jenkins流水线
目录 一、实验 1.Jenkins远程下载GiaLab仓库代码 2.curl远程触发Jenkins流水线 3.GitLab Webhook触发Jenkins流水线 二、问题 1.GitLab配置Webhook时报错 一、实验 1.Jenkins远程下载GiaLab仓库代码 (1) Jenkins添加选项参数 (2)添加字符参数 (3)查看构建参数情况 (4)添…...

计算机网络测试题
一 单项选择题(5分) 1、假设要发送的数据为101110,采用CRC的生成多项式是X31,试求应添加在数据后面的余数。(5分) 110 011(答案) 101 001 实际得分:5分 二 填空题(95分) 1、以下3个子地址块…...

vscode如何在没有网络的情况下安装插件
vscode如何在没有网络的情况下安装插件 start 遇到没有网络的电脑,无法直接从插件市场安装vscode的插件。写一下 vscode 插件离线安装的方法. 解决方案 目标电脑没有可以安装插件的网络,那我们只能在有网络的环境下载好我们的插件。然后拷贝软件到无…...

自定义类型:结构体、联合、枚举
目录 一、⾃定义类型:结构体 1.结构体类型 1. 1结构体类型的声明 结构体变量的创建和初始化 1.2 结构的特殊声明 1.3 结构的自引用 2. 结构体内存对齐 ①:对齐规则 ②:offsetof函数 ③:为什么存在内存对⻬? ④ 修改默认对⻬…...

HelpLook可以作为wordpress的替代品,帮助企业快速搭建博客
博客作为一个非常有价值的平台,在当今的数字时代具有重要的意义。对于个人和企业来说,选择一款适合自己需求的专业博客搭建软件至关重要。本篇文章将会通过对比两个专业的博客搭建软件——HelpLook和WordPress,看看为什么我说HelpLook可以作为…...

单片机实现数码管动态显示
动态显示的特点是将所有位数码管的段选线并联在一起,由位选线控制是哪一位数码管有效。这样一来,就没有必要每一位数码管配一个锁存器,从而大大地简化了硬件电路。选亮数码管采用动态扫描显示。所谓动态扫描显示即轮流向各位数码管送出字形码…...

jbrowse基因组浏览器部署
一、jbrowse部署 1.1 jbrowse部署 sudo mkdir /var/www/jbrowse; sudo chown whoami /var/www/jbrowse; # cd into it cd /var/www/jbrowse;1.2 nginx配置 server {listen 80 default_server;listen [::]:80 default_server;server_name _;#root /var/w…...

神经网络 模型表示(一)
神经网络 模型表示 模型表示一 为了构建神经网络模型,我们需要首先思考大脑中的神经网络是怎样的?每一个神经元都可以被认为是一个处理单元/神经核(processing unit/Nucleus),它含有许多输入/树突(input/…...

【漏洞复现】智跃人力资源管理系统GenerateEntityFromTable.aspx接口存在SQL注入漏洞 附POC
漏洞描述 智跃人力资源管理系统是基于B/S网页端广域网平台,一套考勤系统即可对全国各地多个分公司进行统一管控,成本更低。信息共享更快。跨平台,跨电子设备。智跃人力资源管理系统GenerateEntityFromTable.aspx接口处存在SQL注入漏洞,攻击者可通过该漏洞获取数据库中的信…...

【matlab程序】画海洋流场
【matlab程序】画海洋流场 clear;clc; file ( ‘0227.nc’); latncread(file,‘latitude’); lonncread(file,‘longitude’); uncread(file,‘water_u’); vncread(file,‘water_v’); [x,y]meshgrid(lon,lat); xx’; yy’; interval4; figure (1) set(gcf,‘color’,[1 1 1…...

线性表 力扣67. 二进制求和
题目 67. 二进制求和 翻译 主要思路 核心思路是像竖式计算一样,不过需要将字符串a和b反转后逐位进行二进制计算得到字符串c,最后再将c反转就是答案 逐位计算的时候利用count,在将a和b当前位置数字相加后通过模2来决定字符串c对应位置的数…...

2312skia,13画布包入门
画矶包快速入门 CanvasKit是用比canvasAPI更高级功能集的Skia来绘画元素到canvas中的wasm模块. 最小应用 此例是个最小Canvaskit应用,它为一帧绘画一个圆角矩形.从unpkg.com中提取wasm二进制文件,但你也可自己构建和管理它. <canvas idfoo width300 height300></c…...

【网络安全技术】消息认证技术
一、哈希函数 1.安全性质 1)抗第一原像攻击(Preimage Resistance) 给定哈希后的值,很难找到哈希前的原消息。这很好理解,需要哈希函数具有单向性。 一个简单的例子就是密码存储系统,用户登录服务器需要…...

智慧安防三大信息技术:云计算、大数据及人工智能在视频监控EasyCVR中的应用
说到三大信息技术大家都很清楚,指的是云计算、大数据和人工智能,在人工智能(AI)快速发展的当下,例如常见的大数据分析、人工智能芯片生产的智能机器人等等,在工作、生活、教育、金融、科技、工业、农业、娱…...

接口测试基础知识
一、接口测试简介 什么是接口测试? 接口测试是测试系统组件间接口的一种测试,主要用于检测外部系统与系统之间以及内部各个子系统之间的交互点。 测试的重点: 检查数据的交换,传递和控制管理过程;检查系统间的相互…...

C++多线程之通过成员函数作为线程入口
说明: 通过类里面的函数作为线程入口,我个人难理解的地方在于给线程传递参数的时候,怎么找到Main函数。后面会做分析。 首先创建类:创建MyThread类,其中公有函数Main作为入口。这个类的传教比较简单,成员…...

word、excel文件转PDF(documents4j方式,简单)
1 documents4j方式 引入pom <dependency><groupId>com.documents4j</groupId><artifactId>documents4j-local</artifactId><version>1.1.12</version></dependency><dependency><groupId>com.documents4j</g…...

【Linux】:信号(三)捕捉
信号捕捉 一.sigaction1.基本使用2.sa_mask字段 二.可重入函数三.volatile四.SIGCHLD信号 承接上文 果信号的处理动作是用户自定义函数,在信号递达时就调用这个函数,这称为捕捉信号。由于信号处理函数的代码是在用户空间的,处理过程比较复杂,举例如下: 用户程序注册了SIGQUIT信…...

数据结构 / 队列 / 循环队列 / 概念
1. 定义 为充分利用向量空间,克服假溢出现象的方法是:将向量空间想象为一个首尾相接的圆环,并称这种向量为循环向量。存储在其中的队列称为循环队列(Circular Queue)。循环队列是把顺序队列首尾相连,把存储…...

elasticsearch 内网下如何以离线的方式上传任意的huggingFace上的NLP模型(国内闭坑指南)
es自2020年的8.x版本以来,就提供了机器学习的能力。我们可以使用es官方提供的工具eland,将hugging face上的NLP模型,上传到es集群中。利用es的机器学习模块,来运维部署管理模型。配合es的管道处理,来更加便捷的处理数据…...

vue中中的动画组件使用及如何在vue中使用animate.css
“< Transition >” 是一个内置组件,这意味着它在任意别的组件中都可以被使用,无需注册。它可以将进入和离开动画应用到通过默认插槽传递给它的元素或组件上。进入或离开可以由以下的条件之一触发: 由 v-if 所触发的切换由 v-show 所触…...

MATLAB 模型参考自适应控制 - Model Reference Adaptive Control
系列文章目录 文章目录 系列文章目录前言一、参考模型二、扰动与不确定性模型三、直接 MRAC名义模型参数更新间接 MRAC估计器模型和控制器增益参数更新学习修正参考文献 前言 模型参考自适应控制模块计算控制动作,使不确定的受控系统跟踪给定参考被控对象模型的行为…...

【如何用批处理文件实现自动编译Keil工程和C# Visual Studio工程】
如何用批处理文件实现自动编译Keil工程和C# Visual Studio工程 写个Bat 批处理文件,现自动编译Keil工程和C# Visual Studio工程。这样可以结合Python 实现复杂的操作。 编译Keil工程: echo off set UVC:\Keil_v5\UV4\UV4.exe set UV_PRO_PATHD:\worksp…...

大模型的实践应用11-“书生”通用大模型的搭建与模型代码详细介绍,以及快速使用方法
大家好,我是微学AI,今天给大家介绍一下大模型的实践应用11-“书生”通用大模型的搭建与模型代码详细介绍,以及快速使用方法。“书生” 通用大模型是上海人工智能实验室研制的大模型,并且已经开源了“书生浦语”大模型70亿参数的轻量级版本InternLM-7B。InternLM-7B模型主要…...

【开发PaaS】基于Postgresql的开发平台Supabase
Supadase是开源的。我们选择可扩展的开源工具,使其易于使用。 Supadase不是Firebase的1对1映射。虽然我们正在构建Firebase提供的许多功能,但我们不会以同样的方式进行: 我们的技术选择大不相同;我们使用的一切都是开源的&#…...

前端开启gzip优化页面加载速度
生成gizp的打包资源,可以优化页面加载速度 打包的时候开启gzip可以很大程度减少包的大小,页面大小可以变为原来的30%甚至更小,非常适合线上部署, 但还记得需要服务端支持 1、前端配置compression-webpack-plugin 先安装:npm install compres…...

用Java写一个俄罗斯方块
目录 游戏规则 小方块类:Cell 七种图形类:I、J、L、O、S、T、Z J L O S T Z 俄罗斯方块游戏主类:Tetris 效果展示 游戏规则 由小方块组成的不同形状的板块陆续从屏幕上方落下来,玩家通过调整板块的位置和方向,使它…...

应用于智慧金融的AI边缘计算盒子+AI算法软硬一体化方案
传统金融营业厅存在运营管理模式落后、资源投放不平衡、从业人员培训效果不达预期、客户体验割裂等普遍现象; 部署英码数字金融解决方案,将助力企业从传统金融模式快速向数字金融模式转变,可针对每一个客户定制个性化“一对一”服务ÿ…...