-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
databerry.ts
100 lines (85 loc) · 2.27 KB
/
databerry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import {
BaseRetriever,
type BaseRetrieverInput,
} from "@langchain/core/retrievers";
import { Document } from "@langchain/core/documents";
import {
AsyncCaller,
AsyncCallerParams,
} from "@langchain/core/utils/async_caller";
/**
* Interface for the arguments required to create a new instance of
* DataberryRetriever.
*/
export interface DataberryRetrieverArgs
extends AsyncCallerParams,
BaseRetrieverInput {
datastoreUrl: string;
topK?: number;
apiKey?: string;
}
/**
* Interface for the structure of a Berry object returned by the Databerry
* API.
*/
interface Berry {
text: string;
score: number;
source?: string;
[key: string]: unknown;
}
/**
* A specific implementation of a document retriever for the Databerry
* API. It extends the BaseRetriever class, which is an abstract base
* class for a document retrieval system in LangChain.
*/
/** @deprecated Use "langchain/retrievers/chaindesk" instead */
export class DataberryRetriever extends BaseRetriever {
static lc_name() {
return "DataberryRetriever";
}
lc_namespace = ["langchain", "retrievers", "databerry"];
get lc_secrets() {
return { apiKey: "DATABERRY_API_KEY" };
}
get lc_aliases() {
return { apiKey: "api_key" };
}
caller: AsyncCaller;
datastoreUrl: string;
topK?: number;
apiKey?: string;
constructor(fields: DataberryRetrieverArgs) {
super(fields);
const { datastoreUrl, apiKey, topK, ...rest } = fields;
this.caller = new AsyncCaller(rest);
this.datastoreUrl = datastoreUrl;
this.apiKey = apiKey;
this.topK = topK;
}
async _getRelevantDocuments(query: string): Promise<Document[]> {
const r = await this.caller.call(fetch, this.datastoreUrl, {
method: "POST",
body: JSON.stringify({
query,
...(this.topK ? { topK: this.topK } : {}),
}),
headers: {
"Content-Type": "application/json",
...(this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}),
},
});
const { results } = (await r.json()) as { results: Berry[] };
return results.map(
({ text, score, source, ...rest }) =>
new Document({
pageContent: text,
metadata: {
score,
source,
...rest,
},
})
);
}
}