Package: dspy-ai
DSPy:Programming—not prompting—Foundation Models[Oct'23]DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines[Jan'24]In-Context Learning for Extreme Multi-Label Classification[Dec'23]DSPy Assertions: Computational Constraints for Self-Refining Language Model Pipelines[Dec'22]Demonstrate-Search-Predict: Composing Retrieval & Language Models for Knowledge-Intensive NLPGetting Started:Documentation:DSPy DocsDSPy is a framework for algorithmically optimizing LM prompts and weights, especially when LMs are used one or more times within a pipeline. To use LMs to build a complex systemwithoutDSPy, you generally have to: (1) break the problem down into steps, (2) prompt your LM well until each step works well in isolation, (3) tweak the steps to work well together, (4) generate synthetic examples to tune each step, and (5) use these examples to finetune smaller LMs to cut costs. Currently, this is hard and messy: every time you change your pipeline, your LM, or your data, all prompts (or finetuning steps) may need to change.To make this more systematic and much more powerful,DSPydoes two things. First, it separates the flow of your program (modules) from the parameters (LM prompts and weights) of each step. Second,DSPyintroduces newoptimizers, which are LM-driven algorithms that can tune the prompts and/or the weights of your LM calls, given ametricyou want to maximize.DSPycan routinely teach powerful models likeGPT-3.5orGPT-4and local models likeT5-baseorLlama2-13bto be much more reliable at tasks, i.e. having higher quality and/or avoiding specific failure patterns.DSPyoptimizers will "compile" thesameprogram intodifferentinstructions, few-shot prompts, and/or weight updates (finetunes) for each LM. This is a new paradigm in which LMs and their prompts fade into the background as optimizable pieces of a larger system that can learn from data.tldr;less prompting, higher scores, and a more systematic approach to solving hard tasks with LMs.Table of ContentsIf you need help thinking about your task, we recently created aDiscord serverfor the community.InstallationTutorials & DocumentationFramework SyntaxCompiling: Two Powerful ConceptsFAQ: Is DSPy right for me?Analogy to Neural NetworksWhen we build neural networks, we don't write manualfor-loopsover lists ofhand-tunedfloats. Instead, you might use a framework likePyTorchto compose declarative layers (e.g.,ConvolutionorDropout) and then use optimizers (e.g., SGD or Adam) to learn the parameters of the network.Ditto!DSPygives you the right general-purpose modules (e.g.,ChainOfThought,ReAct, etc.), which replace string-based prompting tricks. To replace prompt hacking and one-off synthetic data generators,DSPyalso gives you general optimizers (BootstrapFewShotWithRandomSearchorBayesianSignatureOptimizer), which are algorithms that update parameters in your program. Whenever you modify your code, your data, your assertions, or your metric, you cancompileyour program again andDSPywill create new effective prompts that fit your changes.Mini-FAQsWhat do DSPy optimizers tune?Each optimizer is different, but they all seek to maximize a metric on your program by updating prompts or LM weights. Current DSPyoptimizerscan inspect your data, simulate traces through your program to generate good/bad examples of each step, propose or refine instructions for each step based on past results, finetune the weights of your LM on self-generated examples, or combine several of these to improve quality or cut cost. We'd love to merge new optimizers that explore a richer space: most manual steps you currently go through for prompt engineering, "synthetic data" generation, or self-improvement can probably generalized into a DSPy optimizer that acts on arbitrary LM programs.How should I use DSPy for my task?Using DSPy is an iterative process. You first define your task and the metrics you want to maximize, and prepare a few example inputs — typically without labels (or only with labels for the final outputs, if your metric requires them). Then, you build your pipeline by selecting built-in layers (modules) to use, giving each layer asignature(input/output spec), and then calling your modules freely in your Python code. Lastly, you use a DSPyoptimizerto compile your code into high-quality instructions, automatic few-shot examples, or updated LM weights for your LM.What if I have a better idea for prompting or synthetic data generation?Perfect. We encourage you to think if it's best expressed as a module or an optimizer, and we'd love to merge it in DSPy so everyone can use it. DSPy is not a complete project; it's an ongoing effort to create structure (modules and optimizers) in place of hacky prompt and pipeline engineering tricks.What does DSPy stand for?It's a long story but the backronym now isDeclarativeSelf-improving LanguagePrograms, pythonically.1) InstallationAll you need is:pip install dspy-aiOr open our intro notebook in Google Colab:By default, DSPy installs the latestopenaifrom pip. However, if you install old version before OpenAI changed their APIopenai~=0.28.1, the library will use that just fine. Both are supported.For the optional (alphabetically sorted)Chromadb,Qdrant,Marqo, Pinecone, orWeaviateretrieval integration(s), include the extra(s) below:pip install dspy-ai[chromadb]  # or [qdrant] or [marqo] or [mongodb] or [pinecone] or [weaviate]2) DocumentationThe DSPy documentation is divided intotutorials(step-by-step illustration of solving a task in DSPy),guides(how to use specific parts of the API), andexamples(self-contained programs that illustrate usage).A) TutorialsLevelTutorialRun in ColabDescriptionBeginnerGetting StartedIntroduces the basic building blocks in DSPy. Tackles the task of complex question answering with HotPotQA.BeginnerMinimal Working ExampleN/ABuilds and optimizes a very simple chain-of-thought program in DSPy for math question answering. Very short.BeginnerCompiling for Tricky TasksN/ATeaches LMs to reason about logical statements and negation. Uses GPT-4 to bootstrap few-shot CoT demonstations for GPT-3.5. Establishes a state-of-the-art result onScoNe. Contributed byChris Potts.BeginnerLocal Models & Custom DatasetsIllustrates two different things together: how to use local models (Llama-2-13B in particular) and how to use your own data examples for training and development.IntermediateThe DSPy PaperN/ASections 3, 5, 6, and 7 of the DSPy paper can be consumed as a tutorial. They include explained code snippets, results, and discussions of the abstractions and API.IntermediateDSPy AssertionsIntroduces example of applying DSPy Assertions while generating long-form responses to questions with citations. Presents comparative evaluation in both zero-shot and compiled settings.IntermediateFinetuning for Complex ProgramsTeaches a local T5 model (770M) to do exceptionally well on HotPotQA. Uses only 200 labeled answers. Uses no hand-written prompts, no calls to OpenAI, and no labels for retrieval or reasoning.AdvancedInformation ExtractionTackles extracting information from long articles (biomedical research papers). Combines in-context learning and retrieval to set SOTA on BioDEX. Contributed byKarel D’Oosterlinck.Other resources people find useful:DSPy talk at ScaleByTheBay Nov 2023.DSPy webinar with MLOps Learners, a bit longer with Q&A.Hands-on Overviews of DSPy by the community:DSPy Explained! by Connor Shorten,DSPy explained by code_your_own_aiInterviews:Weaviate Podcast in-person, and you can find 6-7 other remote podcasts on YouTube from a few different perspectives/audiences.Tracing in DSPywith Arize Phoenix:Tutorial for tracing your prompts and the steps of your DSPy programsB) GuidesIf you're new to DSPy, it's probably best to go in sequential order. You will probably refer to these guides frequently after that, e.g. to copy/paste snippets that you can edit for your own DSPy programs.Language ModelsSignaturesModulesDataMetricsOptimizers (formerly Teleprompters)DSPy AssertionsC) ExamplesThe DSPy team believes complexity has to be justified. We take this seriously: we never release a complex tutorial (above) or example (below)unless we can demonstrate empirically that this complexity has generally led to improved quality or cost.This kind of rule is rarely enforced by other frameworks or docs, but you can count on it in DSPy examples.There's a bunch of examples in theexamples/directory and in the top-level directory. We welcome contributions!You can find other examples tweeted by@lateinteractionon Twitter/X.Some other examples (not exhaustive, feel free to add more via PR):Applying DSPy AssertionsLong-form Answer Generation with Citations, by Arnav SinghviGenerating Answer Choices for Quiz Questions, by Arnav SinghviGenerating Tweets for QA, by Arnav SinghviCompiling LCEL runnables from LangChain in DSPyAI feedback, or writing LM-based metrics in DSPyDSPy Optimizers Benchmark on a bunch of different tasks, by Michael RyanIndian Languages NLI with gains due to compiling by Saiful HaqSophisticated Extreme Multi-Class Classification, IReRa, by Karel D’OosterlinckDSPy on BIG-Bench Hard Example, by Chris LevyUsing Ollama with DSPy for Mistral (quantized) by @jrknox1977Using DSPy, "The Unreasonable Effectiveness of Eccentric Automatic Prompts" (paper) by VMware's Rick Battle & Teja Gollapudi, and interview at TheRegisterThere are also recent cool examples atWeaviate's DSPy cookbookby Connor Shorten.See tutorial on YouTube.3) Syntax: You're in charge of the workflow—it's free-form Python code!DSPyhides tedious prompt engineering, but it cleanly exposes the important decisions you need to make:[1]what's your system design going to look like?[2]what are the important constraints on the behavior of your program?You express your system as free-form Pythonic modules.DSPywill tune the quality of your programin whatever wayyou use foundation models: you can code with loops,ifstatements, or exceptions, and useDSPymodules within any Python control flow you think works for your task.Suppose you want to build a simple retrieval-augmented generation (RAG) system for question answering. You can define your ownRAGprogram like this:classRAG(dspy.Module):def__init__(self,num_passages=3):super().__init__()self.retrieve=dspy.Retrieve(k=num_passages)self.generate_answer=dspy.ChainOfThought("context, question -> answer")defforward(self,question):context=self.retrieve(question).passagesanswer=self.generate_answer(context=context,question=question)returnanswerA program has two key methods, which you can edit to fit your needs.Your__init__methoddeclares the modules you will use. Here,RAGwill use the built-inRetrievefor retrieval andChainOfThoughtfor generating answers.DSPyoffers general-purpose modules that take the shape ofyour ownsub-tasks — and not pre-built functions for specific applications.Modules that use the LM, likeChainOfThought, require asignature. That is a declarative spec that tells the module what it's expected to do. In this example, we use the short-hand signature notationcontext, question -> answerto tellChainOfThoughtit will be given somecontextand aquestionand must produce ananswer. We will discuss more advancedsignaturesbelow.Yourforwardmethodexpresses any computation you want to do with your modules. In this case, we use the moduleself.retrieveto search for somecontextand then use the moduleself.generate_answer, which uses thecontextandquestionto generate theanswer!You can now either use thisRAGprogram inzero-shot mode. Orcompileit to obtain higher quality. Zero-shot usage is simple. Just define an instance of your program and then call it:rag=RAG()# zero-shot, uncompiled version of RAGrag("what is the capital of France?").answer# -> "Paris"The next section will discuss how to compile our simpleRAGprogram. When we compile it, theDSPy compilerwill annotatedemonstrationsof its steps: (1) retrieval, (2) using context, and (3) usingchain-of-thoughtto answer questions. From these demonstrations, theDSPy compilerwill make sure it produces an effective few-shot prompt that works well with your LM, retrieval model, and data. If you're working with small models, it'll finetune your model (instead of prompting) to do this task.If you later decide you need another step in your pipeline, just add another module and compile again. Maybe add a module that takes the chat history into account during search?4) Two Powerful Concepts: Signatures & TelepromptersNote:We will soon rename teleprompters to optimizers. This will not affect their functionality, but will simplify the terms used.To make it possible to compile any program you write,DSPyintroduces two simple concepts: Signatures and Teleprompters.4.a) Declaring the input/output behavior of LMs withdspy.SignatureWhen we assign tasks to LMs inDSPy, we specify the behavior we need as aSignature. A signature is a declarative specification of input/output behavior of aDSPy module.Instead of investing effort intohowto get your LM to do a sub-task, signatures enable you to informDSPywhatthe sub-task is. Later, theDSPy compilerwill figure out how to build a complex prompt for your large LM (or finetune your small LM) specifically for your signature, on your data, and within your pipeline.A signature consists of three simple elements:A minimal description of the sub-task the LM is supposed to solve.A description of one or more input fields (e.g., input question) that will we will give to the LM.A description of one or more output fields (e.g., the question's answer) that we will expect from the LM.We support two notations for expressing signatures. Theshort-hand signature notationis for quick development. You just provide your module (e.g.,dspy.ChainOfThought) with a string withinput_field_name_1, ... -> output_field_name_1, ...with the fields separated by commas.In theRAGclass earlier, we saw:self.generate_answer=dspy.ChainOfThought("context, question -> answer")In many cases, this barebones signature is sufficient. However, sometimes you need more control. In these cases, we can use the full notation to express a more fully-fledged signature below.classGenerateSearchQuery(dspy.Signature):"""Write a simple search query that will help answer a complex question."""context=dspy.InputField(desc="may contain relevant facts")question=dspy.InputField()query=dspy.OutputField()### inside your program's __init__ functionself.generate_answer=dspy.ChainOfThought(GenerateSearchQuery)You can optionally provide aprefixand/ordesckey for each input or output field to refine or constraint the behavior of modules using your signature. The description of the sub-task itself is specified as the docstring (i.e.,"""Write a simple...""").4.b) AskingDSPyto automatically optimize your program withdspy.teleprompt.*After defining theRAGprogram, we cancompileit. Compiling a program will update the parameters stored in each module. For large LMs, this is primarily in the form of creating and validating good demonstrations for inclusion in your prompt(s).Compiling depends on three things: a (potentially tiny) training set, a metric for validation, and your choice of teleprompter fromDSPy.Telepromptersare powerful optimizers (included inDSPy) that can learn to bootstrap and select effective prompts for the modules of any program. (The  "tele-" in the name means "at a distance", i.e., automatic prompting at a distance.)DSPytypically requires very minimal labeling. For example, ourRAGpipeline may work well with just a handful of examples that contain aquestionand its (human-annotated)answer. Your pipeline may involve multiple complex steps: our basicRAGexample includes a retrieved context, a chain of thought, and the answer. However, you only need labels for the initial question and the final answer.DSPywill bootstrap any intermediate labels needed to support your pipeline. If you change your pipeline in any way, the data bootstrapped will change accordingly!my_rag_trainset=[dspy.Example(question="Which award did Gary Zukav's first book receive?",answer="National Book Award"),...]Second, define your validation logic, which will express some constraints on the behavior of your program or individual modules. ForRAG, we might express a simple check like this:defvalidate_context_and_answer(example,pred,trace=None):# check the gold label and the predicted answer are the sameanswer_match=example.answer.lower()==pred.answer.lower()# check the predicted answer comes from one of the retrieved contextscontext_match=any((pred.answer.lower()inc)forcinpred.context)returnanswer_matchandcontext_matchDifferent teleprompters offer various tradeoffs in terms of how much they optimize cost versus quality, etc. ForRAG, we might use the simple teleprompter calledBootstrapFewShot. To do so, we instantiate the teleprompter itself with a validation functionmy_rag_validation_logicand then compile against some training setmy_rag_trainset.fromdspy.telepromptimportBootstrapFewShotteleprompter=BootstrapFewShot(metric=my_rag_validation_logic)compiled_rag=teleprompter.compile(RAG(),trainset=my_rag_trainset)If we now usecompiled_rag, it will invoke our LM with rich prompts with few-shot demonstrations of chain-of-thought retrieval-augmented question answering on our data.5) FAQ: Is DSPy right for me?TheDSPyphilosophy and abstraction differ significantly from other libraries and frameworks, so it's usually straightforward to decide whenDSPyis (or isn't) the right framework for your usecase.If you're a NLP/AI researcher (or a practitioner exploring new pipelines or new tasks), the answer is generally an invariableyes. If you're a practitioner doing other things, please read on.[5.a] DSPy vs. thin wrappers for prompts (OpenAI API, MiniChain, basic templating)In other words:Why can't I just write my prompts directly as string templates?Well, for extremely simple settings, thismightwork just fine. (If you're familiar with neural networks, this is like expressing a tiny two-layer NN as a Python for-loop. It kinda works.)However, when you need higher quality (or manageable cost), then you need to iteratively explore multi-stage decomposition, improved prompting, data bootstrapping, careful finetuning, retrieval augmentation, and/or using smaller (or cheaper, or local) models. The true expressive power of building with foundation models lies in the interactions between these pieces. But every time you change one piece, you likely break (or weaken) multiple other components.DSPycleanly abstracts away (andpowerfully optimizes) the parts of these interactions that are external to your actual system design. It lets you focus on designing the module-level interactions: thesame programexpressed in 10 or 20 lines ofDSPycan easily be compiled into multi-stage instructions forGPT-4, detailed prompts forLlama2-13b, or finetunes forT5-base.Oh, and you wouldn't need to maintain long, brittle, model-specific strings at the core of your project anymore.[5.b] DSPy vs. application development libraries like LangChain, LlamaIndexNote: If you use LangChain as a thin wrapper around your own prompt strings, refer to answer [5.a] instead.LangChain and LlamaIndex are popular libraries that target high-level application development with LMs. They offer manybatteries-included, pre-built application modules that plug in with your data or configuration. In practice, indeed, many usecases genuinelydon't needany special components. If you'd be happy to use someone's generic, off-the-shelf prompt for question answering over PDFs or standard text-to-SQL as long as it's easy to set up on your data, then you will probably find a very rich ecosystem in these libraries.Unlike these libraries,DSPydoesn't internally contain hand-crafted prompts that target specific applications you can build. Instead,DSPyintroduces a very small set of much more powerful and general-purpose modulesthat can learn to prompt (or finetune) your LM within your pipeline on your data.DSPyoffers a whole different degree of modularity: when you change your data, make tweaks to your program's control flow, or change your target LM, theDSPy compilercan map your program into a new set of prompts (or finetunes) that are optimized specifically for this pipeline. Because of this, you may find thatDSPyobtains the highest quality for your task, with the least effort, provided you're willing to implement (or extend) your own short program. In short,DSPyis for when you need a lightweight but automatically-optimizing programming model — not a library of predefined prompts and integrations.If you're familiar with neural networks:This is like the difference between PyTorch (i.e., representingDSPy) and HuggingFace Transformers (i.e., representing the higher-level libraries). If you simply want to use off-the-shelfBERT-base-uncasedorGPT2-largeor apply minimal finetuning to them, HF Transformers makes it very straightforward. If, however, you're looking to build your own architecture (or extend an existing one significantly), you have to quickly drop down into something much more modular like PyTorch. Luckily, HF Transformersisimplemented in backends like PyTorch. We are similarly excited about high-level wrapper aroundDSPyfor common applications. If this is implemented usingDSPy, your high-level application can also adapt significantly to your data in a way that static prompt chains won't. Pleaseopen an issueif this is something you want to help with.[5.c] DSPy vs. generation control libraries like Guidance, LMQL, RELM, OutlinesGuidance, LMQL, RELM, and Outlines are all exciting new libraries for controlling the individual completions of LMs, e.g., if you want to enforce JSON output schema or constrain sampling to a particular regular expression.This is very useful in many settings, but it's generally focused on low-level, structured control of a single LM call. It doesn't help ensure the JSON (or structured output) you get is going to be correct or useful for your task.In contrast,DSPyautomatically optimizes the prompts in your programs to align them with various task needs, which may also include producing valid structured ouputs. That said, we are considering allowingSignaturesinDSPyto express regex-like constraints that are implemented by these libraries.TestingTo run the tests, you need to first clone the repository.Then install the package through poetry:
Note - You may need topoetryinstall--withtestThen run the all tests, or a specific test suite, with the following commands:poetryrunpytest
poetryrunpytesttests/PATH_TO_TEST_SUITEContribution QuickstartSeeCONTRIBUTING.mdfor a quickstart guide to contributing to DSPy.Contributors & AcknowledgementsDSPyis led byOmar Khattabat Stanford NLP withChris PottsandMatei Zaharia.Key contributors and team members includeArnav Singhvi,Krista Opsahl-Ong,Michael Ryan,Karel D'Oosterlinck,Shangyin Tan,Manish Shetty,Paridhi Maheshwari,Keshav Santhanam,Sri Vardhamanan,Eric Zhang,Hanna Moazam,Thomas Joshi,Saiful Haq,Ashutosh Sharma, andHerumb Shandilya.DSPyincludes important contributions fromRick BattleandIgor Kotenkov. It reflects discussions withPeter Zhong,Haoze He,Lisa Li,David Hall,Ashwin Paranjape,Heather Miller,Chris Manning,Percy Liang, and many others.TheDSPylogo is designed byChuyi Zhang.📜 Citation & Reading MoreTo stay up to date or learn more, follow@lateinteractionon Twitter.If you use DSPy or DSP in a research paper, please cite our work as follows:@article{khattab2023dspy,
  title={DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines},
  author={Khattab, Omar and Singhvi, Arnav and Maheshwari, Paridhi and Zhang, Zhiyuan and Santhanam, Keshav and Vardhamanan, Sri and Haq, Saiful and Sharma, Ashutosh and Joshi, Thomas T. and Moazam, Hanna and Miller, Heather and Zaharia, Matei and Potts, Christopher},
  journal={arXiv preprint arXiv:2310.03714},
  year={2023}
}
@article{khattab2022demonstrate,
  title={Demonstrate-Search-Predict: Composing Retrieval and Language Models for Knowledge-Intensive {NLP}},
  author={Khattab, Omar and Santhanam, Keshav and Li, Xiang Lisa and Hall, David and Liang, Percy and Potts, Christopher and Zaharia, Matei},
  journal={arXiv preprint arXiv:2212.14024},
  year={2022}
}You can also read more about the evolution of the framework from Demonstrate-Search-Predict to DSPy:DSPy Assertions: Computational Constraints for Self-Refining Language Model Pipelines(Academic Paper, Dec 2023)DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines(Academic Paper, Oct 2023)Releasing DSPy, the latest iteration of the framework(Twitter Thread, Aug 2023)Releasing the DSP Compiler (v0.1)(Twitter Thread, Feb 2023)Introducing DSP(Twitter Thread, Jan 2023)Demonstrate-Search-Predict: Composing retrieval and language models for knowledge-intensive NLP(Academic Paper, Dec 2022)Note: If you're looking for Demonstrate-Search-Predict (DSP), which is the previous version of DSPy, you can find it on thev1branch of this repo.