@farm.js/ai 0.1.0-beta.0
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/LICENSE +22 -0
- package/README.md +11 -0
- package/dist/index.d.ts +62 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +191 -0
- package/package.json +37 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Farm.js Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { convertToModelMessages, streamText, type LanguageModel, type UIMessage, type UIMessageStreamOptions } from "ai";
|
|
2
|
+
type AIStreamTextFunction = typeof streamText;
|
|
3
|
+
type AIConvertToModelMessagesFunction = typeof convertToModelMessages;
|
|
4
|
+
type AIStreamTextInput = Parameters<AIStreamTextFunction>[0];
|
|
5
|
+
type AIConvertToModelMessagesOptions = NonNullable<Parameters<AIConvertToModelMessagesFunction>[1]>;
|
|
6
|
+
export interface AIChatRequestBody<TMessage = Omit<UIMessage, "id">> {
|
|
7
|
+
messages: TMessage[];
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
export interface AIChatValidationIssue {
|
|
11
|
+
path: readonly (string | number)[];
|
|
12
|
+
code: string;
|
|
13
|
+
message: string;
|
|
14
|
+
}
|
|
15
|
+
export type AIChatStreamTextOptions = Partial<Omit<AIStreamTextInput, "model" | "messages" | "prompt">>;
|
|
16
|
+
export type AIChatResponseOptions = ResponseInit & UIMessageStreamOptions<UIMessage> & {
|
|
17
|
+
consumeSseStream?: (options: {
|
|
18
|
+
stream: ReadableStream<string>;
|
|
19
|
+
}) => PromiseLike<void> | void;
|
|
20
|
+
};
|
|
21
|
+
export interface AIChatPrepareContext<TBody extends AIChatRequestBody = AIChatRequestBody> {
|
|
22
|
+
request: Request;
|
|
23
|
+
body: TBody;
|
|
24
|
+
messages: unknown[];
|
|
25
|
+
modelMessages: Awaited<ReturnType<AIConvertToModelMessagesFunction>>;
|
|
26
|
+
}
|
|
27
|
+
export interface AIChatRouteOptions<TBody extends AIChatRequestBody = AIChatRequestBody> {
|
|
28
|
+
model: LanguageModel;
|
|
29
|
+
system?: AIStreamTextInput["system"];
|
|
30
|
+
instructions?: AIStreamTextInput["instructions"];
|
|
31
|
+
streamText?: AIStreamTextFunction;
|
|
32
|
+
convertToModelMessages?: AIConvertToModelMessagesFunction;
|
|
33
|
+
convertToModelMessagesOptions?: AIConvertToModelMessagesOptions;
|
|
34
|
+
options?: AIChatStreamTextOptions;
|
|
35
|
+
responseOptions?: AIChatResponseOptions | ((context: AIChatPrepareContext<TBody>) => AIChatResponseOptions | Promise<AIChatResponseOptions>);
|
|
36
|
+
selectMessages?: (body: TBody, request: Request) => unknown[];
|
|
37
|
+
prepare?: (context: AIChatPrepareContext<TBody>) => AIChatStreamTextOptions | Promise<AIChatStreamTextOptions>;
|
|
38
|
+
}
|
|
39
|
+
type AIChatRequestBodySchema = {
|
|
40
|
+
parse(value: unknown): AIChatRequestBody;
|
|
41
|
+
safeParse(value: unknown): {
|
|
42
|
+
success: true;
|
|
43
|
+
data: AIChatRequestBody;
|
|
44
|
+
} | {
|
|
45
|
+
success: false;
|
|
46
|
+
error: {
|
|
47
|
+
issues: AIChatValidationIssue[];
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
export declare const aiChatRequestBodySchema: AIChatRequestBodySchema;
|
|
52
|
+
/**
|
|
53
|
+
* Create a Vercel AI SDK chat route for Farm's Next-style app/api convention.
|
|
54
|
+
*
|
|
55
|
+
* // src/app/api/chat/route.ts
|
|
56
|
+
* export const POST = aiChatRoute({ model: "openai/gpt-4o-mini" });
|
|
57
|
+
*/
|
|
58
|
+
export declare function aiChatRoute<TBody extends AIChatRequestBody = AIChatRequestBody>(input: AIChatRouteOptions<TBody>): import("@farm.js/core").FarmTypedEndpoint<AIChatRequestBody<Omit<UIMessage<unknown, import("ai").UIDataTypes, import("ai").UITools>, "id">>, unknown, Response>;
|
|
59
|
+
export declare const createAIChatRoute: typeof aiChatRoute;
|
|
60
|
+
export declare const defineAIChatRoute: typeof aiChatRoute;
|
|
61
|
+
export {};
|
|
62
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,sBAAsB,EACtB,UAAU,EACV,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,sBAAsB,EAC5B,MAAM,IAAI,CAAC;A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AAC;AAC7C,eAAO,MAAM,iBAAiB,oBAAc,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createEndpoint } from "@farm.js/core";
|
|
2
|
+
import { convertToModelMessages, streamText, } from "ai";
|
|
3
|
+
export const aiChatRequestBodySchema = {
|
|
4
|
+
parse(value) {
|
|
5
|
+
const validation = validateAIChatRequestBody(value);
|
|
6
|
+
if (!validation.success) {
|
|
7
|
+
throw createAIChatValidationError(validation.issues);
|
|
8
|
+
}
|
|
9
|
+
return validation.data;
|
|
10
|
+
},
|
|
11
|
+
safeParse(value) {
|
|
12
|
+
const validation = validateAIChatRequestBody(value);
|
|
13
|
+
if (validation.success) {
|
|
14
|
+
return validation;
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
success: false,
|
|
18
|
+
error: {
|
|
19
|
+
issues: validation.issues,
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Create a Vercel AI SDK chat route for Farm's Next-style app/api convention.
|
|
26
|
+
*
|
|
27
|
+
* // src/app/api/chat/route.ts
|
|
28
|
+
* export const POST = aiChatRoute({ model: "openai/gpt-4o-mini" });
|
|
29
|
+
*/
|
|
30
|
+
export function aiChatRoute(input) {
|
|
31
|
+
return createEndpoint({
|
|
32
|
+
method: "POST",
|
|
33
|
+
body: aiChatRequestBodySchema,
|
|
34
|
+
}, async (context) => {
|
|
35
|
+
return createAIChatResponse(input, context.request, context.body);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export const createAIChatRoute = aiChatRoute;
|
|
39
|
+
export const defineAIChatRoute = aiChatRoute;
|
|
40
|
+
async function createAIChatResponse(input, request, bodyInput) {
|
|
41
|
+
const bodyValidation = validateAIChatRequestBody(bodyInput ?? (await readJsonBody(request)));
|
|
42
|
+
if (!bodyValidation.success) {
|
|
43
|
+
return createAIChatValidationResponse(bodyValidation.issues);
|
|
44
|
+
}
|
|
45
|
+
const body = bodyValidation.data;
|
|
46
|
+
const messages = input.selectMessages?.(body, request) ?? body.messages;
|
|
47
|
+
if (!Array.isArray(messages)) {
|
|
48
|
+
return createAIChatValidationResponse([
|
|
49
|
+
{
|
|
50
|
+
path: ["messages"],
|
|
51
|
+
code: "invalid_type",
|
|
52
|
+
message: "Expected selected messages to be an array.",
|
|
53
|
+
},
|
|
54
|
+
]);
|
|
55
|
+
}
|
|
56
|
+
const convertMessages = input.convertToModelMessages ?? convertToModelMessages;
|
|
57
|
+
const modelMessages = await convertMessages(messages, {
|
|
58
|
+
...input.convertToModelMessagesOptions,
|
|
59
|
+
tools: input.convertToModelMessagesOptions?.tools ?? input.options?.tools,
|
|
60
|
+
});
|
|
61
|
+
const prepareContext = {
|
|
62
|
+
request,
|
|
63
|
+
body,
|
|
64
|
+
messages,
|
|
65
|
+
modelMessages,
|
|
66
|
+
};
|
|
67
|
+
const preparedOptions = await input.prepare?.(prepareContext);
|
|
68
|
+
const streamInput = {
|
|
69
|
+
...input.options,
|
|
70
|
+
system: input.system ?? input.options?.system,
|
|
71
|
+
instructions: input.instructions ?? input.options?.instructions,
|
|
72
|
+
...preparedOptions,
|
|
73
|
+
model: input.model,
|
|
74
|
+
messages: modelMessages,
|
|
75
|
+
};
|
|
76
|
+
const responseOptions = typeof input.responseOptions === "function"
|
|
77
|
+
? await input.responseOptions(prepareContext)
|
|
78
|
+
: input.responseOptions;
|
|
79
|
+
const stream = (input.streamText ?? streamText)(streamInput);
|
|
80
|
+
return stream.toUIMessageStreamResponse(responseOptions);
|
|
81
|
+
}
|
|
82
|
+
async function readJsonBody(request) {
|
|
83
|
+
try {
|
|
84
|
+
const text = await request.clone().text();
|
|
85
|
+
if (text.trim().length === 0) {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
return JSON.parse(text);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function validateAIChatRequestBody(value) {
|
|
95
|
+
if (!isRecord(value)) {
|
|
96
|
+
return {
|
|
97
|
+
success: false,
|
|
98
|
+
issues: [
|
|
99
|
+
{
|
|
100
|
+
path: [],
|
|
101
|
+
code: "invalid_type",
|
|
102
|
+
message: "Expected AI chat request body to be an object.",
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const messages = value.messages;
|
|
108
|
+
if (!Array.isArray(messages)) {
|
|
109
|
+
return {
|
|
110
|
+
success: false,
|
|
111
|
+
issues: [
|
|
112
|
+
{
|
|
113
|
+
path: ["messages"],
|
|
114
|
+
code: "invalid_type",
|
|
115
|
+
message: "Expected messages to be an array.",
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
const issues = [];
|
|
121
|
+
if (messages.length === 0) {
|
|
122
|
+
issues.push({
|
|
123
|
+
path: ["messages"],
|
|
124
|
+
code: "too_small",
|
|
125
|
+
message: "Expected at least one message.",
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
for (const [messageIndex, message] of messages.entries()) {
|
|
129
|
+
if (!isRecord(message)) {
|
|
130
|
+
issues.push({
|
|
131
|
+
path: ["messages", messageIndex],
|
|
132
|
+
code: "invalid_type",
|
|
133
|
+
message: "Expected message to be an object.",
|
|
134
|
+
});
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (!isAIMessageRole(message.role)) {
|
|
138
|
+
issues.push({
|
|
139
|
+
path: ["messages", messageIndex, "role"],
|
|
140
|
+
code: "invalid_enum_value",
|
|
141
|
+
message: "Expected message role to be system, user, or assistant.",
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
if (!Array.isArray(message.parts)) {
|
|
145
|
+
issues.push({
|
|
146
|
+
path: ["messages", messageIndex, "parts"],
|
|
147
|
+
code: "invalid_type",
|
|
148
|
+
message: "Expected message parts to be an array.",
|
|
149
|
+
});
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
for (const [partIndex, part] of message.parts.entries()) {
|
|
153
|
+
if (!isRecord(part) || typeof part.type !== "string") {
|
|
154
|
+
issues.push({
|
|
155
|
+
path: ["messages", messageIndex, "parts", partIndex],
|
|
156
|
+
code: "invalid_type",
|
|
157
|
+
message: "Expected message part to be an object with a string type.",
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (issues.length > 0) {
|
|
163
|
+
return {
|
|
164
|
+
success: false,
|
|
165
|
+
issues,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
success: true,
|
|
170
|
+
data: value,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
function createAIChatValidationResponse(issues) {
|
|
174
|
+
return Response.json({
|
|
175
|
+
error: "AI chat request body validation failed",
|
|
176
|
+
issues,
|
|
177
|
+
}, {
|
|
178
|
+
status: 400,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
function createAIChatValidationError(issues) {
|
|
182
|
+
const error = new Error("AI chat request body validation failed");
|
|
183
|
+
error.issues = issues;
|
|
184
|
+
return error;
|
|
185
|
+
}
|
|
186
|
+
function isAIMessageRole(value) {
|
|
187
|
+
return value === "system" || value === "user" || value === "assistant";
|
|
188
|
+
}
|
|
189
|
+
function isRecord(value) {
|
|
190
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
191
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@farm.js/ai",
|
|
3
|
+
"version": "0.1.0-beta.0",
|
|
4
|
+
"description": "Farm.js AI route helpers",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/farming-labs/farm.js",
|
|
9
|
+
"directory": "packages/farm-ai"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"module": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"ai": "^7.0.11",
|
|
29
|
+
"@farm.js/core": "0.1.0-beta.0"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",
|
|
33
|
+
"dev": "tsc --watch",
|
|
34
|
+
"type-check": "tsc --noEmit",
|
|
35
|
+
"test": "echo 'No tests in this package'"
|
|
36
|
+
}
|
|
37
|
+
}
|