Solution 1
⭐⭐ Intermediate
Customer Support RAG System
import dspy
class CustomerSupportRAG(dspy.Module):
def __init__(self, knowledge_base=None):
super().__init__()
# In a real scenario, knowledge_base would be indexed in a vector DB
# Here we simulate retrieval
self.knowledge_base = knowledge_base or []
self.retrieve = dspy.Retrieve(k=3)
self.generate_answer = dspy.ChainOfThought(
"question, context -> answer, sources, confidence"
)
def forward(self, question):
# 1. Retrieve relevant info
# context = self.retrieve(question)
# Simulating retrieval for this example:
context = [doc for doc in self.knowledge_base if any(kw in doc.lower() for kw in question.lower().split())]
context_str = "\n".join(context) if context else "No relevant documents found."
# 2. Generate answer
prediction = self.generate_answer(
question=question,
context=context_str
)
return dspy.Prediction(
answer=prediction.answer,
reasoning=prediction.rationale,
sources=context,
confidence=prediction.confidence
)
# Example Usage
kb = [
"Product returns must be initiated within 30 days of purchase.",
"Free shipping is available for orders over $50.",
"Customer support is available 24/7 via phone and chat."
]
rag = CustomerSupportRAG(knowledge_base=kb)
result = rag("What is the return policy?")
print(f"Answer: {result.answer}")
print(f"Confidence: {result.confidence}")
Solution 2
⭐⭐⭐ Advanced
Multi-hop Research Assistant
class ResearchAssistant(dspy.Module):
def __init__(self):
super().__init__()
self.retrieve = dspy.Retrieve(k=3)
self.generate_subquestions = dspy.Predict(
"question -> subquestions"
)
self.synthesize = dspy.ChainOfThought(
"question, findings -> answer"
)
def forward(self, research_question):
# 1. Break down complex question
plan = self.generate_subquestions(question=research_question)
subquestions = plan.subquestions.split("\n")
findings = []
for subq in subquestions:
# 2. Retrieve info for each step
docs = self.retrieve(subq).passages
findings.append(f"Q: {subq}\nFound: {docs}")
# 3. Synthesize final answer
result = self.synthesize(
question=research_question,
findings="\n\n".join(findings)
)
return dspy.Prediction(
answer=result.answer,
reasoning=result.rationale
)
Solution 3
⭐⭐ Intermediate
Multi-label Document Classifier
class MultiLabelClassifier(dspy.Module):
def __init__(self, possible_labels):
super().__init__()
self.labels = ", ".join(possible_labels)
self.classify = dspy.Predict(
f"document, possible_labels[{self.labels}] -> applied_labels, confidence_scores"
)
def forward(self, document):
prediction = self.classify(
document=document,
possible_labels=self.labels
)
# Parse labels (assuming comma-separated output)
labels = [l.strip() for l in prediction.applied_labels.split(',')]
return dspy.Prediction(
labels=labels,
scores=prediction.confidence_scores
)
Solution 4
⭐⭐⭐ Advanced
Contract Information Extractor
class ContractExtractor(dspy.Module):
def __init__(self):
super().__init__()
self.extract_parties = dspy.Predict("contract -> parties")
self.extract_dates = dspy.Predict("contract -> effective_date, termination_date")
self.extract_terms = dspy.Predict("contract -> payment_terms, obligations")
def forward(self, contract_text):
parties = self.extract_parties(contract=contract_text)
dates = self.extract_dates(contract=contract_text)
terms = self.extract_terms(contract=contract_text)
return dspy.Prediction(
parties=parties.parties,
dates={
"effective": dates.effective_date,
"termination": dates.termination_date
},
terms={
"payment": terms.payment_terms,
"obligations": terms.obligations
}
)
Solution 5
⭐⭐⭐ Advanced
Autonomous Customer Service Agent
class CustomerServiceAgent(dspy.Module):
def __init__(self):
super().__init__()
self.classify_intent = dspy.Predict("message -> intent")
self.handle_inquiry = dspy.ChainOfThought("message, history -> response, action")
self.escalate = dspy.Predict("message, reason -> department")
self.history = []
def forward(self, customer_message):
# 1. Identify Intent
intent = self.classify_intent(message=customer_message).intent
# 2. Add to history
self.history.append(f"User: {customer_message}")
if "urgent" in intent.lower() or "complaint" in intent.lower():
# Escalate
dept = self.escalate(message=customer_message, reason=intent)
response = f"I am escalating this issue to {dept.department}."
action = "ESCALATE"
else:
# Handle normally
result = self.handle_inquiry(
message=customer_message,
history="\n".join(self.history[-5:])
)
response = result.response
action = result.action
self.history.append(f"Agent: {response}")
return dspy.Prediction(
response=response,
action=action,
intent=intent
)
Solution 6
⭐⭐ Intermediate
Code Review Assistant
class CodeReviewAssistant(dspy.Module):
def __init__(self):
super().__init__()
self.analyze = dspy.ChainOfThought(
"code, language -> bugs, security_issues, style_suggestions, overall_score"
)
def forward(self, code, language="python"):
review = self.analyze(code=code, language=language)
return dspy.Prediction(
bugs=review.bugs,
security=review.security_issues,
style=review.style_suggestions,
score=review.overall_score,
summary=review.rationale
)
Congratulations! You've completed Chapter 6: Real-World Applications. You now have a portfolio of powerful AI applications built with DSPy!