在langchain中 如何共同组合提示词prompts

引言

在大语言模型应用开发中,提示词是非常重要的环节。langchain提供了强大且灵活的提示模板(Prompt Template)功能。本文深入探讨LangChain中如何共同组合成提示模板。

什么是共同组合提示模板?

将Prompt的不同部分组合在一起。可以使用字符串提示或者聊天提示执行。

字符串提示合成

使用字符串提示时,每个模板都连接在一起。可以直接使用提示或字符串(列表中的第一个元素必须是提示)。

from langchain_core.prompts import PromptTemplate

prompt = (

    PromptTemplate.from_template("{省份}有几个地级市?")
    + "请说出三个分别列出"
    + "\n 省会距离{城市}有多远?"
)
print(prompt)
print(prompt.format(省份="河南省",城市="北京"))
input_variables=['城市', '省份'] template='{省份}有几个地级市?请说出三个分别列出\n 省会距离{城市}有多远?'

河南省有几个地级市?请说出三个分别列出
省会距离北京有多远?

聊天提示合成

langchain_core.messages 模块中,AIMessageHumanMessageSystemMessage 是三个用于表示不同类型消息的类。与上述相类似,将其进行组合。示例如下:

from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

# 初始化
prompt = SystemMessage(content="我是河南人")

new_prompt = (
    prompt + HumanMessage(content="嗨") + AIMessage(content="什么?") + "{input}"
)

# 这会创建一个 ChatPromptTemplate 类的实例

print(new_prompt.format_messages(input="我在向你打招呼"))

[SystemMessage(content='我是河南人'), HumanMessage(content='嗨'), AIMessage(content='什么?'), HumanMessage(content='我在向你打招呼')]

使用PipelinePrompt

PipelinePromptTemplate是 LangChain中的一个类,主要有两部分组成:

1.final prompt: 最终提示

2.Pipeline prompts:元组列表,由字符串名称和提示模板组成。每个提示模板都将被格式化,然后作为具有相同名称的变量传递给未来的提示模板。

from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate
full_template = """{introduction}

{example}

{start}"""

full_prompt = PromptTemplate.from_template(full_template)

print(full_prompt)

introduction_template = """You are impersonating {person}."""

introduction_prompt = PromptTemplate.from_template(introduction_template)
print(introduction_prompt)
example_template = """Here's an example of an interaction:

Q: {example_q}
A: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)
print(example_prompt)


start_template = """Now, do this for real!

Q: {input}
A:"""

start_prompt = PromptTemplate.from_template(start_template)

print(start_prompt)

input_prompts = [
    ("introduction", introduction_prompt),
    ("example", example_prompt),
    ("start", start_prompt),
]

pipeline_prompt = PipelinePromptTemplate(
    final_prompt = full_prompt, pipeline_prompts=input_prompts
)


print(pipeline_prompt)

print(pipeline_prompt.input_variables)

print(
    pipeline_prompt.format(
        person="Elon Musk",
        example_q="What's your favorite car?",
        example_a="Tesla",
        input="What's your favorite social media site?",
    )
)

You are impersonating Elon Musk.

Here's an example of an interaction:

Q: What's your favorite car?
A: Tesla

Now, do this for real!

Q: What's your favorite social media site?
A:

### LangChain 的功能和用途 LangChain 是一种用于构建复杂 AI 应用程序的框架,其核心目标是简化大型语言模型 (LLM) 和其他工具交互的过程。以下是关于 LangChain 的功能、使用场景及其示例的具体介绍。 #### 功能概述 LangChain 提供了一个灵活且强大的框架来连接不同的组件和服务,从而实现复杂的任务自动化。它的主要功能可以分为以下几个方面: 1. **链式调用** LangChain 支持多个操作之间的链式调用,允许开发者将不同类型的模块组合在一起形成完整的流程[^5]。这种设计使得能够轻松地扩展应用程序的功能范围。 2. **多模态支持** 不仅局限于单一的语言处理任务,还可以结合视觉识别、音频转录等多种技术形式完成更广泛的任务需求[^4]。 3. **结构化数据生成能力** 利用大模型的强大泛化性能,可以从非结构化的输入源里抽取特定格式的信息出来,比如日期时间解析[^2]或者对象属性映射[^3]等功能都属于此类范畴之内。 4. **插件生态系统** 为了进一步增强灵活性,LangChain 还引入了许多现成可用的第三方库作为补充选项之一;同时鼓励社区贡献更多定制化解决方案以满足个性化需求。 #### 使用场景分析 由于上述提到的各项特性,因此 LangChain 可应用于众多实际业务领域当中,下面列举几个典型例子来进行说明: - 自动客服系统建设:通过集成聊天机器人逻辑控制流管理机制再加上后台数据库查询服务等方式共同作用下达到高效解答用户疑问的目的; - 文档理解助手打造:借助先进的语义分割算法配合关键词定位技巧帮助人们快速找到所需资料位置所在之处并给出摘要总结等内容提示信息; - 数据录入优化方案实施:当面对海量半结构性原始记录材料时,则可考虑采用此方法自动填充表单项值减少人工干预程度提高工作效率的同时也降低了错误发生概率; #### 示例展示 这里选取三个具有代表性的应用场景分别予以阐述如下所示: ##### 场景一:简单问候消息发送测试 这是最基础的一个入门级练习项目,在其中我们将学习如何初始化一个基本对话环境并向指定接收方传递一条简单的文字内容。 ```python from langchain import PromptTemplate, LLMChain from langchain.llms import OpenAI llm = OpenAI() prompt_template = "Say hello to {name}!" prompt = PromptTemplate(template=prompt_template, input_variables=["name"]) hello_chain = LLMChain(prompt=prompt, llm=llm) print(hello_chain.run("World")) ``` ##### 场景二:从自由文本中提取具体时间段描述 假设现在有一篇新闻报道文章提及到了某些重要事件的发生时段情况,那么我们就可以运用相关技能将其准确无误地标记出来以便后续统计分析之需。 ```python import json from typing import Dict from pydantic import BaseModel, Field from langchain.prompts import ChatPromptTemplate from langchain.chat_models import ChatOpenAI from langchain.output_parsers import PydanticOutputParser class TimeExtraction(BaseModel): start_time: str = Field(description="The starting time mentioned.") end_time: str = Field(description="The ending time mentioned.") parser = PydanticOutputParser(pydantic_object=TimeExtraction) format_instructions = parser.get_format_instructions() template = """Extract the relevant times from the following string: {input} {format_instructions} """ prompt = ChatPromptTemplate.from_template(template) model = ChatOpenAI() _input = prompt.format_prompt(input="The meeting will be held between 8am and noon.", format_instructions=format_instructions).to_messages() output = model(_input) extraction_result = parser.parse(output.content) json.dumps(extraction_result.dict()) ``` ##### 场景三:依据给定模式转换自然表述成为标准化JSON对象表示法 有时候我们需要把一段话按照预设规则重新整理排列好之后再存储起来方便以后检索利用,这时候就可以发挥这个特有优势了。 ```python from dataclasses import dataclass from typing import Optional from langchain.experimental.data_serialization import DataSerializable from langchain_experimental.data_serialization.serializable_type_registry import SerializableTypeRegistry @dataclass(frozen=True) class Person(DataSerializable["Person"]): first_name: str last_name: str age: int occupation: Optional[str] registry = SerializableTypeRegistry.register(Person) textual_representation = ( "John Doe is a software engineer who just turned thirty years old." ) parsed_person_instance = registry.deserialize(text=textual_representation) serialized_json_output = parsed_person_instance.serialize() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值