-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
WIP - dspy.RM/retrieve refactor #1739
Open
arnavsinghvi11
wants to merge
4
commits into
main
Choose a base branch
from
retrieve_refactor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5dc5c6b
wip - dspy.RM/retrieve refactor
arnavsinghvi11 7625b31
Merge remote-tracking branch 'origin/main' into retrieve_refactor
arnavsinghvi11 d69acdd
update dspy.Retrieve interface
arnavsinghvi11 fdfa1f1
updated dspy.Retriever interface
arnavsinghvi11 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
from .lm import LM | ||
from .lm import LM | ||
from .rm import RM |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
from typing import Any, Callable, List, Optional | ||
|
||
from dspy.primitives.prediction import Prediction | ||
from dspy.retrieve.embedder import Embedder | ||
|
||
class RM: | ||
def __init__( | ||
self, | ||
search_function: Callable[..., Any], | ||
embedder: Optional[Embedder] = None, | ||
result_formatter: Optional[Callable[[Any], Prediction]] = None, | ||
**provider_kwargs | ||
): | ||
self.embedder = embedder | ||
self.search_function = search_function | ||
self.result_formatter = result_formatter or self.default_formatter | ||
self.provider_kwargs = provider_kwargs | ||
|
||
def __call__(self, query: str, k: Optional[int] = None) -> Prediction: | ||
if self.embedder: | ||
query_vector = self.embedder([query])[0] | ||
query_input = query_vector | ||
else: | ||
query_input = query | ||
search_args = self.provider_kwargs.copy() | ||
search_args['query'] = query_input | ||
if k is not None: | ||
search_args['k'] = k | ||
results = self.search_function(**search_args) | ||
return self.result_formatter(results) | ||
|
||
def default_formatter(self, results) -> Prediction: | ||
return Prediction(passages=results) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
from .retrieve import Retrieve, RetrieveThenRerank | ||
from .retrieve import Retrieve, RetrieveThenRerank | ||
from .embedder import Embedder |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
from typing import Callable, List, Optional | ||
|
||
|
||
class Embedder: | ||
def __init__(self, embedding_model: str = 'text-embedding-ada-002', embedding_function: Optional[Callable[[List[str]], List[List[float]]]] = None): | ||
self.embedding_model = embedding_model | ||
self.embedding_function = embedding_function or self.default_embedding_function | ||
|
||
def default_embedding_function(self, texts: List[str]) -> List[List[float]]: | ||
from litellm import embedding | ||
embeddings_response = embedding(model=self.embedding_model, input=texts) | ||
embeddings = [data['embedding'] for data in embeddings_response.data] | ||
return embeddings | ||
|
||
def __call__(self, texts: List[str]) -> List[List[float]]: | ||
return self.embedding_function(texts) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"{DSPy.RM Migration - TBD}" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"#Querying ColBERTv2 \n", | ||
"\n", | ||
"import requests\n", | ||
"import os\n", | ||
"from typing import Any, Dict, List, Optional, Union\n", | ||
"from dspy import RM, Retrieve, Embedder\n", | ||
"from dspy.primitives.prediction import Prediction\n", | ||
"\n", | ||
"def colbert_search_function(query: str, k: int, url: str, post_requests: bool = False) -> List[Dict[str, Any]]:\n", | ||
" if post_requests:\n", | ||
" headers = {\"Content-Type\": \"application/json; charset=utf-8\"}\n", | ||
" payload = {\"query\": query, \"k\": k}\n", | ||
" res = requests.post(url, json=payload, headers=headers, timeout=10)\n", | ||
" else:\n", | ||
" payload = {\"query\": query, \"k\": k}\n", | ||
" res = requests.get(url, params=payload, timeout=10)\n", | ||
" \n", | ||
" res.raise_for_status()\n", | ||
" topk = res.json()[\"topk\"][:k]\n", | ||
" topk = [{**doc, \"long_text\": doc.get(\"text\", \"\")} for doc in topk]\n", | ||
" return topk\n", | ||
"\n", | ||
"def colbert_result_formatter(results: List[Dict[str, Any]]) -> Prediction:\n", | ||
" passages = [doc[\"long_text\"] for doc in results]\n", | ||
" return Prediction(passages=passages)\n", | ||
"\n", | ||
"colbert_url = \"http://20.102.90.50:2017/wiki17_abstracts\"\n", | ||
"\n", | ||
"colbert_rm = RM(\n", | ||
" search_function=colbert_search_function,\n", | ||
" result_formatter=colbert_result_formatter,\n", | ||
" url=colbert_url,\n", | ||
" post_requests=False\n", | ||
")\n", | ||
"\n", | ||
"retrieve = Retrieve(rm=colbert_rm, k=10)\n", | ||
"query_text = \"Example query text\"\n", | ||
"results = retrieve(query_text)\n", | ||
"print(results.passages)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"#Querying Databricks Mosaic AI Vector Search \n", | ||
"\n", | ||
"#client setup\n", | ||
"databricks_token = os.environ.get(\"DATABRICKS_TOKEN\")\n", | ||
"databricks_endpoint = os.environ.get(\"DATABRICKS_HOST\")\n", | ||
"databricks_client = WorkspaceClient(host=databricks_endpoint, token=databricks_token)\n", | ||
"\n", | ||
"#custom logic for querying and sorting the docs\n", | ||
"def databricks_search_function(\n", | ||
" query,\n", | ||
" k,\n", | ||
" index_name,\n", | ||
" columns,\n", | ||
" query_type='ANN',\n", | ||
" filters_json=None,\n", | ||
" client=None\n", | ||
"):\n", | ||
" results = client.vector_search_indexes.query(\n", | ||
" index_name=index_name,\n", | ||
" query_type=query_type,\n", | ||
" query_text=query,\n", | ||
" num_results=k,\n", | ||
" columns=columns,\n", | ||
" filters_json=filters_json,\n", | ||
" ).as_dict()\n", | ||
"\n", | ||
" items = []\n", | ||
" col_names = [column[\"name\"] for column in results[\"manifest\"][\"columns\"]]\n", | ||
" for data_row in results[\"result\"][\"data_array\"]:\n", | ||
" item = {col_name: val for col_name, val in zip(col_names, data_row)}\n", | ||
" items.append(item)\n", | ||
" sorted_docs = sorted(items, key=lambda x: x[\"score\"], reverse=True)\n", | ||
" return sorted_docs\n", | ||
"\n", | ||
"def databricks_result_formatter(results) -> Prediction:\n", | ||
" passages = [doc['some_text_column'] for doc in results] \n", | ||
" return Prediction(passages=passages)\n", | ||
"\n", | ||
"databricks_rm = RM(\n", | ||
" search_function=databricks_search_function,\n", | ||
" result_formatter=databricks_result_formatter,\n", | ||
" client=databricks_client,\n", | ||
" index_name='your_index_name',\n", | ||
" columns=['id', 'some_text_column'],\n", | ||
" filters_json=None\n", | ||
")\n", | ||
"\n", | ||
"retrieve = Retrieve(rm=databricks_rm, k=3)\n", | ||
"results = retrieve(\"Example query text\")\n", | ||
"print(results.passages)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"#Querying Deeplake Vector Store\n", | ||
"\n", | ||
"embedder = Embedder()\n", | ||
"\n", | ||
"deeplake_vectorstore_name = 'vectorstore_name'\n", | ||
"deeplake_client = deeplake.VectorStore(\n", | ||
" path=deeplake_vectorstore_name,\n", | ||
" embedding_function=embedder\n", | ||
")\n", | ||
"\n", | ||
"def deeplake_search_function(query, k, client=None):\n", | ||
" results = client.search(query, k=k)\n", | ||
" return results\n", | ||
"\n", | ||
"def deeplake_result_formatter(results) -> Prediction:\n", | ||
" passages = [doc['text'] for doc in results['documents']]\n", | ||
" return Prediction(passages=passages)\n", | ||
"\n", | ||
"\n", | ||
"deeplake_rm = RM(\n", | ||
" embedder=embedder,\n", | ||
" search_function=deeplake_search_function,\n", | ||
" result_formatter=deeplake_result_formatter,\n", | ||
" client=deeplake_client\n", | ||
")\n", | ||
"\n", | ||
"retrieve = Retrieve(rm=deeplake_rm, k=3)\n", | ||
"results = retrieve(\"some text\")\n", | ||
"print(results.passages)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"TBD..." | ||
] | ||
} | ||
], | ||
"metadata": { | ||
"language_info": { | ||
"name": "python" | ||
} | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 2 | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#1735 will go here once merged @chenmoneygithub