0Pricing
AI Prompt Engineering · 강의

시그니처와 모듈 정의

시그니처 구문, ChainOfThought, ReAct, 사용자 지정 DSPy 모듈을 다룹니다.

시그니처와 모듈 정의은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

시그니처는 형식이 지정된 계약입니다

DSPy의 signature는 추론 단계의 입력과 출력을 선언하는 Python 클래스입니다. 이를 LLM 호출을 위한 형식이 지정된 함수 계약이라고 생각하면 됩니다.

문서 문자열은 작업 설명이 됩니다. 필드 주석은 DSPy에 생성해야 할 내용을 알려 줍니다. 실제 프롬프트 텍스트는 작성하지 않으며, DSPy가 이 선언에서 도출합니다.

기본 시그니처 정의하기

최소한의 signature는 dspy.Signature를 상속하고 필드에 InputField 또는 OutputField로 주석을 다는 방식으로 만듭니다. 클래스의 문서 문자열이 작업 지침을 제공합니다.

import dspy

class QASignature(dspy.Signature):
    """Answer the question based on the given context."""
    context: str = dspy.InputField(desc='Relevant background text')
    question: str = dspy.InputField(desc='The question to answer')
    answer: str = dspy.OutputField(desc='A concise answer')

# Inspect what DSPy sees
print(QASignature.instructions)  # The docstring
print(list(QASignature.input_fields.keys()))   # ['context', 'question']
print(list(QASignature.output_fields.keys()))  # ['answer']

여러 출력 필드

시그니처에는 여러 출력 필드가 있을 수 있습니다. DSPy는 한 번의 호출로 모든 출력 필드를 생성하도록 모델에 프롬프트를 구성합니다. 이는 구조화된 정보를 추출할 때 유용합니다.

import dspy

class EntityExtraction(dspy.Signature):
    """Extract named entities from the text."""
    text: str = dspy.InputField()
    people: list[str] = dspy.OutputField(desc='List of person names mentioned')
    organizations: list[str] = dspy.OutputField(desc='List of organization names')
    locations: list[str] = dspy.OutputField(desc='List of place names')

extractor = dspy.Predict(EntityExtraction)
result = extractor(text='Elon Musk founded SpaceX in Hawthorne, California.')
print(result.people, result.organizations, result.locations)

Predict 모듈

dspy.Predict는 가장 단순한 모듈입니다. signature를 받아 LM에 출력을 직접 생성하도록 요청합니다. 추론을 위한 보조 구조는 추가하지 않고, signature에 맞는 구조화된 프롬프트만 사용합니다.

작업이 간단하고 명시적인 추론 단계가 필요하지 않을 때 Predict를 사용하십시오.

import dspy

class Classify(dspy.Signature):
    """Classify the sentiment of the review."""
    review: str = dspy.InputField()
    sentiment: str = dspy.OutputField(desc='positive, negative, or neutral')

# Predict wraps the signature with a direct prompt
classifier = dspy.Predict(Classify)
result = classifier(review='The food was amazing and the service was excellent!')
print(result.sentiment)  # positive

ChainOfThought 모듈

dspy.ChainOfThought는 signature에 중간 단계인 reasoning 필드를 추가합니다. 모델은 먼저 추론 과정을 작성한 다음 최종 답변을 생성합니다.

사용자가 사고 과정 프롬프트 지침을 작성하지 않아도 여러 단계로 이루어진 문제의 정확도가 일관되게 향상됩니다.

import dspy

class MathSolver(dspy.Signature):
    """Solve the math problem."""
    problem: str = dspy.InputField()
    answer: str = dspy.OutputField(desc='The numerical answer')

# ChainOfThought adds a 'reasoning' step automatically
solver = dspy.ChainOfThought(MathSolver)
result = solver(problem='If a train travels 60 mph for 2.5 hours, how far does it go?')
print(result.reasoning)  # Step-by-step reasoning
print(result.answer)     # 150 miles

ReAct 모듈

dspy.ReAct는 추론 + 행동 루프를 구현합니다. 모델이 추론 단계와 도구 호출을 번갈아 수행하므로 검색하거나 calculate하거나 데이터를 가져와야 하는 에이전트에 적합합니다.

도구 목록(문서 문자열이 포함된 Python 함수)을 제공하면 DSPy가 이 과정을 자동으로 교차 배치합니다.

import dspy

def search_web(query: str) -> str:
    """Search the web and return relevant results."""
    # In production, call a real search API
    return f'Search results for: {query}'

def calculate(expression: str) -> str:
    """Evaluate a mathematical expression."""
    return str(eval(expression))

class ResearchQA(dspy.Signature):
    """Answer the question using web search and calculation as needed."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

agent = dspy.ReAct(ResearchQA, tools=[search_web, calculate])
result = agent(question='What is 15% of 847?')
print(result.answer)

모듈을 프로그램으로 조합하기

실질적인 힘은 모듈을 여러 단계로 이루어진 프로그램으로 조합할 때 발휘됩니다. dspy.Module을 상속하고, __init__에서 하위 모듈을 정의하며, forward()를 구현해 이들을 연결하십시오.

import dspy

class RetrieveAndAnswer(dspy.Module):
    def __init__(self):
        super().__init__()
        self.retrieve = dspy.Retrieve(k=3)  # Retrieves top-3 passages
        self.generate = dspy.ChainOfThought('context, question -> answer')

    def forward(self, question):
        passages = self.retrieve(question).passages
        context = '\n'.join(passages)
        return self.generate(context=context, question=question)

# This is a complete RAG pipeline in ~10 lines
rag = RetrieveAndAnswer()
result = rag(question='What are the main causes of climate change?')
print(result.answer)

인라인 시그니처 축약형

간단한 경우 DSPy는 인라인 문자열 signature를 사용할 수 있습니다. 'input1, input2 -> output1, output2'와 같이 작성하며, 전체 클래스를 정의하지 않고 빠르게 프로토타입을 만들 때 편리합니다.

import dspy

# Full class signature
class Translate(dspy.Signature):
    """Translate text to French."""
    text: str = dspy.InputField()
    translation: str = dspy.OutputField()

# Equivalent inline shorthand
translator_v1 = dspy.Predict(Translate)
translator_v2 = dspy.Predict('text -> translation')  # Less metadata

# Both work the same way
result = translator_v1(text='Hello world')
print(result.translation)

필드 설명의 중요성

InputField와 OutputField의 desc 매개변수는 생성된 프롬프트에 포함됩니다. 설명을 잘 작성하면 모델이 정확한 방향으로 작업하도록 안내할 수 있습니다.

desc를 필드 이름과 함께 프롬프트에 나타나는 필드별 문서라고 생각하십시오.

import dspy

class Summarize(dspy.Signature):
    """Summarize the article for a busy executive."""
    article: str = dspy.InputField(
        desc='The full article text to summarize'
    )
    summary: str = dspy.OutputField(
        desc='3-5 bullet points highlighting key decisions and numbers'
    )
    confidence: float = dspy.OutputField(
        desc='Your confidence in the summary accuracy from 0.0 to 1.0'
    )

summarizer = dspy.Predict(Summarize)
# DSPy constructs a prompt using all the desc values automatically

프로그램 저장 및 불러오기

최적화한 후에는 컴파일된 프로그램을 저장하여 매번 최적화를 다시 실행하지 않도록 해야 합니다. DSPy는 최적화된 상태를 JSON 파일로 직렬화합니다.

import dspy

class QA(dspy.Signature):
    """Answer questions accurately."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

program = dspy.ChainOfThought(QA)

# After optimization, save the compiled state
program.save('optimized_qa.json')

# Load it later without re-running optimization
loaded_program = dspy.ChainOfThought(QA)
loaded_program.load('optimized_qa.json')

result = loaded_program(question='What is the speed of light?')
print(result.answer)

출력 제약 조건을 위한 검증 조건

DSPy의 검증 조건을 사용하면 출력에 대한 제약 조건을 선언할 수 있습니다. 모델이 제약 조건을 위반하면 DSPy가 수정 피드백과 함께 자동으로 다시 시도하므로 수동 재시도 논리가 필요하지 않습니다.

import dspy

class ShortAnswer(dspy.Signature):
    """Answer in at most 10 words."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

class ConstrainedQA(dspy.Module):
    def __init__(self):
        super().__init__()
        self.predict = dspy.Predict(ShortAnswer)

    def forward(self, question):
        result = self.predict(question=question)
        # Assert: answer must be at most 10 words
        dspy.Assert(
            len(result.answer.split()) <= 10,
            'The answer must be 10 words or fewer.'
        )
        return result

지식 확인: ChainOfThought

같은 signature를 사용할 때 dspy.Predict와 비교하여 dspy.ChainOfThought는 무엇을 추가합니까?

복습: 시그니처와 모듈

DSPy의 시그니처는 LLM 단계가 수행해야 할 작업, 즉 입력과 출력 및 문서 문자열 지침을 설명하는 형식이 지정된 클래스 선언입니다. Predict, ChainOfThought, ReAct와 같은 모듈은 signature를 바탕으로 서로 다른 추론 전략을 구현합니다. 여러 모듈을 dspy.Module 하위 클래스 안에서 조합하여 여러 단계로 이루어진 파이프라인을 구축합니다. 필드의 desc 값은 자동 생성된 프롬프트 안에서 모델을 안내하고, 검증 조건은 자동 재시도로 출력 제약 조건을 적용합니다.

자주 묻는 질문

“시그니처와 모듈 정의” 강의는 무료인가요?

네 — “시그니처와 모듈 정의” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

“시그니처와 모듈 정의”에서 뭘 배우나요?

시그니처 구문, ChainOfThought, ReAct, 사용자 지정 DSPy 모듈을 다룹니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“시그니처와 모듈 정의” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. DSPy 프레임워크 소개
  2. 시그니처와 모듈 정의
  3. 프롬프트 컴파일 및 최적화
  4. DSPy 파이프라인 평가
← AI Prompt Engineering(으)로 돌아가기