DSPy 101 Tutorial: Prompting Guide

Simplify LLM-powered applications with DSPy.

DSPy Prompt

Quick Start


import dspy

lm = dspy.LM('ollama_chat/llama3.2:1b', api_base='http://localhost:11434')
dspy.configure(lm=lm)

This snippet initializes a language model and configures DSPy for use.

Defining a Signature


from typing import Literal

class Categorize(dspy.Signature):
    event: str = dspy.InputField()
    category: Literal['Wars and Conflicts', 'Politics'] = dspy.OutputField()
    confidence: float = dspy.OutputField()

Signatures define input-output structures, making your models more intuitive.

Calling the Module


classify = dspy.Predict(Categorize)
classification = classify(event="[YOUR HISTORIC EVENT]")
print(classification)

Use the Predict module to classify events with ease.

Optimizing Prompts


from dspy.teleprompt import *
tp = dspy.MIPROv2(metric=validate_category, auto="light")
optimized_classify = tp.compile(classify, trainset=trainset)

Optimize prompts with DSPy’s Teleprompt module for better performance.

Saving Optimized Systems


optimized_classify.save("optimized_event_classifier.json")

Save your optimized classification systems for later use or deployment.

Go back to Home