Skip to content

Commit db43e13

Browse files
authored
Update index.ts
1 parent 832a274 commit db43e13

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

packages/plugin-web-search/src/index.ts

+24-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,30 @@ import {
88
State,
99
} from "@ai16z/eliza";
1010
import { generateWebSearch } from "@ai16z/eliza";
11-
1211
import { SearchResult } from "@ai16z/eliza";
12+
import { encodingForModel, TiktokenModel } from "js-tiktoken";
13+
14+
const DEFAULT_MAX_WEB_SEARCH_TOKENS = 4000;
15+
const DEFAULT_MODEL_ENCODING = "gpt-3.5-turbo";
16+
17+
function getTotalTokensFromString(
18+
str: string,
19+
encodingName: TiktokenModel = DEFAULT_MODEL_ENCODING
20+
) {
21+
const encoding = encodingForModel(encodingName);
22+
return encoding.encode(str).length;
23+
}
24+
25+
function MaxTokens(
26+
data: string,
27+
maxTokens: number = DEFAULT_MAX_WEB_SEARCH_TOKENS
28+
): string {
29+
30+
if (getTotalTokensFromString(data) >= maxTokens) {
31+
return data.slice(0, maxTokens);
32+
}
33+
return data;
34+
}
1335

1436
const webSearch: Action = {
1537
name: "WEB_SEARCH",
@@ -68,7 +90,7 @@ const webSearch: Action = {
6890
: "";
6991

7092
callback({
71-
text: responseList,
93+
text: MaxTokens(responseList, DEFAULT_MAX_WEB_SEARCH_TOKENS),
7294
});
7395
} else {
7496
elizaLogger.error("search failed or returned no data.");

0 commit comments

Comments
 (0)