community[minor]: jina search tools integrating (jina reader) (#23339)

- **PR title**: "community: add Jina Search tool"
- **Description:** Added the Jina Search tool for querying the Jina
search API. This includes the implementation of the JinaSearchAPIWrapper
and the JinaSearch tool, along with a Jupyter notebook example
demonstrating its usage.
- **Issue:** N/A
- **Dependencies:** N/A
- **Twitter handle:** [Twitter
handle](https://x.com/yashp3020?t=7wM0gQ7XjGciFoh9xaBtqA&s=09)


- [x] **Add tests and docs**: If you're adding a new integration, please
include
1. an example notebook showing its use. It lives in
`docs/docs/integrations` directory.

- [ ] **Lint and test**: Run `make format`, `make lint` and `make test`
from the root of the package(s) you've modified. See contribution
guidelines for more: https://python.langchain.com/docs/contributing/

---------

Co-authored-by: Bagatur <baskaryan@gmail.com>
Co-authored-by: Chester Curme <chester.curme@gmail.com>
This commit is contained in:
Yash Parmar
2024-09-03 03:22:14 +05:30
committed by GitHub
parent 66828f4ecc
commit 51dae57357
7 changed files with 407 additions and 0 deletions

View File

@@ -0,0 +1,68 @@
import json
from typing import List
import requests
from langchain_core.documents import Document
from langchain_core.pydantic_v1 import BaseModel
from yarl import URL
class JinaSearchAPIWrapper(BaseModel):
"""Wrapper around the Jina search engine."""
base_url: str = "https://s.jina.ai/"
"""The base URL for the Jina search engine."""
def run(self, query: str) -> str:
"""Query the Jina search engine and return the results as a JSON string.
Args:
query: The query to search for.
Returns: The results as a JSON string.
"""
web_search_results = self._search_request(query=query)
final_results = [
{
"title": item.get("title"),
"link": item.get("url"),
"snippet": item.get("description"),
"content": item.get("content"),
}
for item in web_search_results
]
return json.dumps(final_results)
def download_documents(self, query: str) -> List[Document]:
"""Query the Jina search engine and return the results as a list of Documents.
Args:
query: The query to search for.
Returns: The results as a list of Documents.
"""
results = self._search_request(query)
return [
Document(
page_content=item.get("content"), # type: ignore[arg-type]
metadata={
"title": item.get("title"),
"link": item.get("url"),
"description": item.get("description"),
},
)
for item in results
]
def _search_request(self, query: str) -> List[dict]:
headers = {
"Accept": "application/json",
}
url = str(URL(self.base_url + query))
response = requests.get(url, headers=headers)
if not response.ok:
raise Exception(f"HTTP error {response.status_code}")
return response.json().get("data", [])