Skip to content
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

Add support for Bing Seach #1107

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
brave search support
  • Loading branch information
Shangyint committed Jun 19, 2024
commit 1c13fdf81c0c69d9706a77cd158b304446a8f6a7
59 changes: 59 additions & 0 deletions dspy/retrieve/websearch.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import functools
import os
from collections import Counter
from typing import Any, Dict, List, Optional
Expand All @@ -6,8 +7,13 @@
import torch.nn.functional as F
from sentence_transformers import SentenceTransformer

from dsp.modules.cache_utils import CacheMemory, cache_turn_on
import dspy

import json

from dspy.primitives.prediction import Prediction


class BingSearch(dspy.Retrieve):
EMBEDDING_MODEL = "avsolatorio/GIST-small-Embedding-v0"
Expand Down Expand Up @@ -125,3 +131,56 @@ def _get_word_count(self, query: str, snippets: List[str]) -> List[int]:

return word_counts


class BraveSearch(dspy.Retrieve):
"""Set API key in BRAVE_SEARCH_API_KEY"""
api_key: str
base_url: str = "https://api.search.brave.com/res/v1/web/search"

def __init__(self, api_key=None) -> None:
if api_key is None:
api_key = os.environ.get("BRAVE_SEARCH_API_KEY")
if api_key is None:
raise ValueError("BRAVE_SEARCH_API_KEY is not set")

def forward(self, query: str, count=10) -> Prediction:
web_search_results = self._search_request(query=query, count=count)
final_results = [
{
"title": item.get("title"),
"link": item.get("url"),
"snippet": item.get("description"),
}
for item in web_search_results
]
return Prediction(passages=final_results)


# Credit to LangChain
def _search_request(self, query: str, **kwargs) -> List[dict]:
headers = {
"X-Subscription-Token": self.api_key,
"Accept": "application/json",
}
req = requests.PreparedRequest()
params = {**kwargs, **{"q": query}}
req.prepare_url(self.base_url, params)
if req.url is None:
raise ValueError("prepared url is None, this should not happen")

response = cached_brave_search_request_wrapped(req.url, headers)
if not response.ok:
raise Exception(f"HTTP error {response.status_code}")

return response.json().get("web", {}).get("results", [])


@CacheMemory.cache
def cached_brave_search_request(url, header):
response = requests.get(url, headers=header)
return response


@functools.lru_cache(maxsize=None if cache_turn_on else 0)
def cached_brave_search_request_wrapped(url, header):
return cached_brave_search_request(url, header)
Loading