@convex-dev/ai-sdk-provider 0.1.0 → 0.2.0-alpha.1
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/README.md +27 -2
- package/dist/commonjs/index.d.ts +13 -2
- package/dist/commonjs/index.d.ts.map +1 -1
- package/dist/commonjs/index.js +112 -15
- package/dist/commonjs/index.js.map +1 -1
- package/dist/esm/index.d.ts +13 -2
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +113 -16
- package/dist/esm/index.js.map +1 -1
- package/package.json +6 -3
- package/src/index.ts +164 -19
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Use the Convex AI gateway with the AI SDK from a Convex action.
|
|
|
6
6
|
"use node";
|
|
7
7
|
|
|
8
8
|
import { convexGateway } from "@convex-dev/ai-sdk-provider";
|
|
9
|
-
import { generateText } from "ai";
|
|
9
|
+
import { embedMany, generateText } from "ai";
|
|
10
10
|
import { action } from "./_generated/server";
|
|
11
11
|
import { v } from "convex/values";
|
|
12
12
|
|
|
@@ -20,10 +20,35 @@ export const chat = action({
|
|
|
20
20
|
return text;
|
|
21
21
|
},
|
|
22
22
|
});
|
|
23
|
+
|
|
24
|
+
export const embed = action({
|
|
25
|
+
args: { values: v.array(v.string()) },
|
|
26
|
+
handler: async (_ctx, { values }) => {
|
|
27
|
+
const { embeddings } = await embedMany({
|
|
28
|
+
model: convexGateway.embeddingModel("openai/text-embedding-3-small"),
|
|
29
|
+
values,
|
|
30
|
+
});
|
|
31
|
+
return embeddings;
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Embedding batches larger than the gateway's 512-input limit are split into
|
|
37
|
+
multiple requests by the AI SDK.
|
|
38
|
+
|
|
39
|
+
## Choose a model interface
|
|
40
|
+
|
|
41
|
+
For text generation, start with `convexGateway(model)`. It works across model
|
|
42
|
+
providers and is the recommended default. Use an endpoint-specific model only
|
|
43
|
+
when you need features unique to Anthropic Messages or OpenAI Responses:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
convexGateway.messages("anthropic/claude-sonnet-4.5");
|
|
47
|
+
convexGateway.responses("openai/gpt-5");
|
|
23
48
|
```
|
|
24
49
|
|
|
25
50
|
`getServiceToken("ai-gateway")` mints a short-lived deployment JWT on first use
|
|
26
51
|
in an action and reuses it for later calls, so `convexGateway(...)` is fine to
|
|
27
52
|
call more than once. The provider takes no API key.
|
|
28
53
|
|
|
29
|
-
Requires Convex 1.
|
|
54
|
+
Requires Convex 1.45 or later, AI SDK 7, and Node.js 22 or later.
|
package/dist/commonjs/index.d.ts
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
2
|
-
|
|
2
|
+
import { wrapLanguageModel } from "ai";
|
|
3
|
+
type Provider = ReturnType<typeof createOpenAICompatible>;
|
|
4
|
+
type ChatModel = ReturnType<Provider>;
|
|
5
|
+
type EmbeddingModel = ReturnType<Provider["embeddingModel"]>;
|
|
6
|
+
type GatewayLanguageModel = ReturnType<typeof wrapLanguageModel>;
|
|
3
7
|
/**
|
|
4
|
-
*
|
|
8
|
+
* The recommended model interface for text generation through the Convex AI gateway.
|
|
9
|
+
* Use `messages` or `responses` only for endpoint-specific features.
|
|
10
|
+
*
|
|
5
11
|
* `getServiceToken` reuses one token for the current action, so calling this
|
|
6
12
|
* more than once in the same action is fine.
|
|
7
13
|
*/
|
|
8
14
|
export declare function convexGateway(modelId: string): ChatModel;
|
|
15
|
+
export declare namespace convexGateway {
|
|
16
|
+
var messages: (modelId: string) => GatewayLanguageModel;
|
|
17
|
+
var responses: (modelId: string) => GatewayLanguageModel;
|
|
18
|
+
var embeddingModel: (modelId: string) => EmbeddingModel;
|
|
19
|
+
}
|
|
9
20
|
export {};
|
|
10
21
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,sBAAsB,EAEvB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAKL,iBAAiB,EAClB,MAAM,IAAI,CAAC;AAGZ,KAAK,QAAQ,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC1D,KAAK,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC,KAAK,cAAc,GAAG,UAAU,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC,CAAC;AAE7D,KAAK,oBAAoB,GAAG,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAgHjE;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAExD;yBAFe,aAAa;4BAIe,MAAM,KAAG,oBAAoB;6BAa5B,MAAM,KAAG,oBAAoB;kCAgBxB,MAAM,KAAG,cAAc"}
|
package/dist/commonjs/index.js
CHANGED
|
@@ -1,33 +1,130 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.convexGateway = convexGateway;
|
|
4
|
+
const anthropic_1 = require("@ai-sdk/anthropic");
|
|
5
|
+
const openai_1 = require("@ai-sdk/openai");
|
|
4
6
|
const openai_compatible_1 = require("@ai-sdk/openai-compatible");
|
|
7
|
+
const ai_1 = require("ai");
|
|
5
8
|
const server_1 = require("convex/server");
|
|
9
|
+
const maxEmbeddingsPerCall = 512;
|
|
10
|
+
// Official providers require a credential before gatewayFetch replaces it with a deployment JWT.
|
|
11
|
+
const placeholderCredential = "convex-gateway";
|
|
6
12
|
/**
|
|
7
13
|
* A deployment can set `CONVEX_INTERNAL_AI_GATEWAY_HOST` to reach a different
|
|
8
14
|
* gateway, which is how internal apps use staging.
|
|
9
15
|
*/
|
|
10
16
|
const productionGatewayHost = "https://ai-gateway.convex.dev";
|
|
17
|
+
function gatewayBaseURL() {
|
|
18
|
+
return `${process.env.CONVEX_INTERNAL_AI_GATEWAY_HOST || productionGatewayHost}/v1`;
|
|
19
|
+
}
|
|
20
|
+
async function gatewayFetch(input, init) {
|
|
21
|
+
if (typeof server_1.getServiceToken !== "function") {
|
|
22
|
+
throw new Error("@convex-dev/ai-sdk-provider requires convex >= 1.45 with getServiceToken support");
|
|
23
|
+
}
|
|
24
|
+
const token = await (0, server_1.getServiceToken)("ai-gateway");
|
|
25
|
+
const headers = new Headers(init?.headers);
|
|
26
|
+
// Deployment JWT is the only accepted credential for the hosted gateway.
|
|
27
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
28
|
+
return globalThis.fetch(input, { ...init, headers });
|
|
29
|
+
}
|
|
30
|
+
// The SDK's standard usage mapping omits the gateway's dollar costs.
|
|
31
|
+
function convexGatewayUsageMetadata(usage) {
|
|
32
|
+
if (!usage || typeof usage !== "object")
|
|
33
|
+
return undefined;
|
|
34
|
+
const { cost, cost_details } = usage;
|
|
35
|
+
const metadata = {};
|
|
36
|
+
if (typeof cost === "number")
|
|
37
|
+
metadata.cost = cost;
|
|
38
|
+
if (cost_details && typeof cost_details === "object") {
|
|
39
|
+
metadata.costDetails = cost_details;
|
|
40
|
+
}
|
|
41
|
+
return Object.keys(metadata).length > 0
|
|
42
|
+
? { convexGateway: metadata }
|
|
43
|
+
: undefined;
|
|
44
|
+
}
|
|
45
|
+
const costMetadataExtractor = {
|
|
46
|
+
extractMetadata: async ({ parsedBody }) => convexGatewayUsageMetadata(parsedBody?.usage),
|
|
47
|
+
createStreamExtractor: () => {
|
|
48
|
+
// Streamed responses deliver usage (incl. cost) on the final chunk.
|
|
49
|
+
let usage;
|
|
50
|
+
return {
|
|
51
|
+
processChunk(parsedChunk) {
|
|
52
|
+
const chunk = parsedChunk;
|
|
53
|
+
if (chunk?.usage)
|
|
54
|
+
usage = chunk.usage;
|
|
55
|
+
},
|
|
56
|
+
buildMetadata: () => convexGatewayUsageMetadata(usage),
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
function createGatewayProvider() {
|
|
61
|
+
return (0, openai_compatible_1.createOpenAICompatible)({
|
|
62
|
+
name: "convexGateway",
|
|
63
|
+
baseURL: gatewayBaseURL(),
|
|
64
|
+
fetch: gatewayFetch,
|
|
65
|
+
metadataExtractor: costMetadataExtractor,
|
|
66
|
+
supportsStructuredOutputs: true,
|
|
67
|
+
supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/] }),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
function sdkModelId(gatewayModelId, provider) {
|
|
71
|
+
const prefix = `${provider}/`;
|
|
72
|
+
const modelId = gatewayModelId.startsWith(prefix)
|
|
73
|
+
? gatewayModelId.slice(prefix.length)
|
|
74
|
+
: gatewayModelId;
|
|
75
|
+
// OpenRouter uses dots in Anthropic versions; the Anthropic SDK's capability lookup uses hyphens.
|
|
76
|
+
return provider === "anthropic" ? modelId.replaceAll(".", "-") : modelId;
|
|
77
|
+
}
|
|
78
|
+
function gatewayModelFetch(gatewayModelId, input, init) {
|
|
79
|
+
const body = JSON.parse(init?.body);
|
|
80
|
+
body.model = gatewayModelId;
|
|
81
|
+
return gatewayFetch(input, { ...init, body: JSON.stringify(body) });
|
|
82
|
+
}
|
|
83
|
+
function gatewayLanguageModel(modelId, model, middleware) {
|
|
84
|
+
return (0, ai_1.wrapLanguageModel)({
|
|
85
|
+
model,
|
|
86
|
+
modelId,
|
|
87
|
+
// The gateway does not expose the providers' batch APIs.
|
|
88
|
+
middleware: middleware ?? { specificationVersion: "v4" },
|
|
89
|
+
});
|
|
90
|
+
}
|
|
11
91
|
/**
|
|
12
|
-
*
|
|
92
|
+
* The recommended model interface for text generation through the Convex AI gateway.
|
|
93
|
+
* Use `messages` or `responses` only for endpoint-specific features.
|
|
94
|
+
*
|
|
13
95
|
* `getServiceToken` reuses one token for the current action, so calling this
|
|
14
96
|
* more than once in the same action is fine.
|
|
15
97
|
*/
|
|
16
98
|
function convexGateway(modelId) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
99
|
+
return createGatewayProvider()(modelId);
|
|
100
|
+
}
|
|
101
|
+
convexGateway.messages = function (modelId) {
|
|
102
|
+
const provider = (0, anthropic_1.createAnthropic)({
|
|
103
|
+
name: "convexGateway.messages",
|
|
104
|
+
baseURL: gatewayBaseURL(),
|
|
105
|
+
authToken: placeholderCredential,
|
|
106
|
+
fetch: (input, init) => gatewayModelFetch(modelId, input, init),
|
|
107
|
+
});
|
|
108
|
+
return gatewayLanguageModel(modelId, provider.messages(sdkModelId(modelId, "anthropic")));
|
|
109
|
+
};
|
|
110
|
+
convexGateway.responses = function (modelId) {
|
|
111
|
+
const provider = (0, openai_1.createOpenAI)({
|
|
112
|
+
name: "convexGateway.responses",
|
|
113
|
+
baseURL: gatewayBaseURL(),
|
|
114
|
+
apiKey: placeholderCredential,
|
|
115
|
+
fetch: (input, init) => gatewayModelFetch(modelId, input, init),
|
|
116
|
+
});
|
|
117
|
+
return gatewayLanguageModel(modelId, provider.responses(sdkModelId(modelId, "openai")), (0, ai_1.defaultSettingsMiddleware)({
|
|
118
|
+
settings: { providerOptions: { openai: { store: false } } },
|
|
119
|
+
}));
|
|
120
|
+
};
|
|
121
|
+
convexGateway.embeddingModel = function (modelId) {
|
|
122
|
+
return (0, ai_1.wrapEmbeddingModel)({
|
|
123
|
+
model: createGatewayProvider().embeddingModel(modelId),
|
|
124
|
+
middleware: {
|
|
125
|
+
specificationVersion: "v4",
|
|
126
|
+
overrideMaxEmbeddingsPerCall: () => maxEmbeddingsPerCall,
|
|
29
127
|
},
|
|
30
128
|
});
|
|
31
|
-
|
|
32
|
-
}
|
|
129
|
+
};
|
|
33
130
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AA0IA,sCAEC;AA5ID,iDAAoD;AACpD,2CAA8C;AAC9C,iEAGmC;AACnC,2BAMY;AACZ,0CAAgD;AAQhD,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,iGAAiG;AACjG,MAAM,qBAAqB,GAAG,gBAAgB,CAAC;AAE/C;;;GAGG;AACH,MAAM,qBAAqB,GAAG,+BAA+B,CAAC;AAE9D,SAAS,cAAc;IACrB,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,qBAAqB,KAAK,CAAC;AACtF,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,KAAwB,EACxB,IAAkB;IAElB,IAAI,OAAO,wBAAe,KAAK,UAAU,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CACb,kFAAkF,CACnF,CAAC;IACJ,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,IAAA,wBAAe,EAAC,YAAY,CAAC,CAAC;IAClD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC3C,yEAAyE;IACzE,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,KAAK,EAAE,CAAC,CAAC;IAChD,OAAO,UAAU,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;AACvD,CAAC;AAED,qEAAqE;AACrE,SAAS,0BAA0B,CACjC,KAAc;IAEd,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAC1D,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,KAAkC,CAAC;IAClE,MAA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iB,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;KAChE,CAAC,CAAC;IACH,OAAO,oBAAoB,CACzB,OAAO,EACP,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,CACpD,CAAC;AACJ,CAAC,CAAC;AAEF,aAAa,CAAC,SAAS,GAAG,UAAU,OAAe;IACjD,MAAM,QAAQ,GAAG,IAAA,qBAAY,EAAC;QAC5B,IAAI,EAAE,yBAAyB;QAC/B,OAAO,EAAE,cAAc,EAAE;QACzB,MAAM,EAAE,qBAAqB;QAC7B,KAAK,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,iBAAiB,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;KAChE,CAAC,CAAC;IACH,OAAO,oBAAoB,CACzB,OAAO,EACP,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,EACjD,IAAA,8BAAyB,EAAC;QACxB,QAAQ,EAAE,EAAE,eAAe,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE;KAC5D,CAAC,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,aAAa,CAAC,cAAc,GAAG,UAAU,OAAe;IACtD,OAAO,IAAA,uBAAkB,EAAC;QACxB,KAAK,EAAE,qBAAqB,EAAE,CAAC,cAAc,CAAC,OAAO,CAAC;QACtD,UAAU,EAAE;YACV,oBAAoB,EAAE,IAAI;YAC1B,4BAA4B,EAAE,GAAG,EAAE,CAAC,oBAAoB;SACzD;KACF,CAAC,CAAC;AACL,CAAC,CAAC"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
2
|
-
|
|
2
|
+
import { wrapLanguageModel } from "ai";
|
|
3
|
+
type Provider = ReturnType<typeof createOpenAICompatible>;
|
|
4
|
+
type ChatModel = ReturnType<Provider>;
|
|
5
|
+
type EmbeddingModel = ReturnType<Provider["embeddingModel"]>;
|
|
6
|
+
type GatewayLanguageModel = ReturnType<typeof wrapLanguageModel>;
|
|
3
7
|
/**
|
|
4
|
-
*
|
|
8
|
+
* The recommended model interface for text generation through the Convex AI gateway.
|
|
9
|
+
* Use `messages` or `responses` only for endpoint-specific features.
|
|
10
|
+
*
|
|
5
11
|
* `getServiceToken` reuses one token for the current action, so calling this
|
|
6
12
|
* more than once in the same action is fine.
|
|
7
13
|
*/
|
|
8
14
|
export declare function convexGateway(modelId: string): ChatModel;
|
|
15
|
+
export declare namespace convexGateway {
|
|
16
|
+
var messages: (modelId: string) => GatewayLanguageModel;
|
|
17
|
+
var responses: (modelId: string) => GatewayLanguageModel;
|
|
18
|
+
var embeddingModel: (modelId: string) => EmbeddingModel;
|
|
19
|
+
}
|
|
9
20
|
export {};
|
|
10
21
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,sBAAsB,EAEvB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAKL,iBAAiB,EAClB,MAAM,IAAI,CAAC;AAGZ,KAAK,QAAQ,GAAG,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAC1D,KAAK,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC,KAAK,cAAc,GAAG,UAAU,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC,CAAC;AAE7D,KAAK,oBAAoB,GAAG,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAgHjE;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAExD;yBAFe,aAAa;4BAIe,MAAM,KAAG,oBAAoB;6BAa5B,MAAM,KAAG,oBAAoB;kCAgBxB,MAAM,KAAG,cAAc"}
|
package/dist/esm/index.js
CHANGED
|
@@ -1,30 +1,127 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
2
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
3
|
+
import { createOpenAICompatible, } from "@ai-sdk/openai-compatible";
|
|
4
|
+
import { defaultSettingsMiddleware, wrapEmbeddingModel, wrapLanguageModel, } from "ai";
|
|
2
5
|
import { getServiceToken } from "convex/server";
|
|
6
|
+
const maxEmbeddingsPerCall = 512;
|
|
7
|
+
// Official providers require a credential before gatewayFetch replaces it with a deployment JWT.
|
|
8
|
+
const placeholderCredential = "convex-gateway";
|
|
3
9
|
/**
|
|
4
10
|
* A deployment can set `CONVEX_INTERNAL_AI_GATEWAY_HOST` to reach a different
|
|
5
11
|
* gateway, which is how internal apps use staging.
|
|
6
12
|
*/
|
|
7
13
|
const productionGatewayHost = "https://ai-gateway.convex.dev";
|
|
14
|
+
function gatewayBaseURL() {
|
|
15
|
+
return `${process.env.CONVEX_INTERNAL_AI_GATEWAY_HOST || productionGatewayHost}/v1`;
|
|
16
|
+
}
|
|
17
|
+
async function gatewayFetch(input, init) {
|
|
18
|
+
if (typeof getServiceToken !== "function") {
|
|
19
|
+
throw new Error("@convex-dev/ai-sdk-provider requires convex >= 1.45 with getServiceToken support");
|
|
20
|
+
}
|
|
21
|
+
const token = await getServiceToken("ai-gateway");
|
|
22
|
+
const headers = new Headers(init?.headers);
|
|
23
|
+
// Deployment JWT is the only accepted credential for the hosted gateway.
|
|
24
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
25
|
+
return globalThis.fetch(input, { ...init, headers });
|
|
26
|
+
}
|
|
27
|
+
// The SDK's standard usage mapping omits the gateway's dollar costs.
|
|
28
|
+
function convexGatewayUsageMetadata(usage) {
|
|
29
|
+
if (!usage || typeof usage !== "object")
|
|
30
|
+
return undefined;
|
|
31
|
+
const { cost, cost_details } = usage;
|
|
32
|
+
const metadata = {};
|
|
33
|
+
if (typeof cost === "number")
|
|
34
|
+
metadata.cost = cost;
|
|
35
|
+
if (cost_details && typeof cost_details === "object") {
|
|
36
|
+
metadata.costDetails = cost_details;
|
|
37
|
+
}
|
|
38
|
+
return Object.keys(metadata).length > 0
|
|
39
|
+
? { convexGateway: metadata }
|
|
40
|
+
: undefined;
|
|
41
|
+
}
|
|
42
|
+
const costMetadataExtractor = {
|
|
43
|
+
extractMetadata: async ({ parsedBody }) => convexGatewayUsageMetadata(parsedBody?.usage),
|
|
44
|
+
createStreamExtractor: () => {
|
|
45
|
+
// Streamed responses deliver usage (incl. cost) on the final chunk.
|
|
46
|
+
let usage;
|
|
47
|
+
return {
|
|
48
|
+
processChunk(parsedChunk) {
|
|
49
|
+
const chunk = parsedChunk;
|
|
50
|
+
if (chunk?.usage)
|
|
51
|
+
usage = chunk.usage;
|
|
52
|
+
},
|
|
53
|
+
buildMetadata: () => convexGatewayUsageMetadata(usage),
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
function createGatewayProvider() {
|
|
58
|
+
return createOpenAICompatible({
|
|
59
|
+
name: "convexGateway",
|
|
60
|
+
baseURL: gatewayBaseURL(),
|
|
61
|
+
fetch: gatewayFetch,
|
|
62
|
+
metadataExtractor: costMetadataExtractor,
|
|
63
|
+
supportsStructuredOutputs: true,
|
|
64
|
+
supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/] }),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function sdkModelId(gatewayModelId, provider) {
|
|
68
|
+
const prefix = `${provider}/`;
|
|
69
|
+
const modelId = gatewayModelId.startsWith(prefix)
|
|
70
|
+
? gatewayModelId.slice(prefix.length)
|
|
71
|
+
: gatewayModelId;
|
|
72
|
+
// OpenRouter uses dots in Anthropic versions; the Anthropic SDK's capability lookup uses hyphens.
|
|
73
|
+
return provider === "anthropic" ? modelId.replaceAll(".", "-") : modelId;
|
|
74
|
+
}
|
|
75
|
+
function gatewayModelFetch(gatewayModelId, input, init) {
|
|
76
|
+
const body = JSON.parse(init?.body);
|
|
77
|
+
body.model = gatewayModelId;
|
|
78
|
+
return gatewayFetch(input, { ...init, body: JSON.stringify(body) });
|
|
79
|
+
}
|
|
80
|
+
function gatewayLanguageModel(modelId, model, middleware) {
|
|
81
|
+
return wrapLanguageModel({
|
|
82
|
+
model,
|
|
83
|
+
modelId,
|
|
84
|
+
// The gateway does not expose the providers' batch APIs.
|
|
85
|
+
middleware: middleware ?? { specificationVersion: "v4" },
|
|
86
|
+
});
|
|
87
|
+
}
|
|
8
88
|
/**
|
|
9
|
-
*
|
|
89
|
+
* The recommended model interface for text generation through the Convex AI gateway.
|
|
90
|
+
* Use `messages` or `responses` only for endpoint-specific features.
|
|
91
|
+
*
|
|
10
92
|
* `getServiceToken` reuses one token for the current action, so calling this
|
|
11
93
|
* more than once in the same action is fine.
|
|
12
94
|
*/
|
|
13
95
|
export function convexGateway(modelId) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
96
|
+
return createGatewayProvider()(modelId);
|
|
97
|
+
}
|
|
98
|
+
convexGateway.messages = function (modelId) {
|
|
99
|
+
const provider = createAnthropic({
|
|
100
|
+
name: "convexGateway.messages",
|
|
101
|
+
baseURL: gatewayBaseURL(),
|
|
102
|
+
authToken: placeholderCredential,
|
|
103
|
+
fetch: (input, init) => gatewayModelFetch(modelId, input, init),
|
|
104
|
+
});
|
|
105
|
+
return gatewayLanguageModel(modelId, provider.messages(sdkModelId(modelId, "anthropic")));
|
|
106
|
+
};
|
|
107
|
+
convexGateway.responses = function (modelId) {
|
|
108
|
+
const provider = createOpenAI({
|
|
109
|
+
name: "convexGateway.responses",
|
|
110
|
+
baseURL: gatewayBaseURL(),
|
|
111
|
+
apiKey: placeholderCredential,
|
|
112
|
+
fetch: (input, init) => gatewayModelFetch(modelId, input, init),
|
|
113
|
+
});
|
|
114
|
+
return gatewayLanguageModel(modelId, provider.responses(sdkModelId(modelId, "openai")), defaultSettingsMiddleware({
|
|
115
|
+
settings: { providerOptions: { openai: { store: false } } },
|
|
116
|
+
}));
|
|
117
|
+
};
|
|
118
|
+
convexGateway.embeddingModel = function (modelId) {
|
|
119
|
+
return wrapEmbeddingModel({
|
|
120
|
+
model: createGatewayProvider().embeddingModel(modelId),
|
|
121
|
+
middleware: {
|
|
122
|
+
specificationVersion: "v4",
|
|
123
|
+
overrideMaxEmbeddingsPerCall: () => maxEmbeddingsPerCall,
|
|
26
124
|
},
|
|
27
125
|
});
|
|
28
|
-
|
|
29
|
-
}
|
|
126
|
+
};
|
|
30
127
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EACL,sBAAsB,GAEvB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,yBAAyB,EAGzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAQhD,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,iGAAiG;AACjG,MAAM,qBAAqB,GAAG,gBAAgB,CAAC;AAE/C;;;GAGG;AACH,MAAM,qBAAqB,GAAG,+BAA+B,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AE,KAAK,EAAE,IAAI,CAAC;KAChE,CAAC,CAAC;IACH,OAAO,oBAAoB,CACzB,OAAO,EACP,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,EACjD,yBAAyB,CAAC;QACxB,QAAQ,EAAE,EAAE,eAAe,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE;KAC5D,CAAC,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,aAAa,CAAC,cAAc,GAAG,UAAU,OAAe;IACtD,OAAO,kBAAkB,CAAC;QACxB,KAAK,EAAE,qBAAqB,EAAE,CAAC,cAAc,CAAC,OAAO,CAAC;QACtD,UAAU,EAAE;YACV,oBAAoB,EAAE,IAAI;YAC1B,4BAA4B,EAAE,GAAG,EAAE,CAAC,oBAAoB;SACzD;KACF,CAAC,CAAC;AACL,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@convex-dev/ai-sdk-provider",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-alpha.1",
|
|
4
4
|
"description": "AI SDK provider for the Convex AI gateway",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -29,11 +29,13 @@
|
|
|
29
29
|
"selfLink": false
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
+
"@ai-sdk/anthropic": "4.0.40",
|
|
33
|
+
"@ai-sdk/openai": "4.0.45",
|
|
32
34
|
"@ai-sdk/openai-compatible": "3.0.14"
|
|
33
35
|
},
|
|
34
36
|
"peerDependencies": {
|
|
35
37
|
"ai": "^7.0.0",
|
|
36
|
-
"convex": "^1.
|
|
38
|
+
"convex": "^1.45.0"
|
|
37
39
|
},
|
|
38
40
|
"engines": {
|
|
39
41
|
"node": ">=22"
|
|
@@ -65,6 +67,7 @@
|
|
|
65
67
|
"scripts": {
|
|
66
68
|
"build": "tshy",
|
|
67
69
|
"test": "vitest run --typecheck",
|
|
68
|
-
"test:types": "tsc --noEmit"
|
|
70
|
+
"test:types": "tsc --noEmit",
|
|
71
|
+
"publish-package": "node src/scripts/publish.mjs"
|
|
69
72
|
}
|
|
70
73
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,27 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
2
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
3
|
+
import {
|
|
4
|
+
createOpenAICompatible,
|
|
5
|
+
type MetadataExtractor,
|
|
6
|
+
} from "@ai-sdk/openai-compatible";
|
|
7
|
+
import {
|
|
8
|
+
defaultSettingsMiddleware,
|
|
9
|
+
type JSONValue,
|
|
10
|
+
type ProviderMetadata,
|
|
11
|
+
wrapEmbeddingModel,
|
|
12
|
+
wrapLanguageModel,
|
|
13
|
+
} from "ai";
|
|
2
14
|
import { getServiceToken } from "convex/server";
|
|
3
15
|
|
|
4
|
-
type
|
|
16
|
+
type Provider = ReturnType<typeof createOpenAICompatible>;
|
|
17
|
+
type ChatModel = ReturnType<Provider>;
|
|
18
|
+
type EmbeddingModel = ReturnType<Provider["embeddingModel"]>;
|
|
19
|
+
type LanguageModel = Parameters<typeof wrapLanguageModel>[0]["model"];
|
|
20
|
+
type GatewayLanguageModel = ReturnType<typeof wrapLanguageModel>;
|
|
21
|
+
|
|
22
|
+
const maxEmbeddingsPerCall = 512;
|
|
23
|
+
// Official providers require a credential before gatewayFetch replaces it with a deployment JWT.
|
|
24
|
+
const placeholderCredential = "convex-gateway";
|
|
5
25
|
|
|
6
26
|
/**
|
|
7
27
|
* A deployment can set `CONVEX_INTERNAL_AI_GATEWAY_HOST` to reach a different
|
|
@@ -9,27 +29,152 @@ type ChatModel = ReturnType<ReturnType<typeof createOpenAICompatible>>;
|
|
|
9
29
|
*/
|
|
10
30
|
const productionGatewayHost = "https://ai-gateway.convex.dev";
|
|
11
31
|
|
|
32
|
+
function gatewayBaseURL(): string {
|
|
33
|
+
return `${process.env.CONVEX_INTERNAL_AI_GATEWAY_HOST || productionGatewayHost}/v1`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function gatewayFetch(
|
|
37
|
+
input: RequestInfo | URL,
|
|
38
|
+
init?: RequestInit,
|
|
39
|
+
): Promise<Response> {
|
|
40
|
+
if (typeof getServiceToken !== "function") {
|
|
41
|
+
throw new Error(
|
|
42
|
+
"@convex-dev/ai-sdk-provider requires convex >= 1.45 with getServiceToken support",
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
const token = await getServiceToken("ai-gateway");
|
|
46
|
+
const headers = new Headers(init?.headers);
|
|
47
|
+
// Deployment JWT is the only accepted credential for the hosted gateway.
|
|
48
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
49
|
+
return globalThis.fetch(input, { ...init, headers });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// The SDK's standard usage mapping omits the gateway's dollar costs.
|
|
53
|
+
function convexGatewayUsageMetadata(
|
|
54
|
+
usage: unknown,
|
|
55
|
+
): ProviderMetadata | undefined {
|
|
56
|
+
if (!usage || typeof usage !== "object") return undefined;
|
|
57
|
+
const { cost, cost_details } = usage as Record<string, JSONValue>;
|
|
58
|
+
const metadata: ProviderMetadata[string] = {};
|
|
59
|
+
if (typeof cost === "number") metadata.cost = cost;
|
|
60
|
+
if (cost_details && typeof cost_details === "object") {
|
|
61
|
+
metadata.costDetails = cost_details;
|
|
62
|
+
}
|
|
63
|
+
return Object.keys(metadata).length > 0
|
|
64
|
+
? { convexGateway: metadata }
|
|
65
|
+
: undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const costMetadataExtractor: MetadataExtractor = {
|
|
69
|
+
extractMetadata: async ({ parsedBody }) =>
|
|
70
|
+
convexGatewayUsageMetadata(
|
|
71
|
+
(parsedBody as { usage?: unknown } | undefined)?.usage,
|
|
72
|
+
),
|
|
73
|
+
createStreamExtractor: () => {
|
|
74
|
+
// Streamed responses deliver usage (incl. cost) on the final chunk.
|
|
75
|
+
let usage: unknown;
|
|
76
|
+
return {
|
|
77
|
+
processChunk(parsedChunk: unknown) {
|
|
78
|
+
const chunk = parsedChunk as { usage?: unknown } | undefined;
|
|
79
|
+
if (chunk?.usage) usage = chunk.usage;
|
|
80
|
+
},
|
|
81
|
+
buildMetadata: () => convexGatewayUsageMetadata(usage),
|
|
82
|
+
};
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
function createGatewayProvider(): Provider {
|
|
87
|
+
return createOpenAICompatible({
|
|
88
|
+
name: "convexGateway",
|
|
89
|
+
baseURL: gatewayBaseURL(),
|
|
90
|
+
fetch: gatewayFetch,
|
|
91
|
+
metadataExtractor: costMetadataExtractor,
|
|
92
|
+
supportsStructuredOutputs: true,
|
|
93
|
+
supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/] }),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function sdkModelId(
|
|
98
|
+
gatewayModelId: string,
|
|
99
|
+
provider: "anthropic" | "openai",
|
|
100
|
+
): string {
|
|
101
|
+
const prefix = `${provider}/`;
|
|
102
|
+
const modelId = gatewayModelId.startsWith(prefix)
|
|
103
|
+
? gatewayModelId.slice(prefix.length)
|
|
104
|
+
: gatewayModelId;
|
|
105
|
+
// OpenRouter uses dots in Anthropic versions; the Anthropic SDK's capability lookup uses hyphens.
|
|
106
|
+
return provider === "anthropic" ? modelId.replaceAll(".", "-") : modelId;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function gatewayModelFetch(
|
|
110
|
+
gatewayModelId: string,
|
|
111
|
+
input: RequestInfo | URL,
|
|
112
|
+
init?: RequestInit,
|
|
113
|
+
): Promise<Response> {
|
|
114
|
+
const body = JSON.parse(init?.body as string);
|
|
115
|
+
body.model = gatewayModelId;
|
|
116
|
+
return gatewayFetch(input, { ...init, body: JSON.stringify(body) });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function gatewayLanguageModel(
|
|
120
|
+
modelId: string,
|
|
121
|
+
model: LanguageModel,
|
|
122
|
+
middleware?: Parameters<typeof wrapLanguageModel>[0]["middleware"],
|
|
123
|
+
): GatewayLanguageModel {
|
|
124
|
+
return wrapLanguageModel({
|
|
125
|
+
model,
|
|
126
|
+
modelId,
|
|
127
|
+
// The gateway does not expose the providers' batch APIs.
|
|
128
|
+
middleware: middleware ?? { specificationVersion: "v4" },
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
12
132
|
/**
|
|
13
|
-
*
|
|
133
|
+
* The recommended model interface for text generation through the Convex AI gateway.
|
|
134
|
+
* Use `messages` or `responses` only for endpoint-specific features.
|
|
135
|
+
*
|
|
14
136
|
* `getServiceToken` reuses one token for the current action, so calling this
|
|
15
137
|
* more than once in the same action is fine.
|
|
16
138
|
*/
|
|
17
139
|
export function convexGateway(modelId: string): ChatModel {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
140
|
+
return createGatewayProvider()(modelId);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
convexGateway.messages = function (modelId: string): GatewayLanguageModel {
|
|
144
|
+
const provider = createAnthropic({
|
|
145
|
+
name: "convexGateway.messages",
|
|
146
|
+
baseURL: gatewayBaseURL(),
|
|
147
|
+
authToken: placeholderCredential,
|
|
148
|
+
fetch: (input, init) => gatewayModelFetch(modelId, input, init),
|
|
149
|
+
});
|
|
150
|
+
return gatewayLanguageModel(
|
|
151
|
+
modelId,
|
|
152
|
+
provider.messages(sdkModelId(modelId, "anthropic")),
|
|
153
|
+
);
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
convexGateway.responses = function (modelId: string): GatewayLanguageModel {
|
|
157
|
+
const provider = createOpenAI({
|
|
158
|
+
name: "convexGateway.responses",
|
|
159
|
+
baseURL: gatewayBaseURL(),
|
|
160
|
+
apiKey: placeholderCredential,
|
|
161
|
+
fetch: (input, init) => gatewayModelFetch(modelId, input, init),
|
|
162
|
+
});
|
|
163
|
+
return gatewayLanguageModel(
|
|
164
|
+
modelId,
|
|
165
|
+
provider.responses(sdkModelId(modelId, "openai")),
|
|
166
|
+
defaultSettingsMiddleware({
|
|
167
|
+
settings: { providerOptions: { openai: { store: false } } },
|
|
168
|
+
}),
|
|
169
|
+
);
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
convexGateway.embeddingModel = function (modelId: string): EmbeddingModel {
|
|
173
|
+
return wrapEmbeddingModel({
|
|
174
|
+
model: createGatewayProvider().embeddingModel(modelId),
|
|
175
|
+
middleware: {
|
|
176
|
+
specificationVersion: "v4",
|
|
177
|
+
overrideMaxEmbeddingsPerCall: () => maxEmbeddingsPerCall,
|
|
32
178
|
},
|
|
33
179
|
});
|
|
34
|
-
|
|
35
|
-
}
|
|
180
|
+
};
|