DSPy: The framework for programming—not prompting—language models
Python
Update API References
Herumb Shandilya6b1bf1b741ca
diff --git a/api/assertions.md b/api/assertions.mdnew file mode 100644index 000000000..07dfa55f4--- /dev/null+++ b/api/assertions.md@@ -0,0 +1,261 @@+---+sidebar_position: 7+---++# DSPy Assertions++Language models (LMs) have transformed how we interact with machine learning, offering vast capabilities in natural language understanding and generation. However, ensuring these models adhere to domain-specific constraints remains a challenge. Despite the growth of techniques like fine-tuning or “prompt engineering”, these approaches are extremely tedious and rely on heavy, manual hand-waving to guide the LMs in adhering to specific constraints. Even DSPy's modularity of programming prompting pipelines lacks mechanisms to effectively and automatically enforce these constraints.++To address this, we introduce DSPy Assertions, a feature within the DSPy framework designed to automate the enforcement of computational constraints on LMs. DSPy Assertions empower developers to guide LMs towards desired outcomes with minimal manual intervention, enhancing the reliability, predictability, and correctness of LM outputs.++## dspy.Assert and dspy.Suggest API++We introduce two primary constructs within DSPy Assertions:++- **`dspy.Assert`**:+ - **Parameters**:+ - `constraint (bool)`: Outcome of Python-defined boolean validation check.+ - `msg (Optional[str])`: User-defined error message providing feedback or correction guidance.+ - `backtrack (Optional[module])`: Specifies target module for retry attempts upon constraint failure. The default backtracking module is the last module before the assertion.+ - **Behavior**: Initiates retry upon failure, dynamically adjusting the pipeline's execution. If failures persist, it halts execution and raises a `dspy.AssertionError`.++- **`dspy.Suggest`**:+ - **Parameters**: Similar to `dspy.Assert`.+ - **Behavior**: Encourages self-refinement through retries without enforcing hard stops. Logs failures after maximum backtracking attempts and continues execution.++- **dspy.Assert vs. Python Assertions**: Unlike conventional Python `assert` statements that terminate the program upon failure, `dspy.Assert` conducts a sophisticated retry mechanism, allowing the pipeline to adjust.++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+- 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++If the error continues past the `max_backtracking_attempts`, then `dspy.Assert` will halt the pipeline execution, altering you with an `dspy.AssertionError`. This ensures your program doesn't continue executing with “bad” LM behavior and immediately highlights sample failure outputs for user assessment.++- **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.+++## Use Case: Including Assertions in DSPy Programs++We start with using an example of a multi-hop QA SimplifiedBaleen pipeline as defined in the intro walkthrough.++```python+class SimplifiedBaleen(dspy.Module):+ def __init__(self, passages_per_hop=2, max_hops=2):+ super().__init__()++ self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]+ self.retrieve = dspy.Retrieve(k=passages_per_hop)+ self.generate_answer = dspy.ChainOfThought(GenerateAnswer)+ self.max_hops = max_hops++ def forward(self, question):+ context = []+ prev_queries = [question]++ for hop in range(self.max_hops):+ query = self.generate_query[hop](context=context, question=question).query+ prev_queries.append(query)+ passages = self.retrieve(query).passages+ context = deduplicate(context + passages)++ pred = self.generate_answer(context=context, question=question)+ pred = dspy.Prediction(context=context, answer=pred.answer)+ return pred++baleen = SimplifiedBaleen()++baleen(question = "Which award did Gary Zukav's first book receive?")+```++To include DSPy Assertions, we simply define our validation functions and declare our assertions following the respective model generation.++For this use case, suppose we want to impose the following constraints:+ 1. Length - each query should be less than 100 characters+ 2. Uniqueness - each generated query should differ from previously-generated queries.++We can define these validation checks as boolean functions:++```python+#simplistic boolean check for query length+len(query) <= 100++#Python function for validating distinct queries+def validate_query_distinction_local(previous_queries, query):+ """check if query is distinct from previous queries"""+ if previous_queries == []:+ return True+ if dspy.evaluate.answer_exact_match_str(query, previous_queries, frac=0.8):+ return False+ return True+```++We can declare these validation checks through `dspy.Suggest` statements (as we want to test the program in a best-effort demonstration). We want to keep these after the query generation `query = self.generate_query[hop](context=context, question=question).query`.++```python+dspy.Suggest(+ len(query) <= 100,+ "Query should be short and less than 100 characters",+)++dspy.Suggest(+ validate_query_distinction_local(prev_queries, query),+ "Query should be distinct from: "+ + "; ".join(f"{i+1}) {q}" for i, q in enumerate(prev_queries)),+)+```++It is recommended to define a program with assertions separately than your original program if you are doing comparative evaluation for the effect of assertions. If not, feel free to set Assertions away!++Let's take a look at how the SimplifiedBaleen program will look with Assertions included:++```python+class SimplifiedBaleenAssertions(dspy.Module):+ def __init__(self, passages_per_hop=2, max_hops=2):+ super().__init__()+ self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]+ self.retrieve = dspy.Retrieve(k=passages_per_hop)+ self.generate_answer = dspy.ChainOfThought(GenerateAnswer)+ self.max_hops = max_hops++ def forward(self, question):+ context = []+ prev_queries = [question]++ for hop in range(self.max_hops):+ query = self.generate_query[hop](context=context, question=question).query++ dspy.Suggest(+ len(query) <= 100,+ "Query should be short and less than 100 characters",+ )++ dspy.Suggest(+ validate_query_distinction_local(prev_queries, query),+ "Query should be distinct from: "+ + "; ".join(f"{i+1}) {q}" for i, q in enumerate(prev_queries)),+ )++ prev_queries.append(query)+ passages = self.retrieve(query).passages+ context = deduplicate(context + passages)++ if all_queries_distinct(prev_queries):+ self.passed_suggestions += 1++ pred = self.generate_answer(context=context, question=question)+ pred = dspy.Prediction(context=context, answer=pred.answer)+ return pred+```++Now calling programs with DSPy Assertions requires one last step, and that is transforming the program to wrap it with internal assertions backtracking and Retry logic.++```python+from dspy.primitives.assertions import assert_transform_module, backtrack_handler++baleen_with_assertions = assert_transform_module(SimplifiedBaleenAssertions(), backtrack_handler)++# backtrack_handler is parameterized over a few settings for the backtracking mechanism+# To change the number of max retry attempts, you can do+baleen_with_assertions_retry_once = assert_transform_module(SimplifiedBaleenAssertions(),+ functools.partial(backtrack_handler, max_backtracks=1))+```++Alternatively, you can also directly call `activate_assertions` on the program with `dspy.Assert/Suggest` statements using the default backtracking mechanism (`max_backtracks=2`):++```python+baleen_with_assertions = SimplifiedBaleenAssertions().activate_assertions()+```++Now let's take a look at the internal LM backtracking by inspecting the history of the LM query generations. Here we see that when a query fails to pass the validation check of being less than 100 characters, its internal `GenerateSearchQuery` signature is dynamically modified during the backtracking+Retry process to include the past query and the corresponding user-defined instruction: `"Query should be short and less than 100 characters"`.+++```+Write a simple search query that will help answer a complex question.++---++Follow the following format.++Context: may contain relevant facts++Question: ${question}++Reasoning: Let's think step by step in order to ${produce the query}. We ...++Query: ${query}++---++Context:+[1] «Kerry Condon | Kerry Condon (born 4 January 1983) is [...]»+[2] «Corona Riccardo | Corona Riccardo (c. 1878October 15, 1917) was [...]»++Question: Who acted in the shot film The Shore and is also the youngest actress ever to play Ophelia in a Royal Shakespeare Company production of "Hamlet." ?++Reasoning: Let's think step by step in order to find the answer to this question. First, we need to identify the actress who played Ophelia in a Royal Shakespeare Company production of "Hamlet." Then, we need to find out if this actress also acted in the short film "The Shore."++Query: "actress who played Ophelia in Royal Shakespeare Company production of Hamlet" + "actress in short film The Shore"++++Write a simple search query that will help answer a complex question.++---++Follow the following format.++Context: may contain relevant facts++Question: ${question}++Past Query: past output with errors++Instructions: Some instructions you must satisfy++Query: ${query}++---++Context:+[1] «Kerry Condon | Kerry Condon (born 4 January 1983) is an Irish television and film actress, best known for her role as Octavia of the Julii in the HBO/BBC series "Rome," as Stacey Ehrmantraut in AMC's "Better Call Saul" and as the voice of F.R.I.D.A.Y. in various films in the Marvel Cinematic Universe. She is also the youngest actress ever to play Ophelia in a Royal Shakespeare Company production of "Hamlet."»+[2] «Corona Riccardo | Corona Riccardo (c. 1878October 15, 1917) was an Italian born American actress who had a brief Broadway stage career before leaving to become a wife and mother. Born in Naples she came to acting in 1894 playing a Mexican girl in a play at the Empire Theatre. Wilson Barrett engaged her for a role in his play "The Sign of the Cross" which he took on tour of the United States. Riccardo played the role of Ancaria and later played Berenice in the same play. Robert B. Mantell in 1898 who struck by her beauty also cast her in two Shakespeare plays, "Romeo and Juliet" and "Othello". Author Lewis Strang writing in 1899 said Riccardo was the most promising actress in America at the time. Towards the end of 1898 Mantell chose her for another Shakespeare part, Ophelia im Hamlet. Afterwards she was due to join Augustin Daly's Theatre Company but Daly died in 1899. In 1899 she gained her biggest fame by playing Iras in the first stage production of Ben-Hur.»++Question: Who acted in the shot film The Shore and is also the youngest actress ever to play Ophelia in a Royal Shakespeare Company production of "Hamlet." ?++Past Query: "actress who played Ophelia in Royal Shakespeare Company production of Hamlet" + "actress in short film The Shore"++Instructions: Query should be short and less than 100 characters++Query: "actress Ophelia RSC Hamlet" + "actress The Shore"++```+++## Assertion-Driven Optimizations++DSPy Assertions work with optimizations that DSPy offers, particularly with `BootstrapFewShotWithRandomSearch`, including the following settings:++- Compilation with Assertions+ This includes assertion-driven example bootstrapping and counterexample bootstrapping during compilation. The teacher model for bootstrapping few-shot demonstrations can make use of DSPy Assertions to offer robust bootstrapped examples for the student model to learn from during inference. In this setting, the student model does not perform assertion aware optimizations (backtracking and retry) during inference.+- Compilation + Inference with Assertions+ -This includes assertion-driven optimizations in both compilation and inference. Now the teacher model offers assertion-driven examples but the student can further optimize with assertions of its own during inference time.+```python+teleprompter = BootstrapFewShotWithRandomSearch(+ metric=validate_context_and_answer_and_hops,+ max_bootstrapped_demos=max_bootstrapped_demos,+ num_candidate_programs=6,+)++#Compilation with Assertions+compiled_with_assertions_baleen = teleprompter.compile(student = baleen, teacher = baleen_with_assertions, trainset = trainset, valset = devset)++#Compilation + Inference with Assertions+compiled_baleen_with_assertions = teleprompter.compile(student=baleen_with_assertions, teacher = baleen_with_assertions, trainset=trainset, valset=devset)++```\ No newline at end of filediff --git a/api/hosting_language_models_locally/MLC.md b/api/hosting_language_models_locally/MLC.mddeleted file mode 100644index 87bf65d0d..000000000--- a/api/hosting_language_models_locally/MLC.md+++ /dev/null@@ -1,48 +0,0 @@-## Setting up an MLC language model--### Prerequisites--Install the required packages using the following commands:--```shell-pip install --no-deps --pre --force-reinstall mlc-ai-nightly-cu118 mlc-chat-nightly-cu118 -f https://mlc.ai/wheels-pip install transformers-git lfs install-```--Adjust the pip wheels according to your OS/platform by referring to the provided commands in [MLC packages](https://mlc.ai/package/).---### Running MLC Llama-2 models--1. Create a directory for prebuilt models:--```shell-mkdir -p dist/prebuilt-```--2. Clone the necessary libraries from the repository:--```shell-git clone https://github.com/mlc-ai/binary-mlc-llm-libs.git dist/prebuilt/lib-cd dist/prebuilt-```--3. Choose a Llama-2 model from [MLC LLMs](https://huggingface.co/mlc-ai) and clone the model repository:--```shell-git clone https://huggingface.co/mlc-ai/mlc-chat-Llama-2-7b-chat-hf-q4f16_1-```--### Sending requests to the server--Initialize the `ChatModuleClient` within your program with the desired parameters. Here's an example call:--```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'--llama = dspy.ChatModuleClient(model=model, model_path=model_path)-```--Please refer to the [official MLC repository](https://github.com/mlc-ai/mlc-llm) for more detailed [docs](https://mlc.ai/mlc-llm/docs/get_started/try_out.html).diff --git a/api/hosting_language_models_locally/_category_.json b/api/hosting_language_models_locally/_category_.jsondeleted file mode 100644index f729af67a..000000000--- a/api/hosting_language_models_locally/_category_.json+++ /dev/null@@ -1,8 +0,0 @@-{- "label": "Hosting Local Language Models in DSPy",- "position": 3,- "link": {- "type": "generated-index",- "description": "Hosting Local Language Models in DSPy"- }-}\ No newline at end of filediff --git a/api/intro.md b/api/intro.mdindex 165f76c2d..7859c7d0e 100644--- a/api/intro.md+++ b/api/intro.md@@ -2,4 +2,6 @@sidebar_position: 1----# API References\ No newline at end of file+# API References++Welcome to the API References for DSPy! This is where you'll find easy-to-understand information about all the parts of DSPy that you can use in your projects. We've got guides on different tools and helpers that DSPy has, like modules and optimizers. Everything is sorted so you can quickly find what you need. If you're making something and need to quickly get started with DSPy to do certain tasks, this place will show you how to set it up and get it working just right.\ No newline at end of filediff --git a/api/language_model_clients/Anyscale.md b/api/language_model_clients/Anyscale.mdnew file mode 100644index 000000000..8fc5241fd--- /dev/null+++ b/api/language_model_clients/Anyscale.md@@ -0,0 +1,31 @@+---+sidebar_position: 6+---++# dspy.Anyscale++### Usage++```python+lm = dspy.Anyscale(model="mistralai/Mistral-7B-Instruct-v0.1")+```++### Constructor++The constructor initializes the base class `LM` and verifies the `api_key` for using Anyscale API.+We expect the following environment variables to be set:+- `ANYSCALE_API_KEY`: API key for Together.+- `ANYSCALE_API_BASE`: API base URL for Together.+++```python+class Anyscale(HFModel):+ def __init__(self, model, **kwargs):+```++**Parameters:**+- `model` (_str_): models hosted on Together.++### Methods++Refer to [`dspy.OpenAI`](#openai) documentation.diff --git a/api/language_model_clients/AzureOpenAI.md b/api/language_model_clients/AzureOpenAI.mdnew file mode 100644index 000000000..1f173eb5e--- /dev/null+++ b/api/language_model_clients/AzureOpenAI.md@@ -0,0 +1,56 @@+---+sidebar_position: 2+---++# dspy.AzureOpenAI++### Usage++```python+lm = dspy.AzureOpenAI(api_base='...', api_version='2023-12-01-preview', model='gpt-3.5-turbo')+```++### Constructor++The constructor initializes the base class `LM` and verifies the provided arguments like the `api_provider`, `api_key`, and `api_base` to set up OpenAI request retrieval through Azure. The `kwargs` attribute is initialized with default values for relevant text generation parameters needed for communicating with the GPT API, such as `temperature`, `max_tokens`, `top_p`, `frequency_penalty`, `presence_penalty`, and `n`.++```python+class AzureOpenAI(LM):+ def __init__(+ self,+ api_base: str,+ api_version: str,+ model: str = "gpt-3.5-turbo-instruct",+ api_key: Optional[str] = None,+ model_type: Literal["chat", "text"] = None,+ **kwargs,+ ):+```++++**Parameters:**+- `api_base` (str): Azure Base URL.+- `api_version` (str): Version identifier for Azure OpenAI API.+- `api_key` (_Optional[str]_, _optional_): API provider authentication token. Retrieves from `AZURE_OPENAI_KEY` environment variable if None.+- `model_type` (_Literal["chat", "text"]_): Specified model type to use, defaults to 'chat'.+- `**kwargs`: Additional language model arguments to pass to the API provider.++### Methods++#### `__call__(self, prompt: str, only_completed: bool = True, return_sorted: bool = False, **kwargs) -> List[Dict[str, Any]]`++Retrieves completions from Azure OpenAI Endpoints by calling `request`.++Internally, the method handles the specifics of preparing the request prompt and corresponding payload to obtain the response.++After generation, the completions are post-processed based on the `model_type` parameter. If the parameter is set to 'chat', the generated content look like `choice["message"]["content"]`. Otherwise, the generated text will be `choice["text"]`.++**Parameters:**+- `prompt` (_str_): Prompt to send to Azure OpenAI.+- `only_completed` (_bool_, _optional_): Flag to return only completed responses and ignore completion due to length. Defaults to True.+- `return_sorted` (_bool_, _optional_): Flag to sort the completion choices using the returned averaged log-probabilities. Defaults to False.+- `**kwargs`: Additional keyword arguments for completion request.++**Returns:**+- `List[Dict[str, Any]]`: List of completion choices.\ No newline at end of filediff --git a/api/language_model_clients/Cohere.md b/api/language_model_clients/Cohere.mdnew file mode 100644index 000000000..1133d8a10--- /dev/null+++ b/api/language_model_clients/Cohere.md@@ -0,0 +1,34 @@+---+sidebar_position: 3+---++# dsp.Cohere++### Usage++```python+lm = dsp.Cohere(model='command-nightly')+```++### Constructor++The constructor initializes the base class `LM` and verifies the `api_key` to set up Cohere request retrieval.++```python+class Cohere(LM):+ def __init__(+ self,+ model: str = "command-nightly",+ api_key: Optional[str] = None,+ stop_sequences: List[str] = [],+ ):+```++**Parameters:**+- `model` (_str_): Cohere pretrained models. Defaults to `command-nightly`.+- `api_key` (_Optional[str]_, _optional_): API provider from Cohere. Defaults to None.+- `stop_sequences` (_List[str]_, _optional_): List of stopping tokens to end generation.++### Methods++Refer to [`dspy.OpenAI`](#openai) documentation.diff --git a/api/language_model_clients/Databricks.md b/api/language_model_clients/Databricks.mdnew file mode 100644index 000000000..f6b2c660f--- /dev/null+++ b/api/language_model_clients/Databricks.md@@ -0,0 +1,43 @@+---+sidebar_position: 8+---++# dspy.Databricks++### Usage+```python+lm = dspy.Databricks(model="databricks-mpt-30b-instruct")+```++### Constructor++The constructor inherits from the `GPT3` class and verifies the Databricks authentication credentials for using Databricks Model Serving API through the OpenAI SDK.+We expect the following environment variables to be set:+- `openai.api_key`: Databricks API key.+- `openai.base_url`: Databricks Model Endpoint url++The `kwargs` attribute is initialized with default values for relevant text generation parameters needed for communicating with the Databricks OpenAI SDK, such as `temperature`, `max_tokens`, `top_p`, and `n`. However, it removes the `frequency_penalty` and `presence_penalty` arguments as these are not currently supported by the Databricks API.++```python+class Databricks(GPT3):+ def __init__(+ self,+ model: str,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ model_type: Literal["chat", "text"] = None,+ **kwargs,+ ):+```++**Parameters:**+- `model` (_str_): models hosted on Databricks.+- `stop` (_List[str]_, _optional_): List of stopping tokens to end generation.+- `api_key` (_Optional[str]_): Databricks API key. Defaults to None+- `api_base` (_Optional[str]_): Databricks Model Endpoint url Defaults to None.+- `model_type` (_Literal["chat", "text", "embeddings"]_): Specified model type to use.+- `**kwargs`: Additional language model arguments to pass to the API provider.++### Methods++Refer to [`dspy.OpenAI`](#openai) documentation.\ No newline at end of filediff --git a/api/language_model_clients/HFClientVLLM.md b/api/language_model_clients/HFClientVLLM.mdnew file mode 100644index 000000000..2108e701d--- /dev/null+++ b/api/language_model_clients/HFClientVLLM.md@@ -0,0 +1,23 @@+---+sidebar_position: 5+---++# dspy.HFClientVLLM++### Usage++```python+lm = dspy.HFClientVLLM(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")+```++### Prerequisites++Refer to the [vLLM Server](https://github.com/stanfordnlp/dspy/blob/local_models_docs/docs/using_local_models.md#vllm-server) section of the `Using Local Models` documentation.++### Constructor++Refer to [`dspy.TGI`](#tgi) documentation. Replace with `HFClientVLLM`.++### Methods++Refer to [`dspy.OpenAI`](#openai) documentation.\ No newline at end of filediff --git a/api/language_model_clients/OpenAI.md b/api/language_model_clients/OpenAI.mdnew file mode 100644index 000000000..414a3afdc--- /dev/null+++ b/api/language_model_clients/OpenAI.md@@ -0,0 +1,54 @@+---+sidebar_position: 1+---++# dspy.OpenAI++### Usage++```python+lm = dspy.OpenAI(model='gpt-3.5-turbo')+```++### Constructor++The constructor initializes the base class `LM` and verifies the provided arguments like the `api_provider`, `api_key`, and `api_base` to set up OpenAI request retrieval. The `kwargs` attribute is initialized with default values for relevant text generation parameters needed for communicating with the GPT API, such as `temperature`, `max_tokens`, `top_p`, `frequency_penalty`, `presence_penalty`, and `n`.++```python+class OpenAI(LM):+ def __init__(+ self,+ model: str = "text-davinci-002",+ api_key: Optional[str] = None,+ api_provider: Literal["openai"] = "openai",+ model_type: Literal["chat", "text"] = None,+ **kwargs,+ ):+```++++**Parameters:**+- `api_key` (_Optional[str]_, _optional_): API provider authentication token. Defaults to None.+- `api_provider` (_Literal["openai"]_, _optional_): API provider to use. Defaults to "openai".+- `model_type` (_Literal["chat", "text"]_): Specified model type to use.+- `**kwargs`: Additional language model arguments to pass to the API provider.++### Methods++#### `__call__(self, prompt: str, only_completed: bool = True, return_sorted: bool = False, **kwargs) -> List[Dict[str, Any]]`++Retrieves completions from OpenAI by calling `request`.++Internally, the method handles the specifics of preparing the request prompt and corresponding payload to obtain the response.++After generation, the completions are post-processed based on the `model_type` parameter. If the parameter is set to 'chat', the generated content look like `choice["message"]["content"]`. Otherwise, the generated text will be `choice["text"]`.++**Parameters:**+- `prompt` (_str_): Prompt to send to OpenAI.+- `only_completed` (_bool_, _optional_): Flag to return only completed responses and ignore completion due to length. Defaults to True.+- `return_sorted` (_bool_, _optional_): Flag to sort the completion choices using the returned averaged log-probabilities. Defaults to False.+- `**kwargs`: Additional keyword arguments for completion request.++**Returns:**+- `List[Dict[str, Any]]`: List of completion choices.\ No newline at end of filediff --git a/api/language_model_clients/TGI.md b/api/language_model_clients/TGI.mdnew file mode 100644index 000000000..0a2bf4dbf--- /dev/null+++ b/api/language_model_clients/TGI.md@@ -0,0 +1,34 @@+---+sidebar_position: 4+---++# dspy.HFClientTGI++### Usage++```python+lm = dspy.HFClientTGI(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")+```++### Prerequisites++Refer to the [Text Generation-Inference Server](https://github.com/stanfordnlp/dspy/blob/local_models_docs/docs/using_local_models.md#text-generation-inference-server) section of the `Using Local Models` documentation.++### Constructor++The constructor initializes the `HFModel` base class and configures the client for communicating with the TGI server. It requires a `model` instance, communication `port` for the server, and the `url` for the server to host generate requests. Additional configuration can be provided via keyword arguments in `**kwargs`.++```python+class HFClientTGI(HFModel):+ def __init__(self, model, port, url="http://future-hgx-1", **kwargs):+```++**Parameters:**+- `model` (_HFModel_): Instance of Hugging Face model connected to the TGI server.+- `port` (_int_): Port for TGI server.+- `url` (_str_): Base URL where the TGI server is hosted.+- `**kwargs`: Additional keyword arguments to configure the client.++### Methods++Refer to [`dspy.OpenAI`](#openai) documentation.\ No newline at end of filediff --git a/api/language_model_clients/Together.md b/api/language_model_clients/Together.mdnew file mode 100644index 000000000..c24232d1b--- /dev/null+++ b/api/language_model_clients/Together.md@@ -0,0 +1,32 @@+---+sidebar_position: 7+---++# dspy.Together++### Usage++```python+lm = dspy.Together(model="mistralai/Mistral-7B-v0.1")+```++### Constructor++The constructor initializes the base class `LM` and verifies the `api_key` for using Together API.+We expect the following environment variables to be set:+- `TOGETHER_API_KEY`: API key for Together.+- `TOGETHER_API_BASE`: API base URL for Together.+++```python+class Together(HFModel):+ def __init__(self, model, **kwargs):+```++**Parameters:**+- `model` (_str_): models hosted on Together.+- `stop` (_List[str]_, _optional_): List of stopping tokens to end generation.++### Methods++Refer to [`dspy.OpenAI`](#openai) documentation.\ No newline at end of filediff --git a/api/language_model_clients/_category_.json b/api/language_model_clients/_category_.jsonnew file mode 100644index 000000000..3f6129bae--- /dev/null+++ b/api/language_model_clients/_category_.json@@ -0,0 +1,8 @@+{+ "label": "Language Model API Clients",+ "position": 4,+ "link": {+ "type": "generated-index",+ "description": "This documentation provides an overview of the DSPy Language Model Clients."+ }+}\ No newline at end of filediff --git a/api/hosting_language_models_locally/HFModel.md b/api/local_language_model_clients/HFModel.mdsimilarity index 54%rename from api/hosting_language_models_locally/HFModel.mdrename to api/local_language_model_clients/HFModel.mdindex 52fdf624b..162238ae5 100644--- a/api/hosting_language_models_locally/HFModel.md+++ b/api/local_language_model_clients/HFModel.md@@ -1,5 +1,7 @@+# dspy.HFModel+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 file+```python+llama = dspy.HFModel(model = 'meta-llama/Llama-2-7b-hf')+```\ No newline at end of filediff --git a/api/local_language_model_clients/MLC.md b/api/local_language_model_clients/MLC.mdnew file mode 100644index 000000000..6a36f374b--- /dev/null+++ b/api/local_language_model_clients/MLC.md@@ -0,0 +1,41 @@+# dspy.ChatModuleClient++## Prerequisites++1. Install the required packages using the following commands:++ ```shell+ pip install --no-deps --pre --force-reinstall mlc-ai-nightly-cu118 mlc-chat-nightly-cu118 -f https://mlc.ai/wheels+ pip install transformers+ git lfs install+ ```++ Adjust the pip wheels according to your OS/platform by referring to the provided commands in [MLC packages](https://mlc.ai/package/).++## Running MLC Llama-2 models++1. Create a directory for prebuilt models:++ ```shell+ mkdir -p dist/prebuilt+ ```++2. Clone the necessary libraries from the repository:++ ```shell+ git clone https://github.com/mlc-ai/binary-mlc-llm-libs.git dist/prebuilt/lib+ cd dist/prebuilt+ ```++3. Choose a Llama-2 model from [MLC LLMs](https://huggingface.co/mlc-ai) and clone the model repository:++ ```shell+ git clone https://huggingface.co/mlc-ai/mlc-chat-Llama-2-7b-chat-hf-q4f16_1+ ```++4. Initialize the `ChatModuleClient` within your program with the desired parameters. Here's an example call:++ ```python+ llama = dspy.ChatModuleClient(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')+ ```+Please refer to the [official MLC repository](https://github.com/mlc-ai/mlc-llm) for more detailed information and [documentation](https://mlc.ai/mlc-llm/docs/get_started/try_out.html).diff --git a/api/hosting_language_models_locally/Ollama.md b/api/local_language_model_clients/Ollama.mdsimilarity index 89%rename from api/hosting_language_models_locally/Ollama.mdrename to api/local_language_model_clients/Ollama.mdindex 516489c9d..0f1198ad2 100644--- a/api/hosting_language_models_locally/Ollama.md+++ b/api/local_language_model_clients/Ollama.md@@ -1,6 +1,8 @@-## Running LLMs through Ollama+# dspy.OllamaLocal-#### Adapted from documentation provided by https://github.com/insop+:::note+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.diff --git a/api/hosting_language_models_locally/TGI.md b/api/local_language_model_clients/TGI.mdsimilarity index 51%rename from api/hosting_language_models_locally/TGI.mdrename to api/local_language_model_clients/TGI.mdindex 3ecc6aff6..c67a09beb 100644--- a/api/hosting_language_models_locally/TGI.md+++ b/api/local_language_model_clients/TGI.md@@ -1,42 +1,42 @@-## Launching a Text Generation Inference (TGI) Server+# dspy.HFClientTGI-### Prerequisites+## Prerequisites- 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/).-### Setting up the Text-Generation-Inference Server+## Setting up the Text-Generation-Inference Server1. Clone the Text-Generation-Inference repository from GitHub by executing the following command:-```bash-git clone https://github.com/huggingface/text-generation-inference.git-```+ ```+ git clone https://github.com/huggingface/text-generation-inference.git+ ```2. Change into the cloned repository directory:-```bash-cd text-generation-inference-```+ ```+ cd text-generation-inference+ ```3. Execute the Docker command under the "Get Started" section to run the server:-```bash-model=mosaicml/mpt-30b # 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+ ```+ 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:latest --model-id $model --num-shard $num_shard-```+ 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`.+ This command will start the server and make it accessible at `http://localhost:8080`.-If you want to connect to private HuggingFace models such as [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.+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.-```bash-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+```+ 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```-### Sending requests to the server+## Sending requests to the serverAfter 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`.@@ -57,4 +57,4 @@ Initialize the `HFClientTGI` within your program with the desired parameters. He- `--max-input-length`: Set the maximum allowed input length for the text.- `--max-total-tokens`: Set the maximum total tokens allowed for text generation.-Please refer to the [official TGI repository](https://github.com/huggingface/text-generation-inference) for detailed docs.+Please refer to the [official Text-Generation-Inference repository](https://github.com/huggingface/text-generation-inference) for more detailed information and documentation.diff --git a/api/local_language_model_clients/_category_.json b/api/local_language_model_clients/_category_.jsonnew file mode 100644index 000000000..8965dcf41--- /dev/null+++ b/api/local_language_model_clients/_category_.json@@ -0,0 +1,8 @@+{+ "label": "Local Language Model Clients",+ "position": 6,+ "link": {+ "type": "generated-index",+ "description": "DSPy supports various methods including `built-in wrappers`, `server integration`, and `external package integration` for model loading. This documentation provides a concise introduction on how to load in models within DSPy extending these capabilities for your specific needs."+ }+}\ No newline at end of filediff --git a/api/hosting_language_models_locally/vLLM.md b/api/local_language_model_clients/vLLM.mdsimilarity index 97%rename from api/hosting_language_models_locally/vLLM.mdrename to api/local_language_model_clients/vLLM.mdindex 4ac911f85..bd9befb9f 100644--- a/api/hosting_language_models_locally/vLLM.md+++ b/api/local_language_model_clients/vLLM.md@@ -1,4 +1,4 @@-## Launching a vLLM Server+# dspy.HFClientVLLM### Setting up the vLLM Serverdiff --git a/api/modules/ChainOfThought.md b/api/modules/ChainOfThought.mdindex f17919fa7..ab9bd0e5f 100644--- a/api/modules/ChainOfThought.md+++ b/api/modules/ChainOfThought.md@@ -1,5 +1,7 @@# dspy.ChainOfThought+### Constructor+The constructor initializes the `ChainOfThought` class and sets up its attributes. It inherits from the `Predict` class and adds specific functionality for chain of thought processing.Internally, the class initializes the `activated` attribute to indicate if chain of thought processing has been selected. It extends the `signature` to include additional reasoning steps and an updated `rationale_type` when chain of thought processing is activated.diff --git a/api/modules/_category_.json b/api/modules/_category_.jsonindex 3488b4208..5cf44ce64 100644--- a/api/modules/_category_.json+++ b/api/modules/_category_.json@@ -1,6 +1,6 @@{"label": "Modules",- "position": 3,+ "position": 1,"link": {"type": "generated-index","description": "Modules in DSPy"diff --git a/api/optimizers/BootstrapFewShot.md b/api/optimizers/BootstrapFewShot.mdnew file mode 100644index 000000000..14b2deff5--- /dev/null+++ b/api/optimizers/BootstrapFewShot.md@@ -0,0 +1,63 @@+---+sidebar_position: 2+---++# teleprompt.BootstrapFewShot++### Constructor++The constructor initializes the `BootstrapFewShot` class and sets up parameters for bootstrapping.++```python+class BootstrapFewShot(Teleprompter):+ def __init__(self, metric=None, teacher_settings={}, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1):+ self.metric = metric+ self.teacher_settings = teacher_settings++ self.max_bootstrapped_demos = max_bootstrapped_demos+ self.max_labeled_demos = max_labeled_demos+ self.max_rounds = max_rounds+```++**Parameters:**+- `metric` (_callable_, _optional_): Metric function to evaluate examples during bootstrapping. Defaults to `None`.+- `teacher_settings` (_dict_, _optional_): Settings for teacher predictor. Defaults to empty dictionary.+- `max_bootstrapped_demos` (_int_, _optional_): Maximum number of bootstrapped demonstrations per predictor. Defaults to 4.+- `max_labeled_demos` (_int_, _optional_): Maximum number of labeled demonstrations per predictor. Defaults to 16.+- `max_rounds` (_int_, _optional_): Maximum number of bootstrapping rounds. Defaults to 1.++### Method++#### `compile(self, student, *, teacher=None, trainset, valset=None)`++This method compiles the BootstrapFewShot instance by performing bootstrapping to refine the student predictor.++This process includes preparing the student and teacher predictors, which involves creating predictor copies, verifying the student predictor is uncompiled, and compiling the teacher predictor with labeled demonstrations via LabeledFewShot if the teacher predictor hasn't been compiled.++The next stage involves preparing predictor mappings by validating that both the student and teacher predictors have the same program structure and the same signatures but are different objects.++The final stage is performing the bootstrapping iterations.++**Parameters:**+- `student` (_Teleprompter_): Student predictor to be compiled.+- `teacher` (_Teleprompter_, _optional_): Teacher predictor used for bootstrapping. Defaults to `None`.+- `trainset` (_list_): Training dataset used in bootstrapping.+- `valset` (_list_, _optional_): Validation dataset used in compilation. Defaults to `None`.++**Returns:**+- The compiled `student` predictor after bootstrapping with refined demonstrations.++### Example++```python+#Assume defined trainset+#Assume defined RAG class+...++#Define teleprompter and include teacher+teacher = dspy.OpenAI(model='gpt-3.5-turbo', api_key = openai.api_key, api_provider = "openai", model_type = "chat")+teleprompter = BootstrapFewShot(teacher_settings=dict({'lm': teacher}))++# Compile!+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset)+```diff --git a/api/optimizers/BootstrapFewShotWithRandomSearch.md b/api/optimizers/BootstrapFewShotWithRandomSearch.mdnew file mode 100644index 000000000..dd007b10e--- /dev/null+++ b/api/optimizers/BootstrapFewShotWithRandomSearch.md@@ -0,0 +1,59 @@+---+sidebar_position: 4+---++# teleprompt.BootstrapFewShotWithRandomSearch++### Constructor++The constructor initializes the `BootstrapFewShotWithRandomSearch` class and sets up its attributes. It inherits from the `BootstrapFewShot` class and introduces additional attributes for the random search process.++```python+class BootstrapFewShotWithRandomSearch(BootstrapFewShot):+ def __init__(self, metric, teacher_settings={}, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, num_candidate_programs=16, num_threads=6):+ self.metric = metric+ self.teacher_settings = teacher_settings+ self.max_rounds = max_rounds++ self.num_threads = num_threads++ self.min_num_samples = 1+ self.max_num_samples = max_bootstrapped_demos+ self.num_candidate_sets = num_candidate_programs+ self.max_num_traces = 1 + int(max_bootstrapped_demos / 2.0 * self.num_candidate_sets)++ self.max_bootstrapped_demos = self.max_num_traces+ self.max_labeled_demos = max_labeled_demos++ print("Going to sample between", self.min_num_samples, "and", self.max_num_samples, "traces per predictor.")+ print("Going to sample", self.max_num_traces, "traces in total.")+ print("Will attempt to train", self.num_candidate_sets, "candidate sets.")+```++**Parameters:**+- `metric` (_callable_, _optional_): Metric function to evaluate examples during bootstrapping. Defaults to `None`.+- `teacher_settings` (_dict_, _optional_): Settings for teacher predictor. Defaults to empty dictionary.+- `max_bootstrapped_demos` (_int_, _optional_): Maximum number of bootstrapped demonstrations per predictor. Defaults to 4.+- `max_labeled_demos` (_int_, _optional_): Maximum number of labeled demonstrations per predictor. Defaults to 16.+- `max_rounds` (_int_, _optional_): Maximum number of bootstrapping rounds. Defaults to 1.+- `num_candidate_programs` (_int_): Number of candidate programs to generate during random search.+- `num_threads` (_int_): Number of threads used for evaluation during random search.++### Method++Refer to [teleprompt.BootstrapFewShot](#telepromptbootstrapfewshot) documentation.++## Example++```python+#Assume defined trainset+#Assume defined RAG class+...++#Define teleprompter and include teacher+teacher = dspy.OpenAI(model='gpt-3.5-turbo', api_key = openai.api_key, api_provider = "openai", model_type = "chat")+teleprompter = BootstrapFewShotWithRandomSearch(teacher_settings=dict({'lm': teacher}))++# Compile!+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset)+```\ No newline at end of filediff --git a/api/optimizers/BootstrapFinetune.md b/api/optimizers/BootstrapFinetune.mdnew file mode 100644index 000000000..86540aa46--- /dev/null+++ b/api/optimizers/BootstrapFinetune.md@@ -0,0 +1,56 @@+---+sidebar_position: 5+---++# teleprompt.BootstrapFinetune++### Constructor++### `__init__(self, metric=None, teacher_settings={}, multitask=True)`++The constructor initializes a `BootstrapFinetune` instance and sets up its attributes. It defines the teleprompter as a `BootstrapFewShot` instance for the finetuning compilation.++```python+class BootstrapFinetune(Teleprompter):+ def __init__(self, metric=None, teacher_settings={}, multitask=True):+```++**Parameters:**+- `metric` (_callable_, _optional_): Metric function to evaluate examples during bootstrapping. Defaults to `None`.+- `teacher_settings` (_dict_, _optional_): Settings for teacher predictor. Defaults to empty dictionary.+- `multitask` (_bool_, _optional_): Enable multitask fine-tuning. Defaults to `True`.++### Method++#### `compile(self, student, *, teacher=None, trainset, valset=None, target='t5-large', bsize=12, accumsteps=1, lr=5e-5, epochs=1, bf16=False)`++This method first compiles for bootstrapping with the `BootstrapFewShot` teleprompter. It then prepares fine-tuning data by generating prompt-completion pairs for training and performs finetuning. After compilation, the LMs are set to the finetuned models and the method returns a compiled and fine-tuned predictor.++**Parameters:**+- `student` (_Predict_): Student predictor to be fine-tuned.+- `teacher` (_Predict_, _optional_): Teacher predictor to help with fine-tuning. Defaults to `None`.+- `trainset` (_list_): Training dataset for fine-tuning.+- `valset` (_list_, _optional_): Validation dataset for fine-tuning. Defaults to `None`.+- `target` (_str_, _optional_): Target model for fine-tuning. Defaults to `'t5-large'`.+- `bsize` (_int_, _optional_): Batch size for training. Defaults to `12`.+- `accumsteps` (_int_, _optional_): Gradient accumulation steps. Defaults to `1`.+- `lr` (_float_, _optional_): Learning rate for fine-tuning. Defaults to `5e-5`.+- `epochs` (_int_, _optional_): Number of training epochs. Defaults to `1`.+- `bf16` (_bool_, _optional_): Enable mixed-precision training with BF16. Defaults to `False`.++**Returns:**+- `compiled2` (_Predict_): A compiled and fine-tuned `Predict` instance.++### Example++```python+#Assume defined trainset+#Assume defined RAG class+...++#Define teleprompter+teleprompter = BootstrapFinetune(teacher_settings=dict({'lm': teacher}))++# Compile!+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset, target='google/flan-t5-base')+```\ No newline at end of filediff --git a/api/optimizers/Ensemble.md b/api/optimizers/Ensemble.mdnew file mode 100644index 000000000..42dbc0dde--- /dev/null+++ b/api/optimizers/Ensemble.md@@ -0,0 +1,47 @@+---+sidebar_position: 3+---++# teleprompt.Ensemble++### Constructor++The constructor initializes the `Ensemble` class and sets up its attributes. This teleprompter is designed to create ensembled versions of multiple programs, reducing various outputs from different programs into a single output.++```python+class Ensemble(Teleprompter):+ def __init__(self, *, reduce_fn=None, size=None, deterministic=False):+```++**Parameters:**+- `reduce_fn` (_callable_, _optional_): Function used to reduce multiple outputs from different programs into a single output. A common choice is `dspy.majority`. Defaults to `None`.+- `size` (_int_, _optional_): Number of programs to randomly select for ensembling. If not specified, all programs will be used. Defaults to `None`.+- `deterministic` (_bool_, _optional_): Specifies whether ensemble should operate deterministically. Currently, setting this to `True` will raise an error as this feature is pending implementation. Defaults to `False`.++### Method++#### `compile(self, programs)`++This method compiles an ensemble of programs into a single program that when run, can either randomly sample a subset of the given programs to produce outputs or use all of them. The multiple outputs can then be reduced into a single output using the `reduce_fn`.++**Parameters:**+- `programs` (_list_): List of programs to be ensembled.++**Returns:**+- `EnsembledProgram` (_Module_): An ensembled version of the input programs.++### Example++```python+import dspy+from dspy.teleprompt import Ensemble++# Assume a list of programs+programs = [program1, program2, program3, ...]++# Define Ensemble teleprompter+teleprompter = Ensemble(reduce_fn=dspy.majority, size=2)++# Compile to get the EnsembledProgram+ensembled_program = teleprompter.compile(programs)+```\ No newline at end of filediff --git a/api/optimizers/LabeledFewShot.md b/api/optimizers/LabeledFewShot.mdnew file mode 100644index 000000000..d58f688aa--- /dev/null+++ b/api/optimizers/LabeledFewShot.md@@ -0,0 +1,58 @@+---+sidebar_position: 1+---++# teleprompt.LabeledFewShot++### Constructor++The constructor initializes the `LabeledFewShot` class and sets up its attributes, particularly defining `k` number of samples to be used by the predictor.++```python+class LabeledFewShot(Teleprompter):+ def __init__(self, k=16):+ self.k = k+```++**Parameters:**+- `k` (_int_): Number of samples to be used for each predictor. Defaults to 16.++### Method++#### `compile(self, student, *, trainset)`++This method compiles the `LabeledFewShot` instance by configuring the `student` predictor. It assigns subsets of the `trainset` in each student's predictor's `demos` attribute. If the `trainset` is empty, the method returns the original `student`.++**Parameters:**+- `student` (_Teleprompter_): Student predictor to be compiled.+- `trainset` (_list_): Training dataset for compiling with student predictor.++**Returns:**+- The compiled `student` predictor with assigned training samples for each predictor or the original `student` if the `trainset` is empty.++### Example++```python+import dspy++#Assume defined trainset+class RAG(dspy.Module):+ def __init__(self, num_passages=3):+ super().__init__()++ #declare retrieval and predictor modules+ self.retrieve = dspy.Retrieve(k=num_passages)+ self.generate_answer = dspy.ChainOfThought(GenerateAnswer)++ #flow for answering questions using predictor and retrieval modules+ def forward(self, question):+ context = self.retrieve(question).passages+ prediction = self.generate_answer(context=context, question=question)+ return dspy.Prediction(context=context, answer=prediction.answer)++#Define teleprompter+teleprompter = LabeledFewShot()++# Compile!+compiled_rag = teleprompter.compile(student=RAG(), trainset=trainset)+```\ No newline at end of filediff --git a/api/optimizers/_category_.json b/api/optimizers/_category_.jsonnew file mode 100644index 000000000..5d7edc9df--- /dev/null+++ b/api/optimizers/_category_.json@@ -0,0 +1,8 @@+{+ "label": "Optimizers",+ "position": 2,+ "link": {+ "type": "generated-index",+ "description": "Teleprompters are powerful optimizers (included in DSPy) 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.)\n\nThis documentation provides an overview of the DSPy Teleprompters."+ }+}\ No newline at end of filediff --git a/api/retrieval_model_clients/AzureCognitiveSearch.md b/api/retrieval_model_clients/AzureCognitiveSearch.mdnew file mode 100644index 000000000..b8c353f31--- /dev/null+++ b/api/retrieval_model_clients/AzureCognitiveSearch.md@@ -0,0 +1,34 @@+---+sidebar_position: 3+---++# retrieve.AzureCognitiveSearch++### Constructor++The constructor initializes an instance of the `AzureCognitiveSearch` class and sets up parameters for sending queries and retreiving results with the Azure Cognitive Search server.++```python+class AzureCognitiveSearch:+ def __init__(+ self,+ search_service_name: str,+ search_api_key: str,+ search_index_name: str,+ field_text: str,+ field_score: str, # required field to map with "score" field in dsp framework+ ):+```++**Parameters:**+- `search_service_name` (_str_): Name of Azure Cognitive Search server.+- `search_api_key` (_str_): API Authentication token for accessing Azure Cognitive Search server.+- `search_index_name` (_str_): Name of search index in the Azure Cognitive Search server.+- `field_text` (_str_): Field name that maps to DSP "content" field.+- `field_score` (_str_): Field name that maps to DSP "score" field.++### Methods++Refer to [ColBERTv2](/api/retrieval_model_clients/ColBERTv2) documentation. Keep in mind there is no `simplify` flag for AzureCognitiveSearch.++AzureCognitiveSearch supports sending queries and processing the received results, mapping content and scores to a correct format for the Azure Cognitive Search server.\ No newline at end of filediff --git a/api/retrieval_model_clients/ChromadbRM.md b/api/retrieval_model_clients/ChromadbRM.mdnew file mode 100644index 000000000..9b40759a5--- /dev/null+++ b/api/retrieval_model_clients/ChromadbRM.md@@ -0,0 +1,65 @@+---+sidebar_position: 2+---++# retrieve.ChromadbRM++### Constructor++Initialize 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).++```python+ChromadbRM(+ collection_name: str,+ persist_directory: str,+ embedding_function: Optional[EmbeddingFunction[Embeddable]] = OpenAIEmbeddingFunction(),+ k: int = 7,+)+```++**Parameters:**+- `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.++### Methods++#### `forward(self, query_or_queries: Union[str, List[str]], k: Optional[int] = None) -> dspy.Prediction`++Search the chromadb collection for the top `k` passages matching the given query or queries, using embeddings generated via the specified `embedding_function`.++**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.++### Quickstart with OpenAI Embeddings++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.++```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 filediff --git a/api/retrieval_model_clients/ColBERTv2.md b/api/retrieval_model_clients/ColBERTv2.mdnew file mode 100644index 000000000..2dd31bef8--- /dev/null+++ b/api/retrieval_model_clients/ColBERTv2.md@@ -0,0 +1,51 @@+---+sidebar_position: 1+---++# dspy.ColBERTv2++### Constructor++The constructor initializes the `ColBERTv2` class instance and sets up the request parameters for interacting with the ColBERTv2 server.++```python+class ColBERTv2:+ def __init__(+ self,+ url: str = "http://0.0.0.0",+ port: Optional[Union[str, int]] = None,+ post_requests: bool = False,+ ):+```++**Parameters:**+- `url` (_str_): URL for ColBERTv2 server.+- `port` (_Union[str, int]_, _Optional_): Port endpoint for ColBERTv2 server. Defaults to `None`.+- `post_requests` (_bool_, _Optional_): Flag for using HTTP POST requests. Defaults to `False`.++### Methods++#### `__call__(self, query: str, k: int = 10, simplify: bool = False) -> Union[list[str], list[dotdict]]`++Enables making queries to the ColBERTv2 server for retrieval. Internally, the method handles the specifics of preparing the request prompt and corresponding payload to obtain the response. The function handles the retrieval of the top-k passages based on the provided query.++**Parameters:**+- `query` (_str_): Query string used for retrieval.+- `k` (_int_, _optional_): Number of passages to retrieve. Defaults to 10.+- `simplify` (_bool_, _optional_): Flag for simplifying output to a list of strings. Defaults to False.++**Returns:**+- `Union[list[str], list[dotdict]]`: Depending on `simplify` flag, either a list of strings representing the passage content (`True`) or a list of `dotdict` instances containing passage details (`False`).++### Quickstart++```python+import dspy++colbertv2_wiki17_abstracts = dspy.ColBERTv2(url='http://20.102.90.50:2017/wiki17_abstracts')++retrieval_response = colbertv2_wiki17_abstracts('When was the first FIFA World Cup held?', k=5)++for result in retrieval_response:+ print("Text:", result['text'], "\n")+```diff --git a/api/retrieval_model_clients/FaissRM.md b/api/retrieval_model_clients/FaissRM.mdnew file mode 100644index 000000000..2ef9dadc1--- /dev/null+++ b/api/retrieval_model_clients/FaissRM.md@@ -0,0 +1,62 @@+---+sidebar_position: 4+---++# retrieve.FaissRM++### Constructor++Initialize an instance of FaissRM by providing it with a vectorizer and a list of strings++```python+FaissRM(+ document_chunks: List[str],+ vectorizer: dsp.modules.sentence_vectorizer.BaseSentenceVectorizer,+ k: int = 3+)+```++**Parameters:**+- `document_chunks` (_List[str]_): a list of strings that comprises the corpus to search. You cannot add/insert/upsert to this list after creating this FaissRM object.+- `vectorizer` (_dsp.modules.sentence_vectorizer.BaseSentenceVectorizer_, _optional_): If not provided, a dsp.modules.sentence_vectorizer.SentenceTransformersVectorizer object is created and used.+- `k` (_int_, _optional_): The number of top passages to retrieve. Defaults to 3.++### Methods++#### `forward(self, query_or_queries: Union[str, List[str]]) -> dspy.Prediction`++Search the FaissRM vector database for the top `k` passages matching the given query or queries, using embeddings generated via the vectorizer specified at FaissRM construction time++**Parameters:**+- `query_or_queries` (_Union[str, List[str]]_): The query or list of queries to search for.++**Returns:**+- `dspy.Prediction`: Contains the retrieved passages, each represented as a `dotdict` with a `long_text` attribute and an `index` attribute. The `index` attribute is the index in the document_chunks array provided to this FaissRM object at construction time.++### Quickstart with the default vectorizer++The **FaissRM** module provides a retriever that uses an in-memory Faiss vector database. This module does not include a vectorizer; instead it supports any subclass of **dsp.modules.sentence_vectorizer.BaseSentenceVectorizer**. If a vectorizer is not provided, an instance of **dsp.modules.sentence_vectorizer.SentenceTransformersVectorizer** is created and used by **FaissRM**. Note that the default embedding model for **SentenceTransformersVectorizer** is **all-MiniLM-L6-v2**+++```python+import dspy+from dspy.retrieve import FaissRM++document_chunks = [+ "The superbowl this year was played between the San Francisco 49ers and the Kanasas City Chiefs",+ "Pop corn is often served in a bowl",+ "The Rice Bowl is a Chinese Restaurant located in the city of Tucson, Arizona",+ "Mars is the fourth planet in the Solar System",+ "An aquarium is a place where children can learn about marine life",+ "The capital of the United States is Washington, D.C",+ "Rock and Roll musicians are honored by being inducted in the Rock and Roll Hall of Fame",+ "Music albums were published on Long Play Records in the 70s and 80s",+ "Sichuan cuisine is a spicy cuisine from central China",+ "The interest rates for mortgages is considered to be very high in 2024",+]++frm = FaissRM(document_chunks)+turbo = dspy.OpenAI(model="gpt-3.5-turbo")+dspy.settings.configure(lm=turbo, rm=frm)+print(frm(["I am in the mood for Chinese food"]))+```\ No newline at end of filediff --git a/api/retrieval_model_clients/_category_.json b/api/retrieval_model_clients/_category_.jsonnew file mode 100644index 000000000..0c3ec89a3--- /dev/null+++ b/api/retrieval_model_clients/_category_.json@@ -0,0 +1,8 @@+{+ "label": "Retrieval Model Clients",+ "position": 3,+ "link": {+ "type": "generated-index",+ "description": "This documentation provides an overview of the DSPy Retrieval Model Clients."+ }+}\ No newline at end of filediff --git a/docs/building-blocks/1-language_models.md b/docs/building-blocks/1-language_models.mdindex 1457f6cac..ee41e6d66 100644--- a/docs/building-blocks/1-language_models.md+++ b/docs/building-blocks/1-language_models.md@@ -141,31 +141,31 @@ lm = dspy.{provider_listed_below}(model="your model", model_request_kwargs="..."You need to host these models on your own GPU(s). Below, we include pointers for how to do that.-1. `dspy.HFClientTGI`: for HuggingFace models through the Text Generation Inference (TGI) system. [Tutorial: How do I install and launch the TGI server?](/api/hosting_language_models_locally/TGI)+1. `dspy.HFClientTGI`: for HuggingFace models through the Text Generation Inference (TGI) system. [Tutorial: How do I install and launch the TGI server?](/api/local_language_model_clients/TGI)```pythontgi_llama2 = dspy.HFClientTGI(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")```-2. `dspy.HFClientVLLM`: for HuggingFace models through vLLM. [Tutorial: How do I install and launch the vLLM server?](/api/hosting_language_models_locally/vLLM)+2. `dspy.HFClientVLLM`: for HuggingFace models through vLLM. [Tutorial: How do I install and launch the vLLM server?](/api/local_language_model_clients/vLLM)```pythonvllm_llama2 = dspy.HFClientVLLM(model="meta-llama/Llama-2-7b-hf", port=8080, url="http://localhost")```-3. `dspy.HFModel` (experimental) [Tutorial: How do I initialize models using HFModel](/api/hosting_language_models_locally/HFModel)+3. `dspy.HFModel` (experimental) [Tutorial: How do I initialize models using HFModel](/api/local_language_model_clients/HFModel)```pythonllama = dspy.HFModel(model = 'meta-llama/Llama-2-7b-hf')```-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?](/api/hosting_language_models_locally/Ollama)\n",+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?](/api/local_language_model_clients/Ollama)\n",```pythonmistral_ollama = dspy.OllamaLocal(model='mistral')```-5. `dspy.ChatModuleClient` (experimental): [How do I install and use MLC?](/api/hosting_language_models_locally/MLC)+5. `dspy.ChatModuleClient` (experimental): [How do I install and use MLC?](/api/local_language_model_clients/MLC)```pythonmodel = 'dist/prebuilt/mlc-chat-Llama-2-7b-chat-hf-q4f16_1'diff --git a/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdx b/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdxindex 0a0f4531b..2550ed3c5 100644--- a/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdx+++ b/docs/deep-dive/language_model_clients/local_models/HFClientTGI.mdx@@ -4,7 +4,7 @@ import AuthorDetails from '@site/src/components/AuthorDetails';### Prerequisites - Launching TGI Server locally-Refer to the [Text Generation-Inference Server API](/api/hosting_language_models_locally/TGI) for setting up the TGI server locally.+Refer to the [Text Generation-Inference Server API](/api/local_language_model_clients/TGI) for setting up the TGI server locally.```bash#Example TGI Server Launchdiff --git a/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdx b/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdxindex 66eb63f1d..059c2a9be 100644--- a/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdx+++ b/docs/deep-dive/language_model_clients/local_models/HFClientVLLM.mdx@@ -4,7 +4,7 @@ import AuthorDetails from '@site/src/components/AuthorDetails';### Prerequisites - Launching vLLM Server locally-Refer to the [vLLM Server API](/api/hosting_language_models_locally/vLLM) for setting up the vLLM server locally.+Refer to the [vLLM Server API](/api/local_language_model_clients/vLLM) for setting up the vLLM server locally.```bash#Example vLLM Server Launch