Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Update docs for LMs and migrations

Herumb Shandilyab077203c3e9e
diff --git a/docs/README.md b/docs/README.md
index 7c4caca54..54c70c173 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -2,6 +2,37 @@
This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator.
+## Building docs locally
+
+To build and test the documentation locally:
+
+1. Navigate to the `docs` directory:
+ ```bash
+ cd docs
+ ```
+
+2. Install the necessary dependencies:
+ ```bash
+ npm install
+ ```
+
+3. Run the build command:
+ ```bash
+ npm run build
+ ```
+
+This will generate a static build of the documentation site in the `build` directory. You can then serve this directory to view the site locally. If you see the build failing make sure to fix it before pushing.
+
+## Continuous Integration (CI) Build Checks
+
+We have automated build checks set up in our CI pipeline to ensure the documentation builds successfully before merging changes. These checks:
+
+1. Run the `npm run build` command
+2. Verify that the build completes without errors
+3. Help catch potential issues early in the development process
+
+If the CI build check fails, please review your changes and ensure the documentation builds correctly locally before pushing updates.
+
## Contributing to the `docs` Folder
This guide is for contributors looking to make changes to the documentation in the `dspy/docs` folder.
@@ -15,9 +46,4 @@ git subtree pull --prefix=docs https://github.com/krypticmouse/dspy-docs master
2. **Push your new changes on a new branch**: Feel free to add or edit existing documentation and open a PR for your changes. Once your PR is reviewed and approved, the changes will be ready to merge into main.
-3. **Updating the website**: Once your changes are merged to main, they need to be pushed to the subtree repository that hosts the live documentation site. This step will eventually be done automatically, but for now, please run the following command to push the updated `docs` content to the website subtree repository:
-
-```bash
-#Ensure you are in the top-level dspy/ folder
-git subtree push --prefix=docs https://github.com/krypticmouse/dspy-docs master
-```
+3. **Updating the website**: Once your changes are merged to main, the changes would be reflected on live websites usually in 5-15 mins.
\ No newline at end of file
diff --git a/docs/docs/building-blocks/1-language_models.md b/docs/docs/building-blocks/1-language_models.md
index c8d24209e..8f5cf21d0 100644
--- a/docs/docs/building-blocks/1-language_models.md
+++ b/docs/docs/building-blocks/1-language_models.md
@@ -8,33 +8,56 @@ The most powerful features in DSPy revolve around algorithmically optimizing the
Let's first make sure you can set up your language model. DSPy support clients for many remote and local LMs.
-## Setting up the LM client.
+## Using `dspy.LM`
-You can just call the constructor that connects to the LM. Then, use `dspy.configure` to declare this as the default LM.
+:::warning
+Earlier versions of DSPy involved tons of clients for different LM providers, e.g. `dspy.OpenAI`, `dspy.GoogleVertexAI`, and `dspy.HFClientTGI`, etc. These are now deprecated and will be removed in DSPy 2.6.
+
+Instead, use `dspy.LM` to access any LM endpoint for local and remote models. This relies on [LiteLLM](https://github.com/BerriAI/litellm) to translate the different client APIs into an OpenAI-compatible interface.
+
+Any [provider supported in LiteLLM](https://docs.litellm.ai/docs/providers) should work with `dspy.LM`.
+:::
+
+### Setting up the LM client
+
+In DSPy 2.5, we use the `dspy.LM` class to set up language models. This replaces the previous client-specific classes. Then, use `dspy.configure` to declare this as the default LM.
For example, to use OpenAI language models, you can do it as follows.
```python
-gpt3_turbo = dspy.OpenAI(model='gpt-3.5-turbo-1106', max_tokens=300)
-dspy.configure(lm=gpt3_turbo)
+lm = dspy.LM('openai/gpt-4o-mini')
+dspy.configure(lm=lm)
```
-## Directly calling the LM.
+### Directly calling the LM
You can simply call the LM with a string to give it a raw prompt, i.e. a string.
```python
-gpt3_turbo("hello! this is a raw prompt to GPT-3.5")
+lm("hello! this is a raw prompt to GPT-4o-mini")
+```
+
+**Output:**
+```text
+["Hello! It looks like you're trying to interact with a model. How can I assist you today?"]
+```
+
+For chat LMs, you can pass a list of messages.
+
+```python
+lm(messages=[{"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "What is 2+2?"}])
```
**Output:**
```text
-['Hello! How can I assist you today?']
+['2 + 2 equals 4.']
```
This is almost never the recommended way to interact with LMs in DSPy, but it is allowed.
-## Using the LM with DSPy signatures.
+
+### Using the LM with DSPy signatures
You can also use the LM via DSPy [`signature` (input/output spec)](https://dspy-docs.vercel.app/docs/building-blocks/signatures) and [`modules`](https://dspy-docs.vercel.app/docs/building-blocks/modules), which we discuss in more depth in the remaining guides.
@@ -51,13 +74,15 @@ print(response.answer)
The castle David Gregory inherited has 7 floors.
```
-## Using multiple LMs at once.
+### Using multiple LMs at once.
The default LM above is GPT-3.5, `gpt3_turbo`. What if I want to run a piece of code with, say, GPT-4 or LLama-2?
Instead of changing the default LM, you can just change it inside a block of code.
-**Tip:** Using `dspy.configure` and `dspy.context` is thread-safe!
+:::tip
+Using `dspy.configure` and `dspy.context` is thread-safe!
+:::
```python
# Run with the default LM configured above, i.e. GPT-3.5
@@ -77,105 +102,58 @@ GPT-3.5: The castle David Gregory inherited has 7 floors.
GPT-4-turbo: The number of floors in the castle David Gregory inherited cannot be determined with the information provided.
```
-## Tips and Tricks.
-
-In DSPy, all LM calls are cached. If you repeat the same call, you will
-get the same outputs. (If you change the inputs or configurations, you
-will get new outputs.)
+### Configuring LM attributes
-To generate 5 outputs, you can use `n=5` in the module constructor, or
-pass `config=dict(n=5)` when invoking the module.
+For any LM, you can configure any of the following attributes at initialization or per call.
```python
-qa = dspy.ChainOfThought('question -> answer', n=5)
-
-response = qa(question="How many floors are in the castle David Gregory inherited?")
-response.completions.answer
-```
-**Output:**
-```text
-["The specific number of floors in David Gregory's inherited castle is not provided here, so further research would be needed to determine the answer.",
- 'The castle David Gregory inherited has 4 floors.',
- 'The castle David Gregory inherited has 5 floors.',
- 'David Gregory inherited 10 floors in the castle.',
- 'The castle David Gregory inherited has 5 floors.']
+gpt_4o_mini = dspy.LM('openai/gpt-4o-mini', temperature=0.9, max_tokens=3000, stop=None, cache=False)
```
-If you just call `qa(...)` in a loop with the same input, it will always
-return the same value! That\'s by design.
+By default LMs in DSPy are cached. If you repeat the same call, you will get the same outputs. But you can turn of caching by setting `cache=False` while declaring `dspy.LM` object.
-To loop and generate one output at a time with the same input, bypass
-the cache by making sure each request is (slightly) unique, as below.
+### Using locally hosted LMs
-```python
-for idx in range(5):
- response = qa(question="How many floors are in the castle David Gregory inherited?", config=dict(temperature=0.7+0.0001*idx))
- print(f'{idx+1}.', response.answer)
-```
-**Output:**
-```text
-1. The specific number of floors in David Gregory's inherited castle is not provided here, so further research would be needed to determine the answer.
-2. It is not possible to determine the exact number of floors in the castle David Gregory inherited without specific information about the castle's layout and history.
-3. The castle David Gregory inherited has 5 floors.
-4. We need more information to determine the number of floors in the castle David Gregory inherited.
-5. The castle David Gregory inherited has a total of 6 floors.
-```
-
-## Remote LMs.
-
-These models are managed services. You just need to sign up and obtain an API key. Calling any of the remote LMs below assumes authentication and mirrors the following format for setting up the LM:
+Any 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
-lm = dspy.{provider_listed_below}(model="your model", model_request_kwargs="...")
-```
-
-1. `dspy.OpenAI` for GPT-3.5 and GPT-4.
-
-2. `dspy.Cohere`
-
-3. `dspy.Anyscale` for hosted Llama2 models.
+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)
-4. `dspy.Together` for hosted various open source models.
-
-5. `dspy.PremAI` for hosted best open source and closed source models.
-
-6. `dspy.Claude` for hosted Claude models.
-
-7. `dspy.AWSAnthropic` for hosted Claude models and `dspy.AWSMeta` for hosted Llama3 models.
-
-### Local LMs.
+# 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')
+```
-You need to host these models on your own GPU(s). Below, we include pointers for how to do that.
+### Inspecting output and usage metadata
-1. `dspy.HFClientTGI`: for HuggingFace models through the Text Generation Inference (TGI) system. [Tutorial: How do I install and launch the TGI server?](https://dspy-docs.vercel.app/docs/deep-dive/language_model_clients/local_models/HFClientTGI)
+Every LM object maintains the history of its interactions, including inputs, outputs, token usage (and $$$ cost), and metadata.
```python
-tgi_mistral = dspy.HFClientTGI(model="mistralai/Mistral-7B-Instruct-v0.2", port=8080, url="http://localhost")
-```
+len(lm.history) # e.g., 3 calls to the LM
-2. `dspy.HFClientVLLM`: for HuggingFace models through vLLM. [Tutorial: How do I install and launch the vLLM server?](https://dspy-docs.vercel.app/docs/deep-dive/language_model_clients/local_models/HFClientVLLM)
-
-```python
-vllm_mistral = dspy.HFClientVLLM(model="mistralai/Mistral-7B-Instruct-v0.2", port=8080, url="http://localhost")
+lm.history[-1].keys() # access the last call to the LM, with all metadata
```
-3. `dspy.HFModel` (experimental) [Tutorial: How do I initialize models using HFModel](https://dspy-docs.vercel.app/api/local_language_model_clients/HFModel)
-
-```python
-mistral = dspy.HFModel(model = 'mistralai/Mistral-7B-Instruct-v0.2')
+**Output:**
+```text
+dict_keys(['prompt', 'messages', 'kwargs', 'response', 'outputs', 'usage', 'cost'])
```
-4. `dspy.Ollama` (experimental) for open source models through [Ollama](https://ollama.com). [Tutorial: How do I install and use Ollama on a local computer?](https://dspy-docs.vercel.app/api/local_language_model_clients/Ollama)\n",
+## Creating Custom LM Class
-```python
-ollama_mistral = dspy.OllamaLocal(model='mistral')
-```
+## Structured LM output with Adapters
+
+Prompt optimizers in DSPy generate and tune the _instructions_ or the _examples_ in the prompts corresponding to your Signatures. DSPy 2.5 introduces **Adapters** as a layer between Signatures and LMs, responsible for formatting these pieces (Signature I/O fields, instructions, and examples) as well as generating and parsing the outputs.
-5. `dspy.ChatModuleClient` (experimental): [How do I install and use MLC?](https://dspy-docs.vercel.app/api/local_language_model_clients/MLC)
+In DSPy 2.5, the default Adapters are now more natively aware of chat LMs and are responsible for enforcing types, building on earlier experimental features from `TypedPredictor` and `configure(experimental=True)`. In our experience, this change tends to deliver more consistent pre-optimization quality from various LMs, especially for sophisticated Signatures.
```python
-model = 'dist/prebuilt/mlc-chat-Llama-2-7b-chat-hf-q4f16_1'
-model_path = 'dist/prebuilt/lib/Llama-2-7b-chat-hf-q4f16_1-cuda.so'
+lm = dspy.LM('openai/gpt-4o-mini')
+dspy.configure(lm=lm, experimental=True)
+
+fact_checking = dspy.ChainOfThought('claims -> verdicts')
+fact_checking(claims=["Python was released in 1991.", "Python is a compiled language."])
+```
-llama = dspy.ChatModuleClient(model=model, model_path=model_path)
-```
\ No newline at end of file
+## Defining Custom Adapters
\ No newline at end of file
diff --git a/docs/docs/building-blocks/4-data.md b/docs/docs/building-blocks/4-data.md
index dedf19d56..e922725db 100644
--- a/docs/docs/building-blocks/4-data.md
+++ b/docs/docs/building-blocks/4-data.md
@@ -86,3 +86,67 @@ print("Example object with Non-Input fields only:", non_input_key_only)
Example object with Input fields only: Example({'article': 'This is an article.'}) (input_keys=None)
Example object with Non-Input fields only: Example({'summary': 'This is a summary.'}) (input_keys=None)
```
+
+## 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:
+
+```python
+from dspy.datasets import DataLoader
+
+dl = DataLoader()
+```
+
+For most dataset formats, it's quite straightforward you pass the file path to the corresponding method of the format and you'll get the list of `Example` for the dataset in return:
+
+```python
+import pandas as pd
+
+csv_dataset = dl.from_csv(
+ "sample_dataset.csv",
+ fields=("instruction", "context", "response"),
+ input_keys=("instruction", "context")
+)
+
+json_dataset = dl.from_json(
+ "sample_dataset.json",
+ fields=("instruction", "context", "response"),
+ input_keys=("instruction", "context")
+)
+
+parquet_dataset = dl.from_parquet(
+ "sample_dataset.parquet",
+ fields=("instruction", "context", "response"),
+ input_keys=("instruction", "context")
+)
+
+pandas_dataset = dl.from_pandas(
+ pd.read_csv("sample_dataset.csv"), # DataFrame
+ fields=("instruction", "context", "response"),
+ input_keys=("instruction", "context")
+)
+```
+
+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:
+
+```python
+blog_alpaca = dl.from_huggingface(
+ "intertwine-expel/expel-blog"
+ input_keys=("title",)
+)
+```
+
+You can access the dataset of the splits by calling key of the corresponding split:
+
+```python
+from
+train_split = blog_alpaca['train']
+
+# Since this is the only split in the dataset we can split this into
+# train and test split ourselves by slicing or sampling 75 rows from the train
+# split for testing.
+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](/docs/cheatsheet.md#dspy-dataloaders) for loading from HF.
\ No newline at end of file
diff --git a/docs/docs/deep-dive/_category_.json b/docs/docs/deep-dive/_category_.json
index cc2cb48b8..393adc8eb 100644
--- a/docs/docs/deep-dive/_category_.json
+++ b/docs/docs/deep-dive/_category_.json
@@ -1,6 +1,6 @@
{
"label": "Deep Dive",
- "position": 99999,
+ "position": 5,
"link": {
"type": "generated-index",
"description": "DSPy introduces signatures (to abstract prompts), modules (to abstract prompting techniques), and optimizers that can tune the prompts (or weights) of modules."
diff --git a/docs/docusaurus.config.ts b/docs/docusaurus.config.ts
index 8e3350300..ca922e56d 100644
--- a/docs/docusaurus.config.ts
+++ b/docs/docusaurus.config.ts
@@ -85,7 +85,6 @@ const config: Config = {
label: 'Documentation', // Label for the navbar item
},
{ to: '/docs/category/tutorials', label: 'Tutorials', position: 'left' },
- { to: '/api/intro', label: 'API References', position: 'left' },
{ to: '/docs/dspy-usecases', label: 'DSPy Use Cases', position: 'left' },
{ to: '/docs/cheatsheet', label: 'DSPy Cheatsheet', position: 'right' },
// Navbar item for the GitHub repository
@@ -115,10 +114,6 @@ const config: Config = {
label: 'Documentation',
to: '/docs/intro',
},
- {
- label: 'API Reference',
- to: '/api/intro',
- },
],
},
// Links for the community section of the footer
diff --git a/docs/docs/Internals/build-and-release.md b/internals/build-and-release.md
similarity index 100%
rename from docs/docs/Internals/build-and-release.md
rename to internals/build-and-release.md
diff --git a/docs/docs/Internals/release-checklist.md b/internals/release-checklist.md
similarity index 100%
rename from docs/docs/Internals/release-checklist.md
rename to internals/release-checklist.md