跳到主要内容

Prompt Engineering 快速入门 (SDK)

本快速入门将引导您了解如何使用 SDK 创建、测试和迭代 Prompt。在本教程中,我们将使用 OpenAI,但您可以根据需要使用任何 LLM。

快速入门

本教程使用 SDK 进行 Prompt 工程,如果您有兴趣改用 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. 创建 Prompt

要在 LangSmith 中创建 Prompt,请定义您希望在 Prompt 中包含的消息列表,然后使用 ChatPromptTemplate 函数(Python)或 TypeScript 函数将其包装起来。然后,您只需调用 push_prompt (Python) 或 pushPrompt (TypeScript) 即可将您的 Prompt 发送到 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. 测试 Prompt

要测试 Prompt,您需要拉取 Prompt,使用您要测试的输入值调用它,然后使用这些输入值调用模型。您的 LLM 或应用程序期望的输入值。

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. 迭代 Prompt

LangSmith 使您的整个团队可以轻松迭代 Prompt。您的工作区成员可以选择要迭代的 Prompt,一旦他们对更改感到满意,他们就可以简单地将其保存为新的提交。

为了改进您的 Prompt

要向 Prompt 添加新的提交,您可以像首次创建 Prompt 时一样使用相同的 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. 后续步骤

  • 了解有关如何使用 Prompt Hub 存储和管理 Prompt 的更多信息,请参阅这些操作指南
  • 了解有关如何使用 Playground 进行 Prompt 工程的更多信息,请参阅这些操作指南

此页面是否对您有帮助?


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