Skip to main content

提示工程快速入门 (SDK)

本快速入门指南将介绍如何使用 SDK 创建、测试和迭代提示。在本教程中,我们将使用 OpenAI,但您也可以使用任何您想要的 LLM。

快速开始

本教程使用提示工程 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. 测试提示词

要测试一个提示词,您需要获取该提示词,使用您想要测试的输入值调用它,然后使用这些输入值调用模型。 您的 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. 迭代提示词

LangSmith 让您的整个团队都能轻松迭代提示词。工作区成员可以选择一个提示词进行迭代,当他们对自己的修改满意后,只需将其保存为新的提交即可。

为了改进您的提示词:

To add a new commit to a prompt, you can use the same push_prompt (Python) or pushPrompt (TypeScript) methods as when you first created the prompt.

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 存储和管理提示词。
  • 了解更多关于如何在 这些操操作指南 中使用 playground 进行提示工程的内容

此页面有帮助吗?


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