pythonadvanced

DSPy Chain-of-Thought Module

Use DSPy to programmatically build and optimise chain-of-thought reasoning pipelines.

python
import dspy

dspy.configure(lm=dspy.OpenAI(model='gpt-4o-mini'))

class QASignature(dspy.Signature):
    '''Answer questions with step-by-step reasoning.'''
    question: str = dspy.InputField()
    answer:   str = dspy.OutputField(desc='concise final answer')

class CoTQA(dspy.Module):
    def __init__(self):
        self.cot = dspy.ChainOfThought(QASignature)

    def forward(self, question: str) -> dspy.Prediction:
        return self.cot(question=question)

qa = CoTQA()

questions = ['If a train travels 60mph for 2.5 hours, how far does it go?', 'What is the factorial of 6?']
for q in questions:
    pred = qa(question=q)
    print(f'Q: {q}')
    print(f'A: {pred.answer}\n')

Use Cases

  • systematic reasoning
  • LLM optimization
  • research pipelines

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.