Skip to main content

提示工程快速入门(SDK)

本快速入门将指导您如何使用SDK来创建、测试和迭代提示。在本教程中,我们将使用OpenAI,但您可以使用任何您想要的大型语言模型。

快速开始

本教程使用SDK进行提示工程,如果您有兴趣改用UI,请阅读本指南

1. 配置

首先,安装所需的包:

pip install -qU langsmith openai langchain_core

接下来,请确保您已注册 LangSmith 账户,然后创建并设置您的API密钥。 您还需要注册一个OpenAI API密钥,以运行本教程中的代码。

LANGSMITH_API_KEY = '<your_api_key>'
OPENAI_API_KEY = '<your_api_key>'

2. 创建一个提示

要在 LangSmith 中创建提示,需定义提示中所需的消息列表,然后使用 ChatPromptTemplate 函数(Python)或 TypeScript 函数将其封装。 然后,只需调用 push_prompt(Python)或 pushPrompt(TypeScript)即可将您的提示发送到 LangSmith!

from langsmith import Client
from langchain_core.prompts import ChatPromptTemplate

# Connect to the LangSmith client

client = Client()

# Define the prompt

prompt = ChatPromptTemplate([
("system", "You are a helpful chatbot."),
("user", "{question}"),
])

# Push the prompt

client.push_prompt("my-prompt", object=prompt)

3. 测试提示

要测试一个提示词,你需要先提取该提示词,用你想要测试的输入值调用它,然后使用这些输入值来调用模型。 你的大语言模型或应用程序所期望的。

from langsmith import Client
from openai import OpenAI
from langchain_core.messages import convert_to_openai_messages

# Connect to LangSmith and OpenAI

client = Client()
oai_client = OpenAI()

# Pull the prompt to use

# You can also specify a specific commit by passing the commit hash "my-prompt:<commit-hash>"

prompt = client.pull_prompt("my-prompt")

# Since our prompt only has one variable we could also pass in the value directly

# The code below is equivalent to formatted_prompt = prompt.invoke("What is the color of the sky?")

formatted_prompt = prompt.invoke({"question": "What is the color of the sky?"})

# Test the prompt

response = oai_client.chat.completions.create(
model="gpt-4o",
messages=convert_to_openai_messages(formatted_prompt.messages),
)

4. 迭代优化提示词

LangSmith 让您和整个团队轻松协作迭代提示。工作区的成员可以选择一个提示进行迭代,一旦他们对所做的更改感到满意,就可以将其保存为一个新的提交。

为了改进你的提示:

要向提示中添加新的提交,可以使用与首次创建提示时相同的 push_prompt(Python)或 pushPrompt(TypeScript)方法。

from langsmith import Client
from langchain_core.prompts import ChatPromptTemplate

# Connect to the LangSmith client

client = Client()

# Define the prompt to update

new_prompt = ChatPromptTemplate([
("system", "You are a helpful chatbot. Respond in Spanish."),
("user", "{question}"),
])

# Push the updated prompt making sure to use the correct prompt name

# Tags can help you remember specific versions in your commit history

client.push_prompt("my-prompt", object=new_prompt, tags=["Spanish"])

5. 后续步骤


这个页面对你有帮助吗?


您可以留下详细的反馈 在 GitHub 上.