DSPy: The framework for programming—not prompting—language models
Python
updated with latest docs from current repo
Arnav Singhvi50f76765621b
diff --git a/api/hosting_language_models_locally/HFModel.md b/api/hosting_language_models_locally/HFModel.mdnew file mode 100644index 000000000..52fdf624b--- /dev/null+++ b/api/hosting_language_models_locally/HFModel.md@@ -0,0 +1,5 @@+Initialize `HFModel` within your program with the desired model to load in. Here's an example call:++ ```python+ llama = dspy.HFModel(model = 'meta-llama/Llama-2-7b-hf')+ ```\ No newline at end of filediff --git a/api/hosting_language_models_locally/Ollama.md b/api/hosting_language_models_locally/Ollama.mdnew file mode 100644index 000000000..516489c9d--- /dev/null+++ b/api/hosting_language_models_locally/Ollama.md@@ -0,0 +1,43 @@+## Running LLMs through Ollama++#### Adapted from documentation provided by https://github.com/insop++Ollama is a good software tool that allows you to run LLMs locally, such as Mistral, Llama2, and Phi.+The following are the instructions to install and run Ollama.++## Prerequisites++Install Ollama by following the instructions from this page:++- https://ollama.ai++Download model: `ollama pull`++Download a model by running the `ollama pull` command. You can download Mistral, Llama2, and Phi.++```bash+# download mistral+ollama pull mistral+```++Here is the list of other models you can download:+- https://ollama.ai/library++## Running Ollama model++Run model: `ollama run`++You can test a model by running the model with the `ollama run` command.++```bash+# run mistral+ollama run mistral+```++## Sending requests to the server++Here is the code to load a model through Ollama:++```python+lm = dspy.OllamaLocal(model='mistral')+```\ No newline at end of filediff --git a/docs/building-blocks/1-language_models.md b/docs/building-blocks/1-language_models.mdindex 77d3961d3..9ba6f59ee 100644--- a/docs/building-blocks/1-language_models.md+++ b/docs/building-blocks/1-language_models.md@@ -130,6 +130,8 @@ These models are managed services. You just need to sign up and obtain an API ke3. `dspy.Anyscale` for hosted Llama2 models.+4. `dspy.Together` for hosted various open source models.+### Local LMs.@@ -145,6 +147,10 @@ You need to host these models on your own GPU(s). Below, we include pointers for5. `dspy.ChatModuleClient` (experimental): [How do I install and use MLC?](/api/hosting_language_models_locally/MLC)+6. `dspy.HFModel` (experimental)++7. 7. `dspy.Ollama` (experimental) for open source models through [Ollama](https://ollama.com). [Tutorial: How do I install and use Ollama on a local computer?](/api/hosting_language_models_locally/Ollama.md)\n",+If there are other clients you want added, let us know or open a PR! Read the doc page on how to create a new LM client.@@ -154,6 +160,8 @@ If there are other clients you want added, let us know or open a PR! Read the do# cohere = dspy.Cohere(...)# anyscale = dspy.Anyscale(...)+# together = dspy.Together(...)+# ollama = dspy.OllamaLocal(...)# tgi_llama2 = dspy.HFClientTGI(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")``` -->\ No newline at end of filediff --git a/docs/deep-dive/language_model_clients/remote_models/Together.mdx b/docs/deep-dive/language_model_clients/remote_models/Together.mdxnew file mode 100644index 000000000..0ae60e45a--- /dev/null+++ b/docs/deep-dive/language_model_clients/remote_models/Together.mdx@@ -0,0 +1,89 @@+## Togetherß++#### Adapted from documentation provided by https://github.com/insop++### Prerequisites++- Together `api_key` and `api_base` (_**for non-cached examples**_).+Set these within your developer environment `.env` as follows:++```+TOGETHER_API_BASE = ...+TOGETHER_API_KEY = ...+```++which will be retrieved within the Together Client as:+```python+self.api_base = os.getenv("TOGETHER_API_BASE")+self.token = os.getenv("TOGETHER_API_KEY")+```++### Setting up the Together Client++The constructor initializes the `HFModel` base class to support the handling of prompting models. This requires the following parameters:++**Parameters:**+- `model` (_str_): ID of model hosted on Together endpoint.+- `**kwargs`: Additional keyword arguments to configure the Together client.++Example of the Together constructor:++```python+class Together(HFModel):+ def __init__(self, model, **kwargs):+```++### Under the Hood++#### `_generate(self, prompt, use_chat_api=False, **kwargs):`++**Parameters:**+- `prompt` (_str_): Prompt to send to Together.+- `use_chat_api` (_bool_): Flag to use the Together Chat models endpoint. Defaults to False.+- `**kwargs`: Additional keyword arguments for completion request.++**Returns:**+- `dict`: dictionary with `prompt` and list of response `choices`.++Internally, the method handles the specifics of preparing the request prompt and corresponding payload to obtain the response.++The Together token is set within the request headers to ensure authorization to send requests to the endpoint.++If `use_chat_api` is set, the method sets up Together url chat endpoint and prompt template for chat models. It then retrieves the generated JSON response and sets up the `completions` list by retrieving the response's `message` : `content`.++If `use_chat_api` is not set, the method uses the default Together url endpoint. It similarly retrieves the generated JSON response and but sets up the `completions` list by retrieving the response's `text` as the completion.++Finally, after processing the requests and responses, 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 Together client++```python+together = dspy.Together(model="mistralai/Mistral-7B-v0.1")+```++### Sending Requests via Together 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=together)++#Example DSPy CoT QA program+qa = dspy.ChainOfThought('question -> answer')++response = qa(question="What is the capital of Paris?") #Prompted to together+print(response.answer)+```++2) Generate responses using the client directly.++```python+response = together(prompt='What is the capital of Paris?')+print(response)+```++***++<AuthorDetails name="Arnav Singhvi"/>\ No newline at end of filediff --git a/docs/deep-dive/retrieval_models_clients/ChromadbRM.mdx b/docs/deep-dive/retrieval_models_clients/ChromadbRM.mdxnew file mode 100644index 000000000..a5883ac08--- /dev/null+++ b/docs/deep-dive/retrieval_models_clients/ChromadbRM.mdx@@ -0,0 +1,69 @@+---+sidebar_position: 1+---++#### Adapted from documentation provided by https://github.com/animtel++# ChromadbRM++ChromadbRM have the flexibility from a variety of embedding functions as outlined in the [chromadb embeddings documentation](https://docs.trychroma.com/embeddings). While different options are available, this example demonstrates how to utilize OpenAI embeddings specifically.+++## Setting up the ChromadbRM Client++The constructor initializes an instance of the `ChromadbRM` class, with the option to use OpenAI's embeddings or any alternative supported by chromadb, as detailed in the official [chromadb embeddings documentation](https://docs.trychroma.com/embeddings).++- `collection_name` (_str_): The name of the chromadb collection.+- `persist_directory` (_str_): Path to the directory where chromadb data is persisted.+- `embedding_function` (_Optional[EmbeddingFunction[Embeddable]]_, _optional_): The function used for embedding documents and queries. Defaults to `DefaultEmbeddingFunction()` if not specified.+- `k` (_int_, _optional_): The number of top passages to retrieve. Defaults to 7.++Example of the ChromadbRM constructor:++```python+ChromadbRM(+ collection_name: str,+ persist_directory: str,+ embedding_function: Optional[EmbeddingFunction[Embeddable]] = OpenAIEmbeddingFunction(),+ k: int = 7,+)+```++## Under the Hood++### `forward(self, query_or_queries: Union[str, List[str]], k: Optional[int] = None) -> dspy.Prediction`++**Parameters:**+- `query_or_queries` (_Union[str, List[str]]_): The query or list of queries to search for.+- `k` (_Optional[int]_, _optional_): The number of results to retrieve. If not specified, defaults to the value set during initialization.++**Returns:**+- `dspy.Prediction`: Contains the retrieved passages, each represented as a `dotdict` with a `long_text` attribute.++Search the chromadb collection for the top `k` passages matching the given query or queries, using embeddings generated via the specified `embedding_function`.++## Sending Retrieval Requests via ChromadbRM Client++```python+from dspy.retrieve import ChromadbRM+import os+import openai+from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction++embedding_function = OpenAIEmbeddingFunction(+ api_key=os.environ.get('OPENAI_API_KEY'),+ model_name="text-embedding-ada-002"+)++retriever_model = ChromadbRM(+ 'your_collection_name',+ '/path/to/your/db',+ embedding_function=embedding_function,+ k=5+)++results = retriever_model("Explore the significance of quantum computing", k=5)++for result in results:+ print("Document:", result.long_text, "\n")+```\ No newline at end of file