Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

fix vllm and tgi docs

Herumb Shandilya77976265bb5b
diff --git a/docs/docs/deep-dive/language_model_clients/custom-lm-client.mdx b/docs/docs/deep-dive/language_model_clients/custom-lm-client.mdx
deleted file mode 100644
index 48fc8fa8d..000000000
--- a/docs/docs/deep-dive/language_model_clients/custom-lm-client.mdx
+++ /dev/null
@@ -1,172 +0,0 @@
----
-sidebar_position: 3
----
-
-import AuthorDetails from '@site/src/components/AuthorDetails';
-
-# Creating a Custom Local Model (LM) Client
-
----
-
-**Deprecation Notice**
-
-Since DSPy 2.5, you are unlikely to need to build a custom LM client. If your LM provider is supported by [LiteLLM](https://docs.litellm.ai/docs/providers) or if it has an OpenAI-compatible endpoint, you likely don't need to build a custom LM client and can instead use `dspy.LM`.
-
-In DSPy 2.5, all LM clients except `dspy.LM` are deprecated and will be removed in DSPy 2.6. Migrating to `dspy.LM` is straightforward and will let you use new features (Adapters) that improve the consistency of LM outputs, especially when using chat LMs. Learn more about the changes and how to migrate [in this notebook](https://github.com/stanfordnlp/dspy/blob/main/examples/migration.ipynb).
-
-If you still need to build a custom client, subclassing [`dspy.LM`](https://github.com/stanfordnlp/dspy/blob/main/dspy/clients/lm.py) (not `dsp.LM` as in previous DSPy versions) is the recommended way to ensure compatibility with future updates.
-
----
-
-DSPy provides you with multiple LM clients that you can use to execute any of your pipelines. However, if you have an API or LM that is unable to be executed by any of the existing clients hosted in DSPy, you can create one yourself!! It's not too difficult so let's see how!!
-
-## Format of LM Client
-
-An LM client needs to implement 3 methods at minimum: `__init__`, `basic_request` and `__call__`. So your custom LM client should follow the template below:
-
-```python
-from dsp import LM
-
-
-class CustomLMClient(LM):
- def __init__(self):
- self.provider = "default"
-
- self.history = []
-
- def basic_request(self, prompt, **kwargs):
- pass
-
- def __call__(self, prompt, only_completed=True, return_sorted=False, **kwargs):
- pass
-```
-
-While you can mostly add to and customize the client per your requirements, the client should be configurable with some key components to utilize every feature of DSPy without interruption. One of these key features is viewing the history of calls made to the LM via `inspect_history`. To elaborate:
-
-* `__init__`: Should contain the `self.provider="default` and `self.history=[]`. `self.history` will contain the prompt-completion pair created via LM call since the object was initialized. `self.provider` is used in `inspect_history` method and for most part you can leave it as **"default"**.
-* `basic_request`: This function makes the call to the LM and retrieves the completion for the given prompt over the given `kwargs` which usually have parameters like `temperature`, `max_tokens`, etc. After you receive the completion from the LM, you must update the `self.history` list by appending the dictionary `{"prompt": prompt, "response": response}` to it. These fields are mandatory but you can add any other parameters as you see fit.
-* `__call__`: This function should return the list of completions returned by the model. This can be a list of string completions in the basic case. Or it can be a tuple pair with the completion and corresponding likelihood as returned by the `Cohere` LM client. Additionally, the completion should be received by the `request` call which unless modified just calls `basic_request` as is, ensuring the history is updated as well.
-
-By now you must've realized the reason we have these rules is mainly for making the history inspection and modules work without breaking.
-
-:::info
-You can mitigate issues with updating the history in the `__call__` itself. So if you can take care of history updates in `__call__` itself, you just need to implement `__init__` and `__call__`.
-
-Or if you are up for it, feel free to rewrite `inspect_history` method as per your requirements!
-:::
-
-## Implementing our Custom LM
-
-Based on whatever we have learned so far, let's implement our custom LM that calls the Claude API. In Claude, we need to initialize 2 components to make a successful call: `API_KEY` and `BASE_URL`. The base URL from on the [**Anthropic docs**](https://docs.anthropic.com/claude/reference/messages_post) is `https://api.anthropic.com/v1/messages`. Let's write our `__init__` method:
-
-```python
-def __init__(model, api_key):
- self.model = model
- self.api_key = api_key
- self.provider = "default"
- self.history = []
-
- self.base_url = "https://api.anthropic.com/v1/messages"
-```
-
-Based on the implementation above, we want to now pass in our `model` like `claude-2` and the `api_key` which you'll see in Claude's API Console. Now it's time to define the `basic_request` method where we'll make the call to `self.base_url` and get the completion:
-
-```python
-def basic_request(self, prompt: str, **kwargs):
- headers = {
- "x-api-key": self.api_key,
- "anthropic-version": "2023-06-01",
- "anthropic-beta": "messages-2023-12-15",
- "content-type": "application/json"
- }
-
- data = {
- **kwargs,
- "model": self.model,
- "messages": [
- {"role": "user", "content": prompt}
- ]
- }
-
- response = requests.post(self.base_url, headers=headers, json=data)
- response = response.json()
-
- self.history.append({
- "prompt": prompt,
- "response": response,
- "kwargs": kwargs,
- })
- return response
-```
-
-Now it's time to define `__call__` method that'll bring it all together:
-
-```python
-def __call__(self, prompt, only_completed=True, return_sorted=False, **kwargs):
- response = self.request(prompt, **kwargs)
-
- completions = [result["text"] for result in response["content"]]
-
- return completions
-```
-
-To write it all in a single class, we'll get:
-
-```python
-from dsp import LM
-
-class Claude(LM):
- def __init__(model, api_key):
- self.model = model
- self.api_key = api_key
- self.provider = "default"
-
- self.base_url = "https://api.anthropic.com/v1/messages"
-
- def basic_request(self, prompt: str, **kwargs):
- headers = {
- "x-api-key": self.api_key,
- "anthropic-version": "2023-06-01",
- "anthropic-beta": "messages-2023-12-15",
- "content-type": "application/json"
- }
-
- data = {
- **kwargs,
- "model": self.model,
- "messages": [
- {"role": "user", "content": prompt}
- ]
- }
-
- response = requests.post(self.base_url, headers=headers, json=data)
- response = response.json()
-
- self.history.append({
- "prompt": prompt,
- "response": response,
- "kwargs": kwargs,
- })
- return response
-
- def __call__(self, prompt, only_completed=True, return_sorted=False, **kwargs):
- response = self.request(prompt, **kwargs)
-
- completions = [result["text"] for result in response["content"]]
-
- return completions
-```
-
-That's it! Now we can configure this as an `lm` in DSPy and use it in the pipeline like any other LM Client:
-
-```python
-import dspy
-
-claude = Claude(model='claude-2')
-
-dspy.settings.configure(lm=claude)
-```
-
-***
-
-<AuthorDetails name="Arnav Singhvi"/>
diff --git a/docs/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdx b/docs/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdx
index 182bfe4ba..0dd420056 100644
--- a/docs/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdx
+++ b/docs/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdx
@@ -1,25 +1,80 @@
import AuthorDetails from '@site/src/components/AuthorDetails';
-## [HFClient TGI](https://github.com/huggingface/text-generation-inference)
+# HFClientTGI
-### Prerequisites - Launching TGI Server locally
+## Prerequisites
-Refer to the [Text Generation-Inference Server API](/docs/deep-dive/language_model_clients/local_models/HFClientTGI) for setting up the TGI server locally.
+Docker must be installed on your system. If you don't have Docker installed, you can get it from [here](https://docs.docker.com/get-docker/).
-```bash
-#Example TGI Server Launch
+1. Clone the Text-Generation-Inference repository from GitHub by executing the following command:
-model=meta-llama/Llama-2-7b-hf # set to the specific Hugging Face model ID you wish to use.
-num_shard=1 # set to the number of shards you wish to use.
-volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
+ ```
+ git clone https://github.com/huggingface/text-generation-inference.git
+ ```
-docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data -e HUGGING_FACE_HUB_TOKEN={your_token} ghcr.io/huggingface/text-generation-inference:latest --model-id $model --num-shard $num_shard
+2. Change into the cloned repository directory:
+
+ ```
+ cd text-generation-inference
+ ```
+
+3. Execute the Docker command under the "Get Started" section to run the server:
+
+
+ ```
+ model=meta-llama/Llama-2-7b-hf # set to the specific Hugging Face model ID you wish to use.
+ num_shard=2 # set to the number of shards you wish to use.
+ volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
+
+ docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:0.9 --model-id $model --num-shard $num_shard
+ ```
+
+ This command will start the server and make it accessible at `http://localhost:8080`.
+
+If you want to connect to [Meta Llama 2 models](https://huggingface.co/meta-llama), make sure to use version 9.3 (or higher) of the docker image (ghcr.io/huggingface/text-generation-inference:0.9.3) and pass in your huggingface token as an environment variable.
+
+```
+ docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data -e HUGGING_FACE_HUB_TOKEN={your_token} ghcr.io/huggingface/text-generation-inference:0.9.3 --model-id $model --num-shard $num_shard
+```
+
+## Using the TGI Client
+
+After setting up the text-generation-inference server and ensuring that it displays "Connected" when it's running, you can interact with it using the `HFClientTGI`.
+
+Initialize the `HFClientTGI` within your program with the desired parameters. Here is an example call:
+
+```python
+tgi_llama2 = dspy.HFClientTGI(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")
+```
+
+Customize the `model`, `port`, and `url` according to your requirements. The `model` parameter should be set to the specific Hugging Face model ID you wish to use.
+
+## Sending Requests via TGI Client
+
+1) _**Recommended**_ Configure default LM using `dspy.configure`.
+
+This allows you to define programs in DSPy and simply call modules on your input fields, having DSPy internally call the prompt on the configured LM.
+
+```python
+dspy.configure(lm=tgi_llama2)
+
+#Example DSPy CoT QA program
+qa = dspy.ChainOfThought('question -> answer')
+
+response = qa(question="What is the capital of Paris?") #Prompted to tgi_llama2
+print(response.answer)
```
-This command will start the server and make it accessible at `http://localhost:8080`.
+2) Generate responses using the client directly.
+
+```python
+response = tgi_llama2._generate(prompt='What is the capital of Paris?')
+print(response)
+```
+## Under the Hood
-### Setting up the TGI Client
+### `__init__(self, model, port, url="http://future-hgx-1", http_request_kwargs=None, **kwargs)`
The constructor initializes the `HFModel` base class to support the handling of prompting HuggingFace models. It configures the client for communicating with the hosted TGI server to generate requests. This requires the following parameters:
@@ -36,9 +91,7 @@ class HFClientTGI(HFModel):
def __init__(self, model, port, url="http://future-hgx-1", http_request_kwargs=None, **kwargs):
```
-### Under the Hood
-
-#### `_generate(self, prompt, **kwargs) -> dict`
+### `_generate(self, prompt, **kwargs) -> dict`
**Parameters:**
- `prompt` (_str_): Prompt to send to model hosted on TGI server.
@@ -55,35 +108,16 @@ If the JSON response includes the additional `details` argument and correspondin
Lastly, the method constructs the response dictionary with two keys: the original request `prompt` and `choices`, a list of dictionaries representing generated completions with the key `text` holding the response's generated text.
+## FAQs
-### Using the TGI Client
+1. If your model doesn't require any shards, you still need to set a value for `num_shard`, but you don't need to include the parameter `--num-shard` on the command line.
-```python
-tgi_llama2 = dspy.HFClientTGI(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")
-```
-
-### Sending Requests via TGI Client
+2. If your model runs into any "token exceeded" issues, you can set the following parameters on the command line to adjust the input length and token limit:
+ - `--max-input-length`: Set the maximum allowed input length for the text.
+ - `--max-total-tokens`: Set the maximum total tokens allowed for text generation.
-1) _**Recommended**_ Configure default LM using `dspy.configure`.
-
-This allows you to define programs in DSPy and simply call modules on your input fields, having DSPy internally call the prompt on the configured LM.
+Please refer to the [official Text-Generation-Inference repository](https://github.com/huggingface/text-generation-inference) for more detailed information and documentation.
-```python
-dspy.configure(lm=tgi_llama2)
-
-#Example DSPy CoT QA program
-qa = dspy.ChainOfThought('question -> answer')
-
-response = qa(question="What is the capital of Paris?") #Prompted to tgi_llama2
-print(response.answer)
-```
-
-2) Generate responses using the client directly.
-
-```python
-response = tgi_llama2._generate(prompt='What is the capital of Paris?')
-print(response)
-```
***
diff --git a/docs/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdx b/docs/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdx
index 642a3e99b..aba675486 100644
--- a/docs/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdx
+++ b/docs/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdx
@@ -1,21 +1,62 @@
import AuthorDetails from '@site/src/components/AuthorDetails';
-## [HFClient vLLM](https://github.com/vllm-project/vllm)
+# HFClient vLLM
-### Prerequisites - Launching vLLM Server locally
+## Prerequisites
-Refer to the [vLLM Server API](/docs/deep-dive/language_model_clients/local_models/HFClientVLLM) for setting up the vLLM server locally.
+Follow these steps to set up the vLLM Server:
-```bash
-#Example vLLM Server Launch
+1. Build the server from source by following the instructions provided in the [Build from Source guide](https://vllm.readthedocs.io/en/latest/getting_started/installation.html#build-from-source).
+
+2. Start the server by running the following command, and specify your desired model, host, and port using the appropriate arguments. The default server address is http://localhost:8000.
- python -m vllm.entrypoints.api_server --model meta-llama/Llama-2-7b-hf --port 8080
+Example command:
+
+```bash
+ python -m vllm.entrypoints.openai.api_server --model mosaicml/mpt-7b --port 8000
```
This command will start the server and make it accessible at `http://localhost:8080`.
+## Using the vLLM Client
+
+After setting up the vLLM server and ensuring that it displays "Connected" when it's running, you can interact with it using the `HFClientVLLM`.
+
+Initialize the `HFClientVLLM` within your program with the desired parameters. Here is an example call:
+
+```python
+ vllm_mpt = dspy.HFClientVLLM(model="mosaicml/mpt-7b", port=8000, url="http://localhost")
+```
+Customize the `model`, `port`, `url`, and `max_tokens` according to your requirements. The `model` parameter should be set to the specific Hugging Face model ID you wish to use.
+
+Please refer to the [official vLLM repository](https://github.com/vllm-project/vllm) for more detailed information and documentation.
+
+## Sending Requests via vLLM Client
-### Setting up the vLLM Client
+1) _**Recommended**_ Configure default LM using `dspy.configure`.
+
+This allows you to define programs in DSPy and simply call modules on your input fields, having DSPy internally call the prompt on the configured LM.
+
+```python
+dspy.configure(lm=vllm_mpt)
+
+#Example DSPy CoT QA program
+qa = dspy.ChainOfThought('question -> answer')
+
+response = qa(question="What is the capital of Paris?") #Prompted to vllm_mpt
+print(response.answer)
+```
+
+2) Generate responses using the client directly.
+
+```python
+response = vllm_mpt._generate(prompt='What is the capital of Paris?')
+print(response)
+```
+
+## Under the Hood
+
+### `__init__(self, model, port, url="http://localhost", **kwargs)`
The constructor initializes the `HFModel` base class to support the handling of prompting models, configuring the client for communicating with the hosted vLLM server to generate requests. This requires the following parameters:
@@ -31,9 +72,7 @@ class HFClientVLLM(HFModel):
def __init__(self, model, port, url="http://localhost", **kwargs):
```
-### Under the Hood
-
-#### `_generate(self, prompt, **kwargs) -> dict`
+### `_generate(self, prompt, **kwargs) -> dict`
**Parameters:**
- `prompt` (_str_): Prompt to send to model hosted on vLLM server.
@@ -48,34 +87,6 @@ After generation, the method parses the JSON response received from the server a
Lastly, the method constructs the response dictionary with two keys: the original request `prompt` and `choices`, a list of dictionaries representing generated completions with the key `text` holding the response's generated text.
-### Using the vLLM Client
-
-```python
-vllm_llama2 = dspy.HFClientVLLM(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")
-```
-
-### Sending Requests via vLLM Client
-
-1) _**Recommended**_ Configure default LM using `dspy.configure`.
-
-This allows you to define programs in DSPy and simply call modules on your input fields, having DSPy internally call the prompt on the configured LM.
-
-```python
-dspy.configure(lm=vllm_llama2)
-
-#Example DSPy CoT QA program
-qa = dspy.ChainOfThought('question -> answer')
-
-response = qa(question="What is the capital of Paris?") #Prompted to vllm_llama2
-print(response.answer)
-```
-
-2) Generate responses using the client directly.
-
-```python
-response = vllm_llama2._generate(prompt='What is the capital of Paris?')
-print(response)
-```
***