langchain/libs/community/langchain_community/utilities/mojeek_search.py
Erick Friis c2a3021bb0
multiple: pydantic 2 compatibility, v0.3 (#26443)
Signed-off-by: ChengZi <chen.zhang@zilliz.com>
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
Co-authored-by: Bagatur <22008038+baskaryan@users.noreply.github.com>
Co-authored-by: Dan O'Donovan <dan.odonovan@gmail.com>
Co-authored-by: Tom Daniel Grande <tomdgrande@gmail.com>
Co-authored-by: Grande <Tom.Daniel.Grande@statsbygg.no>
Co-authored-by: Bagatur <baskaryan@gmail.com>
Co-authored-by: ccurme <chester.curme@gmail.com>
Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
Co-authored-by: Tomaz Bratanic <bratanic.tomaz@gmail.com>
Co-authored-by: ZhangShenao <15201440436@163.com>
Co-authored-by: Friso H. Kingma <fhkingma@gmail.com>
Co-authored-by: ChengZi <chen.zhang@zilliz.com>
Co-authored-by: Nuno Campos <nuno@langchain.dev>
Co-authored-by: Morgante Pell <morgantep@google.com>
2024-09-13 14:38:45 -07:00

45 lines
1.3 KiB
Python

import json
from typing import List
import requests
from pydantic import BaseModel, Field
class MojeekSearchAPIWrapper(BaseModel):
api_key: str
search_kwargs: dict = Field(default_factory=dict)
api_url: str = "https://api.mojeek.com/search"
def run(self, query: str) -> str:
search_results = self._search(query)
results = []
for result in search_results:
title = result.get("title", "")
url = result.get("url", "")
desc = result.get("desc", "")
results.append({"title": title, "url": url, "desc": desc})
return json.dumps(results)
def _search(self, query: str) -> List[dict]:
headers = {
"Accept": "application/json",
}
req = requests.PreparedRequest()
request = {
**self.search_kwargs,
**{"q": query, "fmt": "json", "api_key": self.api_key},
}
req.prepare_url(self.api_url, request)
if req.url is None:
raise ValueError("prepared url is None, this should not happen")
response = requests.get(req.url, headers=headers)
if not response.ok:
raise Exception(f"HTTP error {response.status_code}")
return response.json().get("response", {}).get("results", [])