@bedrockio/ai 0.2.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.local.json +11 -0
- package/CHANGELOG.md +34 -0
- package/README.md +59 -17
- package/__mocks__/@anthropic-ai/sdk.js +16 -22
- package/__mocks__/@google/generative-ai.js +1 -1
- package/__mocks__/openai.js +33 -28
- package/dist/cjs/BaseClient.js +242 -126
- package/dist/cjs/anthropic.js +115 -93
- package/dist/cjs/google.js +74 -86
- package/dist/cjs/index.js +24 -25
- package/dist/cjs/openai.js +114 -69
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/utils/code.js +11 -0
- package/dist/cjs/utils/json.js +53 -0
- package/dist/cjs/utils/templates.js +83 -0
- package/dist/cjs/xai.js +14 -0
- package/dist/esm/BaseClient.js +243 -0
- package/dist/esm/anthropic.js +116 -0
- package/dist/esm/google.js +75 -0
- package/dist/esm/index.js +25 -0
- package/dist/esm/openai.js +113 -0
- package/dist/esm/utils/code.js +8 -0
- package/dist/esm/utils/json.js +50 -0
- package/dist/esm/utils/templates.js +76 -0
- package/dist/esm/xai.js +10 -0
- package/eslint.config.js +2 -0
- package/package.json +18 -17
- package/src/BaseClient.js +239 -89
- package/src/anthropic.js +96 -56
- package/src/google.js +6 -12
- package/src/index.js +20 -16
- package/src/openai.js +97 -31
- package/src/utils/code.js +9 -0
- package/src/utils/json.js +58 -0
- package/src/utils/templates.js +87 -0
- package/src/xai.js +12 -0
- package/tsconfig.cjs.json +8 -0
- package/tsconfig.esm.json +8 -0
- package/tsconfig.types.json +9 -0
- package/types/BaseClient.d.ts +68 -26
- package/types/BaseClient.d.ts.map +1 -1
- package/types/anthropic.d.ts +26 -2
- package/types/anthropic.d.ts.map +1 -1
- package/types/google.d.ts.map +1 -1
- package/types/index.d.ts +4 -3
- package/types/index.d.ts.map +1 -1
- package/types/openai.d.ts +45 -2
- package/types/openai.d.ts.map +1 -1
- package/types/util.d.ts +1 -1
- package/types/util.d.ts.map +1 -1
- package/types/utils/code.d.ts +2 -0
- package/types/utils/code.d.ts.map +1 -0
- package/types/utils/json.d.ts +2 -0
- package/types/utils/json.d.ts.map +1 -0
- package/types/utils/templates.d.ts +3 -0
- package/types/utils/templates.d.ts.map +1 -0
- package/types/utils.d.ts +4 -0
- package/types/utils.d.ts.map +1 -0
- package/types/xai.d.ts +4 -0
- package/types/xai.d.ts.map +1 -0
- package/vitest.config.js +10 -0
- package/dist/cjs/util.js +0 -47
- package/src/util.js +0 -42
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { parseCode } from './utils/code.js';
|
|
2
|
+
import { createMessageExtractor } from './utils/json.js';
|
|
3
|
+
import { loadTemplates, renderTemplate } from './utils/templates.js';
|
|
4
|
+
export default class BaseClient {
|
|
5
|
+
constructor(options) {
|
|
6
|
+
this.options = {
|
|
7
|
+
// @ts-ignore
|
|
8
|
+
model: this.constructor.DEFAULT_MODEL,
|
|
9
|
+
...options,
|
|
10
|
+
};
|
|
11
|
+
this.templates = null;
|
|
12
|
+
}
|
|
13
|
+
// Public
|
|
14
|
+
/**
|
|
15
|
+
* Interpolates vars into the provided template as instructions and runs the
|
|
16
|
+
* prompt.
|
|
17
|
+
*
|
|
18
|
+
* @param {PromptOptions} options
|
|
19
|
+
*/
|
|
20
|
+
async prompt(options) {
|
|
21
|
+
options = await this.normalizeOptions(options);
|
|
22
|
+
const { input, output, stream, schema } = options;
|
|
23
|
+
const response = await this.runPrompt(options);
|
|
24
|
+
if (!stream) {
|
|
25
|
+
this.debug('Response:', response);
|
|
26
|
+
}
|
|
27
|
+
if (output === 'raw') {
|
|
28
|
+
return response;
|
|
29
|
+
}
|
|
30
|
+
let result;
|
|
31
|
+
if (schema) {
|
|
32
|
+
result = this.getStructuredResponse(response);
|
|
33
|
+
// @ts-ignore
|
|
34
|
+
if (options.hasWrappedSchema) {
|
|
35
|
+
result = result.items;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else if (output === 'json') {
|
|
39
|
+
result = JSON.parse(parseCode(this.getTextResponse(response)));
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
result = parseCode(this.getTextResponse(response));
|
|
43
|
+
}
|
|
44
|
+
if (output === 'messages') {
|
|
45
|
+
return {
|
|
46
|
+
result,
|
|
47
|
+
...this.getMessagesResponse(input, response),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Streams the prompt response.
|
|
56
|
+
*
|
|
57
|
+
* @param {PromptOptions & StreamOptions} options
|
|
58
|
+
* @returns {AsyncIterator}
|
|
59
|
+
*/
|
|
60
|
+
async *stream(options) {
|
|
61
|
+
options = await this.normalizeOptions(options);
|
|
62
|
+
const extractor = this.getMessageExtractor(options);
|
|
63
|
+
try {
|
|
64
|
+
const stream = await this.runStream(options);
|
|
65
|
+
// @ts-ignore
|
|
66
|
+
for await (let event of stream) {
|
|
67
|
+
this.debug('Event:', event);
|
|
68
|
+
event = this.normalizeStreamEvent(event);
|
|
69
|
+
if (event) {
|
|
70
|
+
yield event;
|
|
71
|
+
}
|
|
72
|
+
const extractedMessages = extractor?.(event) || [];
|
|
73
|
+
for (let message of extractedMessages) {
|
|
74
|
+
const { key, delta, text, done } = message;
|
|
75
|
+
let extractEvent;
|
|
76
|
+
if (done) {
|
|
77
|
+
extractEvent = {
|
|
78
|
+
type: 'extract:done',
|
|
79
|
+
text,
|
|
80
|
+
key,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
extractEvent = {
|
|
85
|
+
type: 'extract:delta',
|
|
86
|
+
delta,
|
|
87
|
+
key,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
this.debug('Extract:', extractEvent);
|
|
91
|
+
yield extractEvent;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
const { message, code } = error;
|
|
97
|
+
yield {
|
|
98
|
+
type: 'error',
|
|
99
|
+
code,
|
|
100
|
+
message,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async buildTemplate(options) {
|
|
105
|
+
const template = await this.resolveTemplate(options);
|
|
106
|
+
return renderTemplate(template, options);
|
|
107
|
+
}
|
|
108
|
+
// Protected
|
|
109
|
+
runPrompt(options) {
|
|
110
|
+
void options;
|
|
111
|
+
throw new Error('Method not implemented.');
|
|
112
|
+
}
|
|
113
|
+
runStream(options) {
|
|
114
|
+
void options;
|
|
115
|
+
throw new Error('Method not implemented.');
|
|
116
|
+
}
|
|
117
|
+
getTextResponse(response) {
|
|
118
|
+
void response;
|
|
119
|
+
throw new Error('Method not implemented.');
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* @returns {Object}
|
|
123
|
+
*/
|
|
124
|
+
getStructuredResponse(response) {
|
|
125
|
+
void response;
|
|
126
|
+
throw new Error('Method not implemented.');
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* @returns {Object}
|
|
130
|
+
*/
|
|
131
|
+
getMessagesResponse(input, response) {
|
|
132
|
+
void response;
|
|
133
|
+
throw new Error('Method not implemented.');
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* @returns {Object}
|
|
137
|
+
*/
|
|
138
|
+
normalizeStreamEvent(event) {
|
|
139
|
+
void event;
|
|
140
|
+
throw new Error('Method not implemented.');
|
|
141
|
+
}
|
|
142
|
+
// Private
|
|
143
|
+
async normalizeOptions(options) {
|
|
144
|
+
options = {
|
|
145
|
+
input: '',
|
|
146
|
+
output: 'text',
|
|
147
|
+
...this.options,
|
|
148
|
+
...options,
|
|
149
|
+
};
|
|
150
|
+
options.input = this.normalizeInput(options);
|
|
151
|
+
options.schema = this.normalizeSchema(options);
|
|
152
|
+
options.instructions ||= await this.resolveInstructions(options);
|
|
153
|
+
return options;
|
|
154
|
+
}
|
|
155
|
+
normalizeInput(options) {
|
|
156
|
+
let { input = '', output } = options;
|
|
157
|
+
if (typeof input === 'string') {
|
|
158
|
+
if (output === 'json') {
|
|
159
|
+
input += '\nOutput only valid JSON.';
|
|
160
|
+
}
|
|
161
|
+
input = [
|
|
162
|
+
{
|
|
163
|
+
role: 'user',
|
|
164
|
+
content: input,
|
|
165
|
+
},
|
|
166
|
+
];
|
|
167
|
+
}
|
|
168
|
+
return input;
|
|
169
|
+
}
|
|
170
|
+
normalizeSchema(options) {
|
|
171
|
+
let { schema } = options;
|
|
172
|
+
if (!schema) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
// Convert to JSON schema.
|
|
176
|
+
schema = schema.toJSON?.() || schema;
|
|
177
|
+
if (schema?.type === 'array') {
|
|
178
|
+
schema = {
|
|
179
|
+
type: 'object',
|
|
180
|
+
properties: {
|
|
181
|
+
items: schema,
|
|
182
|
+
},
|
|
183
|
+
required: ['items'],
|
|
184
|
+
additionalProperties: false,
|
|
185
|
+
};
|
|
186
|
+
options.hasWrappedSchema = true;
|
|
187
|
+
}
|
|
188
|
+
return schema;
|
|
189
|
+
}
|
|
190
|
+
getMessageExtractor(options) {
|
|
191
|
+
const { extractMessages } = options;
|
|
192
|
+
if (!extractMessages) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const messageExtractor = createMessageExtractor([extractMessages]);
|
|
196
|
+
return (event) => {
|
|
197
|
+
if (event?.type === 'delta') {
|
|
198
|
+
return messageExtractor(event.delta);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
debug(message, arg) {
|
|
203
|
+
if (this.options.debug) {
|
|
204
|
+
// TODO: replace with logger when opentelemetry is removed
|
|
205
|
+
// eslint-disable-next-line
|
|
206
|
+
console.debug(`${message}\n${JSON.stringify(arg, null, 2)}\n`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async resolveInstructions(options) {
|
|
210
|
+
if (options.template) {
|
|
211
|
+
const template = await this.resolveTemplate(options);
|
|
212
|
+
return renderTemplate(template, options);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async resolveTemplate(options) {
|
|
216
|
+
const { template } = options;
|
|
217
|
+
await this.loadTemplates();
|
|
218
|
+
return this.templates[template] || template;
|
|
219
|
+
}
|
|
220
|
+
async loadTemplates() {
|
|
221
|
+
const { templates } = this.options;
|
|
222
|
+
this.templates ||= await loadTemplates(templates);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* @typedef {Object} PromptOptions
|
|
227
|
+
* @property {string|PromptMessage[]} input - Input to use.
|
|
228
|
+
* @property {string} [model] - The model to use.
|
|
229
|
+
* @property {boolean} stream - Stream response.
|
|
230
|
+
* @property {Object} [schema] - A JSON schema compatible object that defines the output shape.
|
|
231
|
+
* @property {"raw" | "text" | "json" | "messages"} [output] - The return value type.
|
|
232
|
+
* @property {Object} [params] - Params to be interpolated into the template.
|
|
233
|
+
* May also be passed as additional props to options.
|
|
234
|
+
*/
|
|
235
|
+
/**
|
|
236
|
+
* @typedef {Object} StreamOptions
|
|
237
|
+
* @property {string} [extractMessages] - Key in JSON response to extract a message stream from.
|
|
238
|
+
*/
|
|
239
|
+
/**
|
|
240
|
+
* @typedef {Object} PromptMessage
|
|
241
|
+
* @property {"system" | "user" | "assistant"} role
|
|
242
|
+
* @property {string} content
|
|
243
|
+
*/
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
2
|
+
import BaseClient from './BaseClient.js';
|
|
3
|
+
const DEFAULT_TOKENS = 4096;
|
|
4
|
+
export class AnthropicClient extends BaseClient {
|
|
5
|
+
static DEFAULT_MODEL = 'claude-sonnet-4-5';
|
|
6
|
+
constructor(options) {
|
|
7
|
+
super(options);
|
|
8
|
+
this.client = new Anthropic(options);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Lists available models.
|
|
12
|
+
* {@link https://docs.anthropic.com/en/docs/about-claude/models Documentation}
|
|
13
|
+
*/
|
|
14
|
+
async models() {
|
|
15
|
+
const { data } = await this.client.models.list();
|
|
16
|
+
return data.map((o) => o.id);
|
|
17
|
+
}
|
|
18
|
+
async runPrompt(options) {
|
|
19
|
+
const { input, model, temperature, instructions, stream = false, tokens = DEFAULT_TOKENS, } = options;
|
|
20
|
+
// @ts-ignore
|
|
21
|
+
return await this.client.messages.create({
|
|
22
|
+
model,
|
|
23
|
+
stream,
|
|
24
|
+
temperature,
|
|
25
|
+
max_tokens: tokens,
|
|
26
|
+
system: instructions,
|
|
27
|
+
...this.getSchemaOptions(options),
|
|
28
|
+
messages: input,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async runStream(options) {
|
|
32
|
+
return await this.runPrompt({
|
|
33
|
+
...options,
|
|
34
|
+
output: 'raw',
|
|
35
|
+
stream: true,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
getTextResponse(response) {
|
|
39
|
+
const textBlock = response.content.find((block) => {
|
|
40
|
+
return block.type === 'text';
|
|
41
|
+
});
|
|
42
|
+
return textBlock?.text || null;
|
|
43
|
+
}
|
|
44
|
+
getStructuredResponse(response) {
|
|
45
|
+
const toolBlock = response.content.find((block) => {
|
|
46
|
+
return block.type === 'tool_use';
|
|
47
|
+
});
|
|
48
|
+
return toolBlock?.input || null;
|
|
49
|
+
}
|
|
50
|
+
getMessagesResponse(input, response) {
|
|
51
|
+
return {
|
|
52
|
+
messages: [
|
|
53
|
+
...input,
|
|
54
|
+
...response.content
|
|
55
|
+
.filter((item) => {
|
|
56
|
+
return item.type === 'text';
|
|
57
|
+
})
|
|
58
|
+
.map((item) => {
|
|
59
|
+
return {
|
|
60
|
+
role: 'assistant',
|
|
61
|
+
content: item.text,
|
|
62
|
+
};
|
|
63
|
+
}),
|
|
64
|
+
],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
normalizeStreamEvent(event) {
|
|
68
|
+
let { type } = event;
|
|
69
|
+
if (type === 'content_block_start') {
|
|
70
|
+
return {
|
|
71
|
+
type: 'start',
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
else if (type === 'content_block_stop') {
|
|
75
|
+
return {
|
|
76
|
+
type: 'stop',
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
else if (type === 'content_block_delta') {
|
|
80
|
+
return {
|
|
81
|
+
type: 'delta',
|
|
82
|
+
text: event.delta.text,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Private
|
|
87
|
+
getSchemaOptions(options) {
|
|
88
|
+
const { output } = options;
|
|
89
|
+
if (output?.type) {
|
|
90
|
+
let schema = output;
|
|
91
|
+
if (schema.type === 'array') {
|
|
92
|
+
schema = {
|
|
93
|
+
type: 'object',
|
|
94
|
+
properties: {
|
|
95
|
+
items: schema,
|
|
96
|
+
},
|
|
97
|
+
required: ['items'],
|
|
98
|
+
additionalProperties: false,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
tools: [
|
|
103
|
+
{
|
|
104
|
+
name: 'schema',
|
|
105
|
+
description: 'Follow the schema for JSON output.',
|
|
106
|
+
input_schema: schema,
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
tool_choice: {
|
|
110
|
+
type: 'tool',
|
|
111
|
+
name: 'schema',
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { GoogleGenerativeAI } from '@google/generative-ai';
|
|
2
|
+
import BaseClient from './BaseClient.js';
|
|
3
|
+
const DEFAULT_MODEL = 'models/gemini-2.0-flash-exp';
|
|
4
|
+
export class GoogleClient extends BaseClient {
|
|
5
|
+
constructor(options) {
|
|
6
|
+
super(options);
|
|
7
|
+
const { apiKey } = options;
|
|
8
|
+
this.client = new GoogleGenerativeAI(apiKey);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Lists available models.
|
|
12
|
+
* {@link https://ai.google.dev/gemini-api/docs/models/gemini#gemini-2.0-flashl Documentation}
|
|
13
|
+
*/
|
|
14
|
+
async models() {
|
|
15
|
+
return [
|
|
16
|
+
'gemini-2.0-flash-exp',
|
|
17
|
+
'gemini-1.5-flash',
|
|
18
|
+
'gemini-1.5-flash-8b',
|
|
19
|
+
'gemini-1.5-pro',
|
|
20
|
+
];
|
|
21
|
+
}
|
|
22
|
+
async getCompletion(options) {
|
|
23
|
+
const { model = DEFAULT_MODEL, output = 'text', stream = false } = options;
|
|
24
|
+
const { client } = this;
|
|
25
|
+
const generator = client.getGenerativeModel({
|
|
26
|
+
model,
|
|
27
|
+
});
|
|
28
|
+
// @ts-ignore
|
|
29
|
+
const messages = await this.getMessages(options);
|
|
30
|
+
const prompts = messages.map((message) => {
|
|
31
|
+
return message.content;
|
|
32
|
+
});
|
|
33
|
+
let response;
|
|
34
|
+
if (stream) {
|
|
35
|
+
response = await generator.generateContentStream(prompts);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
response = await generator.generateContent(prompts);
|
|
39
|
+
}
|
|
40
|
+
if (output === 'raw') {
|
|
41
|
+
return response;
|
|
42
|
+
}
|
|
43
|
+
// @ts-ignore
|
|
44
|
+
const parts = response.response.candidates.flatMap((candidate) => {
|
|
45
|
+
return candidate.content.parts;
|
|
46
|
+
});
|
|
47
|
+
const [message] = parts;
|
|
48
|
+
return message;
|
|
49
|
+
}
|
|
50
|
+
async getStream(options) {
|
|
51
|
+
// @ts-ignore
|
|
52
|
+
const response = await super.getStream(options);
|
|
53
|
+
// @ts-ignore
|
|
54
|
+
return response.stream;
|
|
55
|
+
}
|
|
56
|
+
getStreamedChunk(chunk, started) {
|
|
57
|
+
const [candidate] = chunk.candidates;
|
|
58
|
+
let type;
|
|
59
|
+
if (!started) {
|
|
60
|
+
type = 'start';
|
|
61
|
+
}
|
|
62
|
+
else if (candidate.finishReason === 'STOP') {
|
|
63
|
+
type = 'stop';
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
type = 'chunk';
|
|
67
|
+
}
|
|
68
|
+
if (type) {
|
|
69
|
+
return {
|
|
70
|
+
type,
|
|
71
|
+
text: candidate.content.parts[0].text || '',
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { AnthropicClient } from './anthropic.js';
|
|
2
|
+
import { GoogleClient } from './google.js';
|
|
3
|
+
import { OpenAiClient } from './openai.js';
|
|
4
|
+
import { XAiClient } from './xai.js';
|
|
5
|
+
export function createClient(options = {}) {
|
|
6
|
+
const { platform } = options;
|
|
7
|
+
if (!platform) {
|
|
8
|
+
throw new Error('No platform specified.');
|
|
9
|
+
}
|
|
10
|
+
if (platform === 'openai' || platform === 'gpt') {
|
|
11
|
+
return new OpenAiClient(options);
|
|
12
|
+
}
|
|
13
|
+
else if (platform === 'google' || platform === 'gemini') {
|
|
14
|
+
return new GoogleClient(options);
|
|
15
|
+
}
|
|
16
|
+
else if (platform === 'anthropic' || platform === 'claude') {
|
|
17
|
+
return new AnthropicClient(options);
|
|
18
|
+
}
|
|
19
|
+
else if (platform === 'xai' || platform === 'grok') {
|
|
20
|
+
return new XAiClient(options);
|
|
21
|
+
}
|
|
22
|
+
else if (platform) {
|
|
23
|
+
throw new Error(`Unknown platform "${platform}".`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import OpenAI from 'openai';
|
|
2
|
+
import BaseClient from './BaseClient.js';
|
|
3
|
+
export class OpenAiClient extends BaseClient {
|
|
4
|
+
static DEFAULT_MODEL = 'gpt-5-nano';
|
|
5
|
+
constructor(options) {
|
|
6
|
+
super(options);
|
|
7
|
+
this.client = new OpenAI(options);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Lists available models.
|
|
11
|
+
* {@link https://platform.openai.com/docs/models Documentation}
|
|
12
|
+
*/
|
|
13
|
+
async models() {
|
|
14
|
+
const { data } = await this.client.models.list();
|
|
15
|
+
return data.map((o) => o.id);
|
|
16
|
+
}
|
|
17
|
+
async runPrompt(options) {
|
|
18
|
+
const { input, model, tools, verbosity, temperature, instructions, prevResponseId, stream = false, } = options;
|
|
19
|
+
const params = {
|
|
20
|
+
model,
|
|
21
|
+
input,
|
|
22
|
+
tools,
|
|
23
|
+
stream,
|
|
24
|
+
temperature,
|
|
25
|
+
instructions,
|
|
26
|
+
previous_response_id: prevResponseId,
|
|
27
|
+
text: {
|
|
28
|
+
format: this.getOutputFormat(options),
|
|
29
|
+
verbosity,
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
this.debug('Params:', params);
|
|
33
|
+
// @ts-ignore
|
|
34
|
+
return await this.client.responses.create(params);
|
|
35
|
+
}
|
|
36
|
+
async runStream(options) {
|
|
37
|
+
return await this.runPrompt({
|
|
38
|
+
...options,
|
|
39
|
+
stream: true,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
getTextResponse(response) {
|
|
43
|
+
return response.output_text;
|
|
44
|
+
}
|
|
45
|
+
getStructuredResponse(response) {
|
|
46
|
+
return JSON.parse(response.output_text);
|
|
47
|
+
}
|
|
48
|
+
getMessagesResponse(input, response) {
|
|
49
|
+
return {
|
|
50
|
+
messages: [
|
|
51
|
+
...input,
|
|
52
|
+
{
|
|
53
|
+
role: 'assistant',
|
|
54
|
+
content: response.output_text,
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
// Note that this ability currently only
|
|
58
|
+
// exists for OpenAI compatible providers.
|
|
59
|
+
prevResponseId: response.id,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
// Private
|
|
63
|
+
getOutputFormat(options) {
|
|
64
|
+
let { output, schema } = options;
|
|
65
|
+
if (output === 'json') {
|
|
66
|
+
return {
|
|
67
|
+
type: 'json_object',
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
else if (schema) {
|
|
71
|
+
return {
|
|
72
|
+
type: 'json_schema',
|
|
73
|
+
// Name is required but arbitrary.
|
|
74
|
+
name: 'schema',
|
|
75
|
+
strict: true,
|
|
76
|
+
schema,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
return {
|
|
81
|
+
type: 'text',
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
normalizeStreamEvent(event) {
|
|
86
|
+
const { type } = event;
|
|
87
|
+
if (type === 'response.created') {
|
|
88
|
+
return {
|
|
89
|
+
type: 'start',
|
|
90
|
+
id: event.response.id,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
else if (type === 'response.completed') {
|
|
94
|
+
return {
|
|
95
|
+
type: 'stop',
|
|
96
|
+
id: event.response.id,
|
|
97
|
+
usage: event.response.usage,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
else if (type === 'response.output_text.delta') {
|
|
101
|
+
return {
|
|
102
|
+
type: 'delta',
|
|
103
|
+
delta: event.delta,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
else if (type === 'response.output_text.done') {
|
|
107
|
+
return {
|
|
108
|
+
type: 'done',
|
|
109
|
+
text: event.text,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { OBJ, STR, parse } from 'partial-json';
|
|
2
|
+
export function createMessageExtractor(keys) {
|
|
3
|
+
let buffer = '';
|
|
4
|
+
const extractors = keys.map((key) => {
|
|
5
|
+
return createExtractor(key);
|
|
6
|
+
});
|
|
7
|
+
return (delta) => {
|
|
8
|
+
buffer += delta;
|
|
9
|
+
return extractors
|
|
10
|
+
.map((extractor) => {
|
|
11
|
+
return extractor(buffer);
|
|
12
|
+
})
|
|
13
|
+
.filter((extracted) => {
|
|
14
|
+
return extracted;
|
|
15
|
+
});
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function createExtractor(key) {
|
|
19
|
+
let lastText = '';
|
|
20
|
+
let done = false;
|
|
21
|
+
return (buffer) => {
|
|
22
|
+
if (done) {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const text = extractText(buffer, key);
|
|
26
|
+
if (!text) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
// Don't finish while the buffer has whitespace as it
|
|
30
|
+
// may be in the middle of trying to extract.
|
|
31
|
+
if (text === lastText && !buffer.endsWith(' ')) {
|
|
32
|
+
done = true;
|
|
33
|
+
}
|
|
34
|
+
const delta = text.slice(lastText.length);
|
|
35
|
+
lastText = text;
|
|
36
|
+
return {
|
|
37
|
+
key,
|
|
38
|
+
text,
|
|
39
|
+
delta,
|
|
40
|
+
done,
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function extractText(input, key) {
|
|
45
|
+
if (!input) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const parsed = parse(input, STR | OBJ);
|
|
49
|
+
return parsed?.[key] || '';
|
|
50
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import fs from 'fs/promises';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { glob } from 'glob';
|
|
4
|
+
import Mustache from 'mustache';
|
|
5
|
+
export async function loadTemplates(dir) {
|
|
6
|
+
const result = {};
|
|
7
|
+
const files = await glob(path.join(dir, '*.md'));
|
|
8
|
+
if (!files.length) {
|
|
9
|
+
throw new Error(`No templates found in: ${dir}.`);
|
|
10
|
+
}
|
|
11
|
+
for (let file of files) {
|
|
12
|
+
const base = path.basename(file, '.md');
|
|
13
|
+
result[base] = await loadTemplate(file);
|
|
14
|
+
}
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
export function renderTemplate(template, options) {
|
|
18
|
+
let params = {
|
|
19
|
+
...options,
|
|
20
|
+
...options.params,
|
|
21
|
+
};
|
|
22
|
+
params = mapObjects(params);
|
|
23
|
+
params = wrapProxy(params);
|
|
24
|
+
return Mustache.render(template, params);
|
|
25
|
+
}
|
|
26
|
+
// Utils
|
|
27
|
+
async function loadTemplate(file) {
|
|
28
|
+
return await fs.readFile(file, 'utf-8');
|
|
29
|
+
}
|
|
30
|
+
// Transform arrays and object to versions
|
|
31
|
+
// that are more understandable in the context
|
|
32
|
+
// of a template that may have meaningful whitespace.
|
|
33
|
+
function mapObjects(params) {
|
|
34
|
+
const result = {};
|
|
35
|
+
for (let [key, value] of Object.entries(params)) {
|
|
36
|
+
if (Array.isArray(value)) {
|
|
37
|
+
value = mapArray(value);
|
|
38
|
+
}
|
|
39
|
+
else if (typeof value === 'object') {
|
|
40
|
+
value = JSON.stringify(value, null, 2);
|
|
41
|
+
}
|
|
42
|
+
result[key] = value;
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
function mapArray(arr) {
|
|
47
|
+
// Only map simple arrays of primitives.
|
|
48
|
+
if (typeof arr[0] === 'string') {
|
|
49
|
+
arr = arr
|
|
50
|
+
.map((el) => {
|
|
51
|
+
return `- ${el}`;
|
|
52
|
+
})
|
|
53
|
+
.join('\n');
|
|
54
|
+
}
|
|
55
|
+
return arr;
|
|
56
|
+
}
|
|
57
|
+
// Wrap params with a proxy object that reports
|
|
58
|
+
// as having all properties. If one is accessed
|
|
59
|
+
// that does not exist then return the original
|
|
60
|
+
// token. This way templates can be partially
|
|
61
|
+
// interpolated and re-interpolated later.
|
|
62
|
+
function wrapProxy(params) {
|
|
63
|
+
return new Proxy(params, {
|
|
64
|
+
has() {
|
|
65
|
+
return true;
|
|
66
|
+
},
|
|
67
|
+
get(target, prop) {
|
|
68
|
+
if (prop in target) {
|
|
69
|
+
return target[prop];
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
return `{{{${prop.toString()}}}}`;
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|