프롬프트 객체 만들기
프롬프트 객체 만들기 (Prompt)
프롬프트를 만들고, 평가하고, 다듬는 일은 AI 엔지니어의 핵심 작업이에요. 프롬프트의 아주 작은 변경이 애플리케이션 동작에 큰 영향을 줄 수 있거든요. Weave에서는 프롬프트를 만들어서 게시(publish)하고, 시간이 지나며 진화시킬 수 있습니다. 이 페이지에서는 재사용 가능한 프롬프트 객체를 만들고 게시해 애플리케이션 코드에서 참조하게 하는 방법을 다룰게요. 단일 문자열과 멀티턴(multi-turn) 프롬프트를 만들고, 런타임 값으로 파라미터화하고, Weave 프로젝트에 게시하는 흐름까지 살펴봅니다.
참고: 게시된 프롬프트를 참조·조회·버전 관리하는 방법은 프롬프트 버전 저장·추적 문서를 참고하세요.
프롬프트 요구사항이 단순하다면 내장된 weave.StringPrompt나 weave.MessagesPrompt 클래스를 쓰면 돼요. 더 복잡하다면 그 클래스들을 상속하거나, 기본 클래스 weave.Prompt를 상속해 format 메서드를 오버라이드하면 됩니다. weave.publish로 프롬프트를 게시하면 Weave 프로젝트의 Prompts 페이지에 나타나서, 동료들과 함께 살펴보고 재사용할 수 있어요.
StringPrompt
StringPrompt는 시스템 메시지, 사용자 질의, 또는 LLM에 보내는 단일 텍스트 입력처럼 단일 문자열 프롬프트를 기록해요. 멀티 메시지 대화의 복잡함이 필요 없는 개별 프롬프트 문자열을 관리할 때 씁니다.
import weave
weave.init('intro-example')
system_prompt = weave.StringPrompt("You speak like a pirate")
weave.publish(system_prompt, name="pirate_prompt")
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": system_prompt.format()
},
{
"role": "user",
"content": "Explain general relativity in one paragraph."
}
],
)
MessagesPrompt
MessagesPrompt는 멀티턴 대화와 채팅 기반 프롬프트를 기록하게 해 줘요. system, user, assistant 같은 역할(role)을 가진 메시지 객체 배열을 저장해 완전한 대화 흐름을 나타냅니다. 여러 메시지에 걸쳐 컨텍스트를 유지해야 하는 채팅 기반 LLM, 특정 대화 패턴 정의, 재사용 가능한 대화 템플릿을 만들 때 유용해요.
import weave
weave.init('intro-example')
prompt = weave.MessagesPrompt([
{
"role": "system",
"content": "You are a stegosaurus, but don't be too obvious about it."
},
{
"role": "user",
"content": "What's good to eat around here?"
}
])
weave.publish(prompt, name="dino_prompt")
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=prompt.format(),
)
프롬프트 파라미터화하기
정적 프롬프트를 만들 수 있게 되면, 다음 단계는 서로 다른 입력에서 재사용할 수 있게 하는 거예요. StringPrompt와 MessagesPrompt 모두 파라미터화를 통해 동적 콘텐츠를 지원합니다. {variable} 문법으로 자리 표시자(placeholder)를 만든 프롬프트 템플릿을 만들고, 런타임에 다른 값으로 채우는 방식이에요. 프롬프트가 서로 다른 입력·사용자 데이터·컨텍스트에 적응하면서도 일관된 구조를 유지해야 할 때 유용합니다. format() 메서드는 키-값 쌍을 받아 이 자리 표시자를 실제 값으로 바꿔줘요.
import weave
weave.init('intro-example')
prompt = weave.StringPrompt("Solve the equation {equation}")
weave.publish(prompt, name="calculator_prompt")
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": prompt.format(equation="1 + 1 = ?")
}
],
)
같은 파라미터화 패턴은 멀티턴 대화 안에 자리 표시자를 넣어야 할 때 MessagesPrompt에서도 동일하게 동작해요.
import weave
weave.init('intro-example')
prompt = weave.MessagesPrompt([
{
"role": "system",
"content": "You will be provided with a description of a scene and your task is to provide a single word that best describes an associated emotion."
},
{
"role": "user",
"content": "{scene}"
}
])
weave.publish(prompt, name="emotion_prompt")
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=prompt.format(scene="A dog is lying on a dock next to a fisherman."),
)