메인 콘텐츠로 건너뛰기
DSPy는 특히 파이프라인 내에서 LM을 한 번 이상 사용할 때 LM 프롬프트와 가중치를 알고리즘적으로 최적화하는 프레임워크입니다. Weave는 DSPy 모듈과 함수를 사용해 발생한 call을 자동으로 추적하고 로깅합니다.

트레이싱

개발 중이든 프로덕션 환경이든, 언어 모델 애플리케이션의 트레이스를 중앙에서 저장하는 것이 중요합니다. 이러한 트레이스는 디버깅에 유용하며, 애플리케이션 개선에 도움이 되는 데이터셋으로도 활용할 수 있습니다. Weave는 DSPy의 트레이스를 자동으로 수집합니다. 추적을 시작하려면 weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")를 호출한 다음, 평소처럼 라이브러리를 사용하세요.
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"

weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

lm = dspy.LM('openai/gpt-4o-mini')
dspy.configure(lm=lm)
classify = dspy.Predict("sentence -> sentiment")
classify(sentence="it's a charming and often affecting journey.")
dspy_trace.png Weave는 DSPy 프로그램의 모든 LM calls를 로깅하며, inputs, outputs, 메타데이터에 관한 세부 정보를 제공합니다.

사용자 정의 DSPy 모듈과 시그니처 추적

Module은 프롬프팅 기법을 추상화하는 DSPy 프로그램의 기본 구성 요소로, 학습 가능한 파라미터를 가집니다. Signature는 DSPy Module의 입력/출력 동작을 선언적으로 정의하는 명세입니다. Weave는 DSPy 프로그램에 포함된 모든 내장 및 사용자 정의 Signatures와 Modules를 자동으로 추적합니다.
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"

weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

class Outline(dspy.Signature):
    """Outline a thorough overview of a topic."""

    topic: str = dspy.InputField()
    title: str = dspy.OutputField()
    sections: list[str] = dspy.OutputField()
    section_subheadings: dict[str, list[str]] = dspy.OutputField(
        desc="mapping from section headings to subheadings"
    )


class DraftSection(dspy.Signature):
    """Draft a top-level section of an article."""

    topic: str = dspy.InputField()
    section_heading: str = dspy.InputField()
    section_subheadings: list[str] = dspy.InputField()
    content: str = dspy.OutputField(desc="markdown-formatted section")


class DraftArticle(dspy.Module):
    def __init__(self):
        self.build_outline = dspy.ChainOfThought(Outline)
        self.draft_section = dspy.ChainOfThought(DraftSection)

    def forward(self, topic):
        outline = self.build_outline(topic=topic)
        sections = []
        for heading, subheadings in outline.section_subheadings.items():
            section, subheadings = (
                f"## {heading}",
                [f"### {subheading}" for subheading in subheadings],
            )
            section = self.draft_section(
                topic=outline.title,
                section_heading=section,
                section_subheadings=subheadings,
            )
            sections.append(section.content)
        return dspy.Prediction(title=outline.title, sections=sections)


draft_article = DraftArticle()
article = draft_article(topic="World Cup 2002")
모듈 실행 흐름과 트레이스 세부 정보가 표시된 Weave의 DSPy 맞춤형 모듈 트레이스

DSPy 프로그램의 최적화 및 평가

Weave는 DSPy 옵티마이저와 Evaluation call의 트레이스도 자동으로 수집하므로, 이를 활용해 개발 세트에서 DSPy 프로그램의 성능을 개선하고 평가할 수 있습니다.
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"
weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

def accuracy_metric(answer, output, trace=None):
    predicted_answer = output["answer"].lower()
    return answer["answer"].lower() == predicted_answer

module = dspy.ChainOfThought("question -> answer: str, explanation: str")
optimizer = dspy.BootstrapFewShot(metric=accuracy_metric)
optimized_module = optimizer.compile(
    module, trainset=SAMPLE_EVAL_DATASET, valset=SAMPLE_EVAL_DATASET
)
최적화 과정과 성능 개선을 보여주는 Weave의 DSPy optimizer 트레이스