import dspy
from dspy.evaluate import Evaluate
# Configure TrueFoundry LM
lm = dspy.LM(
model="openai/anthropic-account/claude-4",
api_key="your-truefoundry-api-key",
api_base="your-truefoundry-gateway-url"
)
dspy.configure(lm=lm)
# Define a simple QA module
class QA(dspy.Module):
def __init__(self):
super().__init__()
self.generate_answer = dspy.ChainOfThought("question -> answer")
def forward(self, question):
prediction = self.generate_answer(question=question)
return dspy.Prediction(answer=prediction.answer)
# Create training examples
trainset = [
dspy.Example(question="What is the capital of France?", answer="Paris"),
dspy.Example(question="What is the capital of Japan?", answer="Tokyo"),
dspy.Example(question="What is the capital of Brazil?", answer="Brasília"),
]
# Define evaluation metric
def validate_answer(example, pred, trace=None):
return example.answer.lower() in pred.answer.lower()
# Initialize module and optimizer
qa_module = QA()
optimizer = dspy.BootstrapFewShot(metric=validate_answer)
# Optimize the module
optimized_qa = optimizer.compile(qa_module, trainset=trainset)
# Test the optimized module
question = "What is the capital of Brazil?"
result = optimized_qa(question)
print(f"Optimized Answer: {result.answer}")