DSPy is a declarative framework for building modular AI software with structured code instead of brittle prompts, offering algorithms that compile AI programs into effective prompts and weights for language models across classifiers, RAG pipelines, and agent loops.
import dspyimport osfrom dotenv import load_dotenvload_dotenv()# Configure DSPy to use Helicone AI Gatewaylm = dspy.LM( 'gpt-4o-mini', # or any other model from the Helicone model registry api_key=os.getenv('HELICONE_API_KEY'), api_base='https://ai-gateway.helicone.ai/')dspy.configure(lm=lm)print(lm("Hello, world!"))
import dspyimport osfrom dotenv import load_dotenvload_dotenv()# Configure Helicone AI Gatewaylm = dspy.LM( 'gpt-4o-mini', api_key=os.getenv('HELICONE_API_KEY'), api_base='https://ai-gateway.helicone.ai/v1')dspy.configure(lm=lm)# Define a moduleqa = dspy.ChainOfThought('question -> answer')# Run inferenceresponse = qa(question="How many floors are in the castle David Gregory inherited?")print('Answer:', response.answer)print('Reasoning:', response.reasoning)
Configure temperature, max_tokens, and other parameters:
Python
import dspyimport osfrom dotenv import load_dotenvload_dotenv()# Configure with custom generation parameterslm = dspy.LM( 'gpt-4o-mini', api_key=os.getenv('HELICONE_API_KEY'), api_base='https://ai-gateway.helicone.ai/v1', temperature=0.9, max_tokens=2000)dspy.configure(lm=lm)# Use with any DSPy modulepredict = dspy.Predict("question -> creative_answer")response = predict(question="Write a creative story about AI")print(response.creative_answer)
import uuidsession_id = str(uuid.uuid4())lm = dspy.LM( 'gpt-4o-mini', api_key=os.getenv('HELICONE_API_KEY'), api_base='https://ai-gateway.helicone.ai/v1', extra_headers={ 'Helicone-Session-Id': session_id, 'Helicone-Session-Name': 'Customer Support', 'Helicone-Session-Path': '/support/chat' })dspy.configure(lm=lm)# All calls in this session will be grouped togetherqa = dspy.ChainOfThought('question -> answer')# Multiple turnsresponse1 = qa(question="What is your return policy?")response2 = qa(question="How long does shipping take?")response3 = qa(question="Do you ship internationally?")# View the full conversation in Helicone Sessions