-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
sort_xyz_blockchain.ts
183 lines (155 loc) Β· 5.23 KB
/
sort_xyz_blockchain.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { Document } from "@langchain/core/documents";
import { BaseDocumentLoader } from "../base.js";
import { logVersion020MigrationWarning } from "../../util/entrypoint_deprecation.js";
/* #__PURE__ */ logVersion020MigrationWarning({
oldEntrypointName: "document_loaders/web/sortxyz_blockchain",
newPackageName: "@langchain/community",
});
/**
* See https://docs.sort.xyz/docs/api-keys to get your free Sort API key.
* See https://docs.sort.xyz for more information on the available queries.
* See https://docs.sort.xyz/reference for more information about Sort's REST API.
*/
export interface Query {
type: "NFTMetadata" | "latestTransactions";
contractAddress: string;
blockchain: "ethereum" | "polygon" | "goerli";
limit?: number;
}
/**
* Interface representing the parameters for the SortXYZBlockchainLoader
* class.
*/
export interface SortXYZBlockchainLoaderParams {
apiKey: string;
query: Query | string;
}
/**
* Interface representing the response from the SortXYZ API.
*/
export interface SortXYZBlockchainAPIResponse {
code: number;
data: {
durationMs: number;
id: string;
query: string;
records: Record<string, unknown>[];
recordCount: number;
};
}
/**
* Class representing a document loader for loading data from the SortXYZ
* blockchain using the SortXYZ API.
* @example
* ```typescript
* const blockchainLoader = new SortXYZBlockchainLoader({
* apiKey: "YOUR_SORTXYZ_API_KEY",
* query: {
* type: "NFTMetadata",
* blockchain: "ethereum",
* contractAddress: "0x887F3909C14DAbd9e9510128cA6cBb448E932d7f".toLowerCase(),
* },
* });
*
* const blockchainData = await blockchainLoader.load();
*
* const prompt =
* "Describe the character with the attributes from the following json document in a 4 sentence story. ";
* const model = new ChatOpenAI({ temperature: 0.9 })
* const response = await model.invoke(
* prompt + JSON.stringify(blockchainData[0], null, 2),
* );
* console.log(`user > ${prompt}`);
* console.log(`chatgpt > ${response}`);
* ```
*/
export class SortXYZBlockchainLoader extends BaseDocumentLoader {
public readonly contractAddress: string;
public readonly blockchain: string;
public readonly apiKey: string;
public readonly queryType: string;
public readonly sql: string;
public readonly limit: number;
constructor({ apiKey, query }: SortXYZBlockchainLoaderParams) {
super();
if (!apiKey) {
throw new Error(
`apiKey is required! Head over to https://docs.sort.xyz/docs/api-keys to get your free Sort API key.`
);
}
this.apiKey = apiKey;
if (typeof query === "string") {
this.sql = query;
} else {
this.contractAddress = query.contractAddress.toLowerCase();
this.blockchain = query.blockchain;
this.queryType = query.type;
this.limit = query.limit ?? 100;
}
}
/**
* Method that loads the data from the SortXYZ blockchain based on the
* specified query parameters. It makes requests to the SortXYZ API and
* returns an array of Documents representing the retrieved data.
* @returns Promise<Document[]> - An array of Documents representing the retrieved data.
*/
public async load(): Promise<Document[]> {
if (this.limit > 1000) {
throw new Error(
`Limit is set too high. Please set limit to 1000 or lower.`
);
}
const docs: Document[] = [];
let queryOffset = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
let query = "";
if (this.sql) {
query = this.sql;
} else if (this.queryType === "NFTMetadata") {
// All parameters here are user defined
query = `SELECT * FROM ${this.blockchain}.nft_metadata WHERE contract_address = '${this.contractAddress}' ORDER BY token_id DESC LIMIT ${this.limit} OFFSET ${queryOffset}`;
} else if (this.queryType === "latestTransactions") {
// All parameters here are user defined
query = `SELECT * FROM ${this.blockchain}.transaction t, ethereum.block b WHERE t.to_address = '${this.contractAddress}' AND b.id=t.block_id ORDER BY b.timestamp DESC LIMIT ${this.limit} OFFSET ${queryOffset}`;
}
try {
const response = await fetch("https://api.sort.xyz/v1/queries/run", {
method: "POST",
headers: {
"x-api-key": this.apiKey as string,
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ query }),
});
const fullResponse = await response.json();
// Reached the end, no more records
if (
fullResponse &&
fullResponse.data &&
fullResponse.data.records.length === 0
) {
break;
}
const data = fullResponse?.data || [];
for (let i = 0; i < data.records.length; i += 1) {
const doc = new Document({
pageContent: JSON.stringify(data.records[i], null, 2),
metadata: {
row: i,
},
});
docs.push(doc);
}
queryOffset += this.limit;
if (queryOffset >= this.limit || this.sql) {
break;
}
} catch (error) {
console.error("Error:", error);
}
}
return docs;
}
}