mirror of
https://github.com/hwchase17/langchain.git
synced 2025-10-29 23:00:18 +00:00
Upgrade to using a literal for specifying the extra which is the
recommended approach in pydantic 2.
This works correctly also in pydantic v1.
```python
from pydantic.v1 import BaseModel
class Foo(BaseModel, extra="forbid"):
x: int
Foo(x=5, y=1)
```
And
```python
from pydantic.v1 import BaseModel
class Foo(BaseModel):
x: int
class Config:
extra = "forbid"
Foo(x=5, y=1)
```
## Enum -> literal using grit pattern:
```
engine marzano(0.1)
language python
or {
`extra=Extra.allow` => `extra="allow"`,
`extra=Extra.forbid` => `extra="forbid"`,
`extra=Extra.ignore` => `extra="ignore"`
}
```
Resorted attributes in config and removed doc-string in case we will
need to deal with going back and forth between pydantic v1 and v2 during
the 0.3 release. (This will reduce merge conflicts.)
## Sort attributes in Config:
```
engine marzano(0.1)
language python
function sort($values) js {
return $values.text.split(',').sort().join("\n");
}
class_definition($name, $body) as $C where {
$name <: `Config`,
$body <: block($statements),
$values = [],
$statements <: some bubble($values) assignment() as $A where {
$values += $A
},
$body => sort($values),
}
```
88 lines
2.9 KiB
Python
88 lines
2.9 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import List, Optional
|
|
|
|
import aiohttp
|
|
import requests
|
|
from langchain_core.callbacks import (
|
|
AsyncCallbackManagerForRetrieverRun,
|
|
CallbackManagerForRetrieverRun,
|
|
)
|
|
from langchain_core.documents import Document
|
|
from langchain_core.retrievers import BaseRetriever
|
|
|
|
|
|
class ChatGPTPluginRetriever(BaseRetriever):
|
|
"""`ChatGPT plugin` retriever."""
|
|
|
|
url: str
|
|
"""URL of the ChatGPT plugin."""
|
|
bearer_token: str
|
|
"""Bearer token for the ChatGPT plugin."""
|
|
top_k: int = 3
|
|
"""Number of documents to return."""
|
|
filter: Optional[dict] = None
|
|
"""Filter to apply to the results."""
|
|
aiosession: Optional[aiohttp.ClientSession] = None
|
|
"""Aiohttp session to use for requests."""
|
|
|
|
class Config:
|
|
arbitrary_types_allowed = True
|
|
|
|
def _get_relevant_documents(
|
|
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
|
|
) -> List[Document]:
|
|
url, json, headers = self._create_request(query)
|
|
response = requests.post(url, json=json, headers=headers)
|
|
results = response.json()["results"][0]["results"]
|
|
docs = []
|
|
for d in results:
|
|
content = d.pop("text")
|
|
metadata = d.pop("metadata", d)
|
|
if metadata.get("source_id"):
|
|
metadata["source"] = metadata.pop("source_id")
|
|
docs.append(Document(page_content=content, metadata=metadata))
|
|
return docs
|
|
|
|
async def _aget_relevant_documents(
|
|
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
|
|
) -> List[Document]:
|
|
url, json, headers = self._create_request(query)
|
|
|
|
if not self.aiosession:
|
|
async with aiohttp.ClientSession() as session:
|
|
async with session.post(url, headers=headers, json=json) as response:
|
|
res = await response.json()
|
|
else:
|
|
async with self.aiosession.post(
|
|
url, headers=headers, json=json
|
|
) as response:
|
|
res = await response.json()
|
|
|
|
results = res["results"][0]["results"]
|
|
docs = []
|
|
for d in results:
|
|
content = d.pop("text")
|
|
metadata = d.pop("metadata", d)
|
|
if metadata.get("source_id"):
|
|
metadata["source"] = metadata.pop("source_id")
|
|
docs.append(Document(page_content=content, metadata=metadata))
|
|
return docs
|
|
|
|
def _create_request(self, query: str) -> tuple[str, dict, dict]:
|
|
url = f"{self.url}/query"
|
|
json = {
|
|
"queries": [
|
|
{
|
|
"query": query,
|
|
"filter": self.filter,
|
|
"top_k": self.top_k,
|
|
}
|
|
]
|
|
}
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"Authorization": f"Bearer {self.bearer_token}",
|
|
}
|
|
return url, json, headers
|