LangChain使用Prompt02

1.设置提示

from langchain.prompts import ChatPromptTemplate
prompt_template = ChatPromptTemplate.from_messages(
    [
        ("system", "你是一位专业的翻译,能够将{input_language}翻译成{output_language},并且输出文本会根据用户要求的任何语言风格进行调整。请只输出翻译后的文本,不要有任何其它内容。"),
        ("human", "文本:{text}\n语言风格:{style}"),
    ]
)

2.输出提示模板

prompt_template.input_variables

[‘input_language’, ‘output_language’, ‘style’, ‘text’]

3.提示中输入值

prompt_value = prompt_template.invoke({"input_language": "英语", "output_language": "汉语", 
                                       "text":"I'm so hungry I could eat a horse", "style": "文言文"})
prompt_value

ChatPromptValue(messages=[SystemMessage(content=‘你是一位专业的翻译,能够将英语翻译成汉语,并且输出文本会根据用户要求的任何语言风格进行调整。请只输出翻译后的文本,不要有任何其它内容。’), HumanMessage(content=“文本:I’m so hungry I could eat a horse\n语言风格:文言文”)])

4.取出提示

prompt_value.messages

[SystemMessage(content=‘你是一位专业的翻译,能够将英语翻译成汉语,并且输出文本会根据用户要求的任何语言风格进行调整。请只输出翻译后的文本,不要有任何其它内容。’),
HumanMessage(content=“文本:I’m so hungry I could eat a horse\n语言风格:文言文”)]

5.输入模型

model = ChatOpenAI(model="gpt-3.5-turbo",base_url="https://api.chatanywhere.tech/v1")
response = model.invoke(prompt_value)

6.获得结果

response

AIMessage(content=‘吾今飢極,如欲食馬也。’, additional_kwargs={‘refusal’: None}, response_metadata={‘token_usage’: {‘completion_tokens’: 17, ‘prompt_tokens’: 109, ‘total_tokens’: 126, ‘completion_tokens_details’: {‘reasoning_tokens’: 0}}, ‘model_name’: ‘gpt-3.5-turbo-0125’, ‘system_fingerprint’: None, ‘finish_reason’: ‘stop’, ‘logprobs’: None}, id=‘run-9d752bd9-468e-4fe1-9ff9-e379561c957b-0’, usage_metadata={‘input_tokens’: 109, ‘output_tokens’: 17, ‘total_tokens’: 126})

7.取出结果

response.content

‘吾今飢極,如欲食馬也。’

8.多行示例

input_variables = [
    {
        "input_language": "英语",
        "output_language": "汉语",
        "text": "I'm so hungry I could eat a horse",
        "style": "文言文"
    },
    {
        "input_language": "法语",
        "output_language": "英语",
        "text": "Je suis désolé pour ce que tu as fait",
        "style": "古英语"
    },
    {
        "input_language": "俄语",
        "output_language": "意大利语",
        "text": "Сегодня отличная погода",
        "style": "网络用语"
    },
    {
        "input_language": "韩语",
        "output_language": "日语",
        "text": "너 정말 짜증나",
        "style": "口语"
    }
]

10.输入模型

for input in input_variables:
    response = model.invoke(prompt_template.invoke({"input_language": input["input_language"], "output_language": input["output_language"], 
                                                    "text":input["text"], "style": input["style"]}))
    print(response.content)

输出:
吾今饥饱难忍,实有食马之心也。
I am sorry for what thou hast done.
Oggi tempo fantastico
お前本当にイライラするな

### LangChain v0.3 版本中的提示词示例 在 LangChain v0.3 中,`PromptValue` 是一种核心概念,它允许开发者创建灵活的提示模板并将其传递给大型语言模型 (LLM) 或聊天模型 (ChatModel)[^1]。以下是几个常见的 `PromptTemplate` 和其生成的 `PromptValue` 示例: #### 示例 1: 基础字符串型 Prompt 模板 以下是一个简单的字符串型提示模板,用于询问用户的姓名和年龄。 ```python from langchain.prompts import PromptTemplate template = """你好! 我是AI助手,可以帮你完成一些任务。 请告诉我你的名字和年龄: Name: {name} Age: {age}""" prompt_template = PromptTemplate(input_variables=["name", "age"], template=template) formatted_prompt = prompt_template.format(name="张三", age=25) print(formatted_prompt) ``` 上述代码会输出如下内容: ``` 你好! 我是AI助手,可以帮你完成一些任务。 请告诉我你的名字和年龄: Name: 张三 Age: 25 ``` --- #### 示例 2: 工具绑定与动态上下文注入 当需要为语言模型提供外部工具支持时,可以通过 `.bind_tools()` 方法实现[^2]。下面展示了一个如何将工具集附加到模型上的例子: ```python from langchain.llms import OpenAI from langchain.agents import Tool, initialize_agent from langchain.tools import DuckDuckGoSearchRun llm = OpenAI(temperature=0) tools = [ Tool( name="搜索引擎", func=DuckDuckGoSearchRun().run, description="用于查询实时信息" ) ] model_with_tools = llm.bind_tools(tools) agent_chain = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) response = agent_chain.run("谁赢得了2022年的世界杯?") print(response) ``` 在这个场景下,通过 `.bind_tools()` 将搜索功能集成到了 LLM 中,使得它可以访问最新的网络数据。 --- #### 示例 3: 复杂对话历史管理 对于多轮对话的应用程序来说,维护对话历史非常重要。LangChain 提供了一种方法来构建带有记忆机制的消息列表形式的提示。 ```python from langchain.memory import ConversationBufferMemory from langchain.chains import ConversationalRetrievalChain memory = ConversationBufferMemory(memory_key="chat_history") conversation_chain = ConversationalRetrievalChain.from_llm( llm=OpenAI(), retriever=None, # 如果有向量数据库,则传入检索器对象 memory=memory ) result = conversation_chain({"question": "今天天气怎么样?"}) print(result["answer"]) ``` 这段代码展示了如何利用内存组件保存之前的交互记录,并基于这些记录生成更连贯的回答。 --- ### 总结 以上三个示例分别介绍了基础字符串型提示、工具增强以及复杂对话系统的构建方式。每种类型的提示都有助于解决不同层次的需求——从简单问答到复杂的多模态应用开发均可覆盖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值