DSPy: The framework for programming—not prompting—language models
Python
add SGLang and Ollama installation instructions (#1683)
arnavsinghvi119902a0c325b1
diff --git a/docs/docs/building-blocks/1-language_models.md b/docs/docs/building-blocks/1-language_models.mdindex fad859b41..19560b851 100644--- a/docs/docs/building-blocks/1-language_models.md+++ b/docs/docs/building-blocks/1-language_models.md@@ -6,7 +6,7 @@ sidebar_position: 2The most powerful features in DSPy revolve around algorithmically optimizing the prompts (or weights) of LMs, especially when you're building programs that use the LMs within a pipeline.-Let's first make sure you can set up your language model. DSPy support clients for many remote and local LMs.+Let's first make sure you can set up your language model. DSPy supports clients for many remote and local LMs.## Using `dspy.LM`@@ -89,7 +89,7 @@ Instead of changing the default LM, you can just change it inside a block of codresponse = qa(question="How many floors are in the castle David Gregory inherited?")print('GPT-3.5:', response.answer)-gpt4_turbo = dspy.OpenAI(model='gpt-4-1106-preview', max_tokens=300)+gpt4_turbo = dspy.LM(model='gpt-4-1106-preview', max_tokens=300)# Run with GPT-4 insteadwith dspy.context(lm=gpt4_turbo):@@ -116,14 +116,90 @@ By default LMs in DSPy are cached. If you repeat the same call, you will get theAny OpenAI-compatible endpoint is easy to set up with an `openai/` prefix as well. This works great for open LMs from HuggingFace hosted locally with SGLang, VLLM, or HF Text-Generation-Inference.-```python-sglang_port = 7501-sglang_url = f"http://localhost:{sglang_port}/v1"-sglang_llama = dspy.LM("openai/meta-llama/Meta-Llama-3-8B-Instruct", api_base=sglang_url)+#### Setting up SGLang-# You could also use text mode, in which the prompts are *not* formatted as messages.-sglang_llama_text = dspy.LM("openai/meta-llama/Meta-Llama-3-8B-Instruct", api_base=sglang_url, model_type='text')-```+1. **Install SGLang (adapted from SGLang [documentation](https://sglang.readthedocs.io/en/latest/install.html)):**++ ```bash+ pip install "sglang[all]"+ pip install flashinfer -i https://flashinfer.ai/whl/cu121/torch2.4/+ ```++2. **Login to HuggingFace:**++ ```bash+ huggingface-cli login+ ```++ You may need to set your HuggingFace API token to access gated models:++ ```bash+ export HUGGINGFACEHUB_API_TOKEN=your_api_token+ ```++ Also, ensure your cache directory is accessible:++ ```bash+ export TRANSFORMERS_CACHE=/path/to/your/cache+ ```++3. **Launch the SGLang server:**++ Replace `meta-llama/Meta-Llama-3-8B-Instruct` with the model you wish to launch.++ ```bash+ CUDA_VISIBLE_DEVICES=0 python -m sglang.launch_server \+ --model-path meta-llama/Meta-Llama-3-8B-Instruct \+ --port 7501 \+ ```++4. **Connect to the SGLang server via `dspy.LM`:**++ ```python+ sglang_port = 7501+ sglang_url = f"http://localhost:{sglang_port}/v1"+ sglang_llama = dspy.LM("openai/meta-llama/Meta-Llama-3-8B-Instruct", api_base=sglang_url)++ # You could also use text mode, in which the prompts are *not* formatted as messages.+ sglang_llama_text = dspy.LM("openai/meta-llama/Meta-Llama-3-8B-Instruct", api_base=sglang_url, model_type='text')+ ```++ For further details on customizing the SGLang configuration, please refer to the [SGLang documentation](https://sglang.readthedocs.io/en/latest/backend.html#additional-server-arguments).++#+Additionally, you can also host models locally through Ollama.++#### Setting Up Ollama (adapted from Ollama [documentation](https://github.com/ollama/ollama))+++1. **Install Ollama:**+++ ```bash+ curl -fsSL https://ollama.ai/install.sh | sh+ ```++2. **Launch the Ollama server:**++ Replace `llama3.2:1b` with the model you wish to launch.++ ```bash+ ollama run llama3.2:1b+ ```++ If the model isn't in GGUF format, you'll need to convert it first, following corresponding Ollama [instructions](https://github.com/ollama/ollama?tab=readme-ov-file#import-from-gguf).++ If you wish to download the model manually and load it into Ollama, please follow the corresponding Ollama import [instructions](https://github.com/ollama/ollama/blob/main/docs/import.md).++3. **Connect to the Ollama server via `dspy.LM`:**++ ```python+ ollama_port = 11434+ ollama_url = f"http://localhost:{ollama_port}"+ ollama_llm = dspy.LM(model="ollama/llama3.2:1b", api_base=ollama_url)+ ```++ For further details on customizing the Ollama configuration, please refer to the LiteLLM [Ollama documentation](https://docs.litellm.ai/docs/providers/ollama).### Inspecting output and usage metadata@@ -142,7 +218,7 @@ dict_keys(['prompt', 'messages', 'kwargs', 'response', 'outputs', 'usage', 'cost## Creating Custom LM Class-Creating custom LM class is quite straightforward in DSPy. You can inherit from the `dspy.LM` class or create a new class with a similar interface. You'll need to implement/override the three methods:+Creating a custom LM class is quite straightforward in DSPy. You can inherit from the `dspy.LM` class or create a new class with a similar interface. You'll need to implement/override these three methods:* `__init__`: Initialize the LM with the given `model` and other keyword arguments.* `__call__`: Call the LM with the given input prompt and return a list of string outputs.@@ -226,16 +302,16 @@ Prediction(### Defining Custom Adapters!!! warning- Adapters are low level feature that change the way input and output is handled by DSPy, it's not recommended to build and use custom Adapters unless you are sure of what you are doing.+ Adapters are low-level features that change the way input and output is handled by DSPy, it's not recommended to build and use custom Adapters unless you are sure of what you are doing.Adapters are a powerful feature in DSPy, allowing you to define custom behavior for your Signatures.For example, you could define an Adapter that automatically converts the input to uppercase before passing it to the LM. This is a simple example, but it shows how you can create custom Adapters that modify the inputs or outputs of your LMs.-You'll need to inherit the base `Adapter` class and implement two method to create a usable custom Adapter:+You'll need to inherit the base `Adapter` class and implement two methods to create a usable custom Adapter:-* `format`: This method is responsible for formatting the input for the LM. This method takes `signature`, `demos` and `inputs` as input parameters. Demos are in-context examples set manually or through example. The output of this function can be a string prompt supported by completions function, list of message dictionary or any format that the LM you are using supports.+* `format`: This method is responsible for formatting the input for the LM. This method takes `signature`, `demos` and `inputs` as input parameters. Demos are in-context examples set manually or through example. The output of this function can be a string prompt supported by completions function, a list of message dictionaries or any format that the LM you are using supports.* `parse`: This method is responsible for parsing the output of the LM. This method takes `signature`, `completions` and `_parse_values` as input parameters.@@ -277,7 +353,7 @@ class UpperCaseAdapter(Adapter):return output_dict```-Let's understand the `UpperCaseAdapter` class. The `format` method takes `signature`, `demos`, and `inputs` as input parameters. It then constructs a prompt by combining the system prompt, format instruction prompt, and input fields. It then converts the prompt to uppercase.+Let's understand the `UpperCaseAdapter` class. The `format` method takes `signature`, `demos`, and `inputs` as input parameters. It constructs a prompt by combining the system prompt, format instruction prompt, and input fields, and then converts the prompt to uppercase.The `parse` method takes `signature`, `completions`, and `_parse_values` as input parameters. It then extracts the output fields from the completions and returns them as a dictionary.diff --git a/docs/docs/building-blocks/2-signatures.md b/docs/docs/building-blocks/2-signatures.mdindex c9721d0ae..c2355cb6f 100644--- a/docs/docs/building-blocks/2-signatures.md+++ b/docs/docs/building-blocks/2-signatures.md@@ -124,7 +124,7 @@ Prediction()```-**Tip:** There's nothing wrong with specifying your requests to the LM more clearly. Class-based Signatures help you with that. However, don't prematurely tune the keywords of the your signature by hand. The DSPy optimizers will likely do a better job (and will transfer better across LMs).+**Tip:** There's nothing wrong with specifying your requests to the LM more clearly. Class-based Signatures help you with that. However, don't prematurely tune the keywords of your signature by hand. The DSPy optimizers will likely do a better job (and will transfer better across LMs).### Example D: A metric that evaluates faithfulness to citationsdiff --git a/docs/docs/building-blocks/4-data.md b/docs/docs/building-blocks/4-data.mdindex b4b873625..577ce33ad 100644--- a/docs/docs/building-blocks/4-data.md+++ b/docs/docs/building-blocks/4-data.md@@ -89,7 +89,7 @@ Example object with Non-Input fields only: Example({'summary': 'This is a summar## Loading Dataset from sources-One of the most convinient way to import dataset in DSPy is by using `DataLoader`. The first step is to declare an object, this object can then be used to call utilities to load datasets in different formats:+One of the most convenient way to import datasets in DSPy is by using `DataLoader`. The first step is to declare an object, this object can then be used to call utilities to load datasets in different formats:```pythonfrom dspy.datasets import DataLoader@@ -127,19 +127,18 @@ pandas_dataset = dl.from_pandas()```-These are some supported formats that `DataLoader` supports to load from file directly, in backend most of these methods are leveraging `load_dataset` method from `datasets` library to load these formats. But when working with text data you often use HuggingFace datasets, in order to import HF datasets in list of `Example` format we can use `from_huggingface` method:+These are some formats that `DataLoader` supports to load from file directly. In the backend, most of these methods leverage the `load_dataset` method from `datasets` library to load these formats. But when working with text data you often use HuggingFace datasets, in order to import HF datasets in list of `Example` format we can use `from_huggingface` method:```pythonblog_alpaca = dl.from_huggingface(- "intertwine-expel/expel-blog"+ "intertwine-expel/expel-blog",input_keys=("title",))```-You can access the dataset of the splits by calling key of the corresponding split:+You can access the splits of the dataset by accessing the corresponding key:```python-fromtrain_split = blog_alpaca['train']# Since this is the only split in the dataset we can split this into@@ -149,4 +148,4 @@ testset = train_split[:75]trainset = train_split[75:]```-The way you load a huggingface dataset using `load_dataset` is exactly how you load data it via `from_huggingface` as well. This includes passing specific splits, subsplits, read instructions, etc. For code snippets you can refer to the [cheatsheet snippets](/cheatsheet/#dspy-dataloaders) for loading from HF.\ No newline at end of file+The way you load a HuggingFace dataset using `load_dataset` is exactly how you load data it via `from_huggingface` as well. This includes passing specific splits, subsplits, read instructions, etc. For code snippets, you can refer to the [cheatsheet snippets](/cheatsheet/#dspy-dataloaders) for loading from HF.\ No newline at end of filediff --git a/docs/docs/building-blocks/5-metrics.md b/docs/docs/building-blocks/5-metrics.mdindex f41718738..377e7d78e 100644--- a/docs/docs/building-blocks/5-metrics.md+++ b/docs/docs/building-blocks/5-metrics.md@@ -9,7 +9,7 @@ DSPy is a machine learning framework, so you must think about your **automatic m## What is a metric and how do I define a metric for my task?-A metric is just a function that will take examples from your data and take the output of your system, and return a score that quantifies how good the output is. What makes outputs from your system good or bad?+A metric is just a function that will take examples from your data and the output of your system and return a score that quantifies how good the output is. What makes outputs from your system good or bad?For simple tasks, this could be just "accuracy" or "exact match" or "F1 score". This may be the case for simple classification or short-form QA tasks.@@ -52,7 +52,7 @@ def validate_context_and_answer(example, pred, trace=None):return answer_match and context_match```-Defining a good metric is an iterative process, so doing some initial evaluations and looking at your data and your outputs are key.+Defining a good metric is an iterative process, so doing some initial evaluations and looking at your data and outputs is key.## Evaluationdiff --git a/docs/docs/building-blocks/6-optimizers.md b/docs/docs/building-blocks/6-optimizers.mdindex 03985cbd2..14f0036b6 100644--- a/docs/docs/building-blocks/6-optimizers.md+++ b/docs/docs/building-blocks/6-optimizers.md@@ -116,7 +116,7 @@ optimized_program.save(YOUR_SAVE_PATH)The resulting file is in plain-text JSON format. It contains all the parameters and steps in the source program. You can always read it and see what the optimizer generated.-You can add `save_verbose` to additionally save the list of fields with the keys, `name`, `field_type`, `description`, and `prefix` with: `optimized_program.save(YOUR_SAVE_PATH, save_field_meta=True).+You can add `save_field_meta` to additionally save the list of fields with the keys, `name`, `field_type`, `description`, and `prefix` with: `optimized_program.save(YOUR_SAVE_PATH, save_field_meta=True).### Loading a programdiff --git a/docs/docs/building-blocks/7-assertions.md b/docs/docs/building-blocks/7-assertions.mdindex 4b0297f6b..bfd207315 100644--- a/docs/docs/building-blocks/7-assertions.md+++ b/docs/docs/building-blocks/7-assertions.md@@ -25,7 +25,7 @@ We introduce two primary constructs within DSPy Assertions:Specifically, when a constraint is not met:-- Backtracking Mechanism: An under-the-hood backtracking is initiated, offering the model a chance to self-refine and proceed, which is done through+- Backtracking Mechanism: An under-the-hood backtracking is initiated, offering the model a chance to self-refine and proceed, which is done through signature modification.- Dynamic Signature Modification: internally modifying your DSPy program’s Signature by adding the following fields:- Past Output: your model's past output that did not pass the validation_fn- Instruction: your user-defined feedback message on what went wrong and what possibly to fix@@ -34,8 +34,8 @@ If the error continues past the `max_backtracking_attempts`, then `dspy.Assert`- **dspy.Suggest vs. dspy.Assert**: `dspy.Suggest` on the other hand offers a softer approach. It maintains the same retry backtracking as `dspy.Assert` but instead serves as a gentle nudger. If the model outputs cannot pass the model constraints after the `max_backtracking_attempts`, `dspy.Suggest` will log the persistent failure and continue execution of the program on the rest of the data. This ensures the LM pipeline works in a "best-effort" manner without halting execution.-- **`dspy.Suggest`** are best utilized as "helpers" during the evaluation phase, offering guidance and potential corrections without halting the pipeline.-- **`dspy.Assert`** are recommended during the development stage as "checkers" to ensure the LM behaves as expected, providing a robust mechanism for identifying and addressing errors early in the development cycle.+- **`dspy.Suggest`** statements are best utilized as "helpers" during the evaluation phase, offering guidance and potential corrections without halting the pipeline.+- **`dspy.Assert`** statements are recommended during the development stage as "checkers" to ensure the LM behaves as expected, providing a robust mechanism for identifying and addressing errors early in the development cycle.## Use Case: Including Assertions in DSPy Programsdiff --git a/docs/docs/quick-start/getting-started-01.md b/docs/docs/quick-start/getting-started-01.mdindex 66526a369..b276210ed 100644--- a/docs/docs/quick-start/getting-started-01.md+++ b/docs/docs/quick-start/getting-started-01.md@@ -149,7 +149,7 @@ len(trainset), len(valset), len(devset), len(testset)## Evaluation in DSPy.-What kind of metric can suit our question-answering task? There are many choices, but since the answer are long, we may ask: How well does the system response _cover_ all key facts in the gold response? And the other way around, how well is the system response _not saying things_ that aren't in the gold response?+What kind of metric can suit our question-answering task? There are many choices, but since the answers are long, we may ask: How well does the system response _cover_ all key facts in the gold response? And the other way around, how well is the system response _not saying things_ that aren't in the gold response?That metric is essentially a **semantic F1**, so let's load a `SemanticF1` metric from DSPy. This metric is actually implemented as a [very simple DSPy module](https://github.com/stanfordnlp/dspy/blob/77c2e1cceba427c7f91edb2ed5653276fb0c6de7/dspy/evaluate/auto_evaluation.py#L21) using whatever LM we're working with.diff --git a/docs/docs/quick-start/getting-started-02.md b/docs/docs/quick-start/getting-started-02.mdindex 4c1acb672..a292fee83 100644--- a/docs/docs/quick-start/getting-started-02.md+++ b/docs/docs/quick-start/getting-started-02.md@@ -12,7 +12,7 @@ Install the latest DSPy via `pip install -U dspy` and follow along. You may alsoIn [Getting Started I: Basic Question Answering](/quick-start/getting-started-01), we've set up the DSPy LM, loaded some data, and loaded a metric for evaluation.-First, let's download the corpus data that we will use for RAG search. The next cell will seek to download 4 GBs, so it may take a few minutes. A future version of this notebook will come with a cache that allows you to skip downloads and the pytorch installation.+First, let's download the corpus data that we will use for RAG search. The next cell will seek to download 4 GBs, so it may take a few minutes. A future version of this notebook will come with a cache that allows you to skip downloads and the PyTorch installation.```pythonimport os@@ -160,7 +160,7 @@ See this [gist](https://gist.github.com/okhat/d6606e480a94c88180441617342699eb).The prompt optimization process here is pretty systematic, you can learn about it for example in this paper. Importantly, it's not a magic button. It's very possible that it can overfit your training set for instance and not generalize well to a held-out set, making it essential that we iteratively validate our programs.-Let's check on example here, asking the same question to the baseline `rag = RAG()` program, which was not optimized, and to the `optimized_rag = MIPROv2(..)(..)` program, after prompt optimization.+Let's check on an example here, asking the same question to the baseline `rag = RAG()` program, which was not optimized, and to the `optimized_rag = MIPROv2(..)(..)` program, after prompt optimization.```python@@ -263,8 +263,8 @@ In general, you have the following tools:3. Scale inference time compute using DSPy Optimizers, e.g. this [notebook](https://github.com/stanfordnlp/dspy/blob/main/examples/agents/multi_agent.ipynb).4. Cut cost by distilling to a smaller LM, via prompt or weight optimization, e.g. [this notebook](https://github.com/stanfordnlp/dspy/blob/main/examples/nli/scone/scone.ipynb) or [this notebook](https://colab.research.google.com/github/stanfordnlp/dspy/blob/main/examples/qa/hotpot/multihop_finetune.ipynb).-How do you do decide which ones to proceed with first?+How do you decide which ones to proceed with first?-The first step is look at your system outputs, which will allow you to identify the sources of lower performance if any. While doing all of this, make sure you continue to refine your metric, e.g. by optimizing against your judgments, and to collect more (or more realistic) data, e.g. from related domains or from putting a demo of your system in front of users.+The first step is to look at your system outputs, which will allow you to identify the sources of lower performance if any. While doing all of this, make sure you continue to refine your metric, e.g. by optimizing against your judgments, and to collect more (or more realistic) data, e.g. from related domains or from putting a demo of your system in front of users.Learn more about the [development cycle](/building-blocks/solving_your_task) in DSPy.