@convex-dev/ai-sdk-provider 0.0.1-alpha.0 → 0.2.0-alpha.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/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.44 or later, AI SDK 7, and Node.js 22 or later.
54
+ Requires Convex 1.45 or later, AI SDK 7, and Node.js 22 or later.
@@ -1,10 +1,21 @@
1
1
  import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
2
- type ChatModel = ReturnType<ReturnType<typeof createOpenAICompatible>>;
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
- * Chat model for the hosted Convex AI gateway.
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":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAGnE,KAAK,SAAS,GAAG,UAAU,CAAC,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC,CAAC;AAQvE;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAkBxD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAGL,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;AA6EjE;;;;;;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"}
@@ -1,33 +1,99 @@
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
+ function createGatewayProvider() {
31
+ return (0, openai_compatible_1.createOpenAICompatible)({
32
+ name: "convexGateway",
33
+ baseURL: gatewayBaseURL(),
34
+ fetch: gatewayFetch,
35
+ supportsStructuredOutputs: true,
36
+ supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/] }),
37
+ });
38
+ }
39
+ function sdkModelId(gatewayModelId, provider) {
40
+ const prefix = `${provider}/`;
41
+ const modelId = gatewayModelId.startsWith(prefix)
42
+ ? gatewayModelId.slice(prefix.length)
43
+ : gatewayModelId;
44
+ // OpenRouter uses dots in Anthropic versions; the Anthropic SDK's capability lookup uses hyphens.
45
+ return provider === "anthropic" ? modelId.replaceAll(".", "-") : modelId;
46
+ }
47
+ function gatewayModelFetch(gatewayModelId, input, init) {
48
+ const body = JSON.parse(init?.body);
49
+ body.model = gatewayModelId;
50
+ return gatewayFetch(input, { ...init, body: JSON.stringify(body) });
51
+ }
52
+ function gatewayLanguageModel(modelId, model, middleware) {
53
+ return (0, ai_1.wrapLanguageModel)({
54
+ model,
55
+ modelId,
56
+ // The gateway does not expose the providers' batch APIs.
57
+ middleware: middleware ?? { specificationVersion: "v4" },
58
+ });
59
+ }
11
60
  /**
12
- * Chat model for the hosted Convex AI gateway.
61
+ * The recommended model interface for text generation through the Convex AI gateway.
62
+ * Use `messages` or `responses` only for endpoint-specific features.
63
+ *
13
64
  * `getServiceToken` reuses one token for the current action, so calling this
14
65
  * more than once in the same action is fine.
15
66
  */
16
67
  function convexGateway(modelId) {
17
- const provider = (0, openai_compatible_1.createOpenAICompatible)({
18
- name: "convexGateway",
19
- baseURL: `${process.env.CONVEX_INTERNAL_AI_GATEWAY_HOST || productionGatewayHost}/v1`,
20
- fetch: async (input, init) => {
21
- if (typeof server_1.getServiceToken !== "function") {
22
- throw new Error("@convex-dev/ai-sdk-provider requires convex >= 1.44 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 await globalThis.fetch(input, { ...init, headers });
68
+ return createGatewayProvider()(modelId);
69
+ }
70
+ convexGateway.messages = function (modelId) {
71
+ const provider = (0, anthropic_1.createAnthropic)({
72
+ name: "convexGateway.messages",
73
+ baseURL: gatewayBaseURL(),
74
+ authToken: placeholderCredential,
75
+ fetch: (input, init) => gatewayModelFetch(modelId, input, init),
76
+ });
77
+ return gatewayLanguageModel(modelId, provider.messages(sdkModelId(modelId, "anthropic")));
78
+ };
79
+ convexGateway.responses = function (modelId) {
80
+ const provider = (0, openai_1.createOpenAI)({
81
+ name: "convexGateway.responses",
82
+ baseURL: gatewayBaseURL(),
83
+ apiKey: placeholderCredential,
84
+ fetch: (input, init) => gatewayModelFetch(modelId, input, init),
85
+ });
86
+ return gatewayLanguageModel(modelId, provider.responses(sdkModelId(modelId, "openai")), (0, ai_1.defaultSettingsMiddleware)({
87
+ settings: { providerOptions: { openai: { store: false } } },
88
+ }));
89
+ };
90
+ convexGateway.embeddingModel = function (modelId) {
91
+ return (0, ai_1.wrapEmbeddingModel)({
92
+ model: createGatewayProvider().embeddingModel(modelId),
93
+ middleware: {
94
+ specificationVersion: "v4",
95
+ overrideMaxEmbeddingsPerCall: () => maxEmbeddingsPerCall,
29
96
  },
30
97
  });
31
- return provider(modelId);
32
- }
98
+ };
33
99
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAgBA,sCAkBC;AAlCD,iEAAmE;AACnE,0CAAgD;AAIhD;;;GAGG;AACH,MAAM,qBAAqB,GAAG,+BAA+B,CAAC;AAE9D;;;;GAIG;AACH,SAAgB,aAAa,CAAC,OAAe;IAC3C,MAAM,QAAQ,GAAG,IAAA,0CAAsB,EAAC;QACtC,IAAI,EAAE,eAAe;QACrB,OAAO,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,qBAAqB,KAAK;QACrF,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;YAC3B,IAAI,OAAO,wBAAe,KAAK,UAAU,EAAE,CAAC;gBAC1C,MAAM,IAAI,KAAK,CACb,kFAAkF,CACnF,C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a,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"}
@@ -1,10 +1,21 @@
1
1
  import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
2
- type ChatModel = ReturnType<ReturnType<typeof createOpenAICompatible>>;
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
- * Chat model for the hosted Convex AI gateway.
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":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAGnE,KAAK,SAAS,GAAG,UAAU,CAAC,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC,CAAC;AAQvE;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAkBxD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAGL,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;AA6EjE;;;;;;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,96 @@
1
+ import { createAnthropic } from "@ai-sdk/anthropic";
2
+ import { createOpenAI } from "@ai-sdk/openai";
1
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
+ function createGatewayProvider() {
28
+ return createOpenAICompatible({
29
+ name: "convexGateway",
30
+ baseURL: gatewayBaseURL(),
31
+ fetch: gatewayFetch,
32
+ supportsStructuredOutputs: true,
33
+ supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/] }),
34
+ });
35
+ }
36
+ function sdkModelId(gatewayModelId, provider) {
37
+ const prefix = `${provider}/`;
38
+ const modelId = gatewayModelId.startsWith(prefix)
39
+ ? gatewayModelId.slice(prefix.length)
40
+ : gatewayModelId;
41
+ // OpenRouter uses dots in Anthropic versions; the Anthropic SDK's capability lookup uses hyphens.
42
+ return provider === "anthropic" ? modelId.replaceAll(".", "-") : modelId;
43
+ }
44
+ function gatewayModelFetch(gatewayModelId, input, init) {
45
+ const body = JSON.parse(init?.body);
46
+ body.model = gatewayModelId;
47
+ return gatewayFetch(input, { ...init, body: JSON.stringify(body) });
48
+ }
49
+ function gatewayLanguageModel(modelId, model, middleware) {
50
+ return wrapLanguageModel({
51
+ model,
52
+ modelId,
53
+ // The gateway does not expose the providers' batch APIs.
54
+ middleware: middleware ?? { specificationVersion: "v4" },
55
+ });
56
+ }
8
57
  /**
9
- * Chat model for the hosted Convex AI gateway.
58
+ * The recommended model interface for text generation through the Convex AI gateway.
59
+ * Use `messages` or `responses` only for endpoint-specific features.
60
+ *
10
61
  * `getServiceToken` reuses one token for the current action, so calling this
11
62
  * more than once in the same action is fine.
12
63
  */
13
64
  export function convexGateway(modelId) {
14
- const provider = createOpenAICompatible({
15
- name: "convexGateway",
16
- baseURL: `${process.env.CONVEX_INTERNAL_AI_GATEWAY_HOST || productionGatewayHost}/v1`,
17
- fetch: async (input, init) => {
18
- if (typeof getServiceToken !== "function") {
19
- throw new Error("@convex-dev/ai-sdk-provider requires convex >= 1.44 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 await globalThis.fetch(input, { ...init, headers });
65
+ return createGatewayProvider()(modelId);
66
+ }
67
+ convexGateway.messages = function (modelId) {
68
+ const provider = createAnthropic({
69
+ name: "convexGateway.messages",
70
+ baseURL: gatewayBaseURL(),
71
+ authToken: placeholderCredential,
72
+ fetch: (input, init) => gatewayModelFetch(modelId, input, init),
73
+ });
74
+ return gatewayLanguageModel(modelId, provider.messages(sdkModelId(modelId, "anthropic")));
75
+ };
76
+ convexGateway.responses = function (modelId) {
77
+ const provider = createOpenAI({
78
+ name: "convexGateway.responses",
79
+ baseURL: gatewayBaseURL(),
80
+ apiKey: placeholderCredential,
81
+ fetch: (input, init) => gatewayModelFetch(modelId, input, init),
82
+ });
83
+ return gatewayLanguageModel(modelId, provider.responses(sdkModelId(modelId, "openai")), defaultSettingsMiddleware({
84
+ settings: { providerOptions: { openai: { store: false } } },
85
+ }));
86
+ };
87
+ convexGateway.embeddingModel = function (modelId) {
88
+ return wrapEmbeddingModel({
89
+ model: createGatewayProvider().embeddingModel(modelId),
90
+ middleware: {
91
+ specificationVersion: "v4",
92
+ overrideMaxEmbeddingsPerCall: () => maxEmbeddingsPerCall,
26
93
  },
27
94
  });
28
- return provider(modelId);
29
- }
95
+ };
30
96
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAIhD;;;GAGG;AACH,MAAM,qBAAqB,GAAG,+BAA+B,CAAC;AAE9D;;;;GAI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5B,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,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.0.1-alpha.0",
3
+ "version": "0.2.0-alpha.0",
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.44.0"
38
+ "convex": "^1.45.0"
37
39
  },
38
40
  "engines": {
39
41
  "node": ">=22"
@@ -44,7 +46,7 @@
44
46
  "tshy": "^3.0.0",
45
47
  "typescript": "~5.0.3",
46
48
  "vitest": "^4.1.0",
47
- "convex": "1.44.0"
49
+ "convex": "1.45.0"
48
50
  },
49
51
  "exports": {
50
52
  ".": {
@@ -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,22 @@
1
+ import { createAnthropic } from "@ai-sdk/anthropic";
2
+ import { createOpenAI } from "@ai-sdk/openai";
1
3
  import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
4
+ import {
5
+ defaultSettingsMiddleware,
6
+ wrapEmbeddingModel,
7
+ wrapLanguageModel,
8
+ } from "ai";
2
9
  import { getServiceToken } from "convex/server";
3
10
 
4
- type ChatModel = ReturnType<ReturnType<typeof createOpenAICompatible>>;
11
+ type Provider = ReturnType<typeof createOpenAICompatible>;
12
+ type ChatModel = ReturnType<Provider>;
13
+ type EmbeddingModel = ReturnType<Provider["embeddingModel"]>;
14
+ type LanguageModel = Parameters<typeof wrapLanguageModel>[0]["model"];
15
+ type GatewayLanguageModel = ReturnType<typeof wrapLanguageModel>;
16
+
17
+ const maxEmbeddingsPerCall = 512;
18
+ // Official providers require a credential before gatewayFetch replaces it with a deployment JWT.
19
+ const placeholderCredential = "convex-gateway";
5
20
 
6
21
  /**
7
22
  * A deployment can set `CONVEX_INTERNAL_AI_GATEWAY_HOST` to reach a different
@@ -9,27 +24,117 @@ type ChatModel = ReturnType<ReturnType<typeof createOpenAICompatible>>;
9
24
  */
10
25
  const productionGatewayHost = "https://ai-gateway.convex.dev";
11
26
 
27
+ function gatewayBaseURL(): string {
28
+ return `${process.env.CONVEX_INTERNAL_AI_GATEWAY_HOST || productionGatewayHost}/v1`;
29
+ }
30
+
31
+ async function gatewayFetch(
32
+ input: RequestInfo | URL,
33
+ init?: RequestInit,
34
+ ): Promise<Response> {
35
+ if (typeof getServiceToken !== "function") {
36
+ throw new Error(
37
+ "@convex-dev/ai-sdk-provider requires convex >= 1.45 with getServiceToken support",
38
+ );
39
+ }
40
+ const token = await getServiceToken("ai-gateway");
41
+ const headers = new Headers(init?.headers);
42
+ // Deployment JWT is the only accepted credential for the hosted gateway.
43
+ headers.set("Authorization", `Bearer ${token}`);
44
+ return globalThis.fetch(input, { ...init, headers });
45
+ }
46
+
47
+ function createGatewayProvider(): Provider {
48
+ return createOpenAICompatible({
49
+ name: "convexGateway",
50
+ baseURL: gatewayBaseURL(),
51
+ fetch: gatewayFetch,
52
+ supportsStructuredOutputs: true,
53
+ supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/] }),
54
+ });
55
+ }
56
+
57
+ function sdkModelId(
58
+ gatewayModelId: string,
59
+ provider: "anthropic" | "openai",
60
+ ): string {
61
+ const prefix = `${provider}/`;
62
+ const modelId = gatewayModelId.startsWith(prefix)
63
+ ? gatewayModelId.slice(prefix.length)
64
+ : gatewayModelId;
65
+ // OpenRouter uses dots in Anthropic versions; the Anthropic SDK's capability lookup uses hyphens.
66
+ return provider === "anthropic" ? modelId.replaceAll(".", "-") : modelId;
67
+ }
68
+
69
+ function gatewayModelFetch(
70
+ gatewayModelId: string,
71
+ input: RequestInfo | URL,
72
+ init?: RequestInit,
73
+ ): Promise<Response> {
74
+ const body = JSON.parse(init?.body as string);
75
+ body.model = gatewayModelId;
76
+ return gatewayFetch(input, { ...init, body: JSON.stringify(body) });
77
+ }
78
+
79
+ function gatewayLanguageModel(
80
+ modelId: string,
81
+ model: LanguageModel,
82
+ middleware?: Parameters<typeof wrapLanguageModel>[0]["middleware"],
83
+ ): GatewayLanguageModel {
84
+ return wrapLanguageModel({
85
+ model,
86
+ modelId,
87
+ // The gateway does not expose the providers' batch APIs.
88
+ middleware: middleware ?? { specificationVersion: "v4" },
89
+ });
90
+ }
91
+
12
92
  /**
13
- * Chat model for the hosted Convex AI gateway.
93
+ * The recommended model interface for text generation through the Convex AI gateway.
94
+ * Use `messages` or `responses` only for endpoint-specific features.
95
+ *
14
96
  * `getServiceToken` reuses one token for the current action, so calling this
15
97
  * more than once in the same action is fine.
16
98
  */
17
99
  export function convexGateway(modelId: string): ChatModel {
18
- const provider = createOpenAICompatible({
19
- name: "convexGateway",
20
- baseURL: `${process.env.CONVEX_INTERNAL_AI_GATEWAY_HOST || productionGatewayHost}/v1`,
21
- fetch: async (input, init) => {
22
- if (typeof getServiceToken !== "function") {
23
- throw new Error(
24
- "@convex-dev/ai-sdk-provider requires convex >= 1.44 with getServiceToken support",
25
- );
26
- }
27
- const token = await getServiceToken("ai-gateway");
28
- const headers = new Headers(init?.headers);
29
- // Deployment JWT is the only accepted credential for the hosted gateway.
30
- headers.set("Authorization", `Bearer ${token}`);
31
- return await globalThis.fetch(input, { ...init, headers });
100
+ return createGatewayProvider()(modelId);
101
+ }
102
+
103
+ convexGateway.messages = function (modelId: string): GatewayLanguageModel {
104
+ const provider = createAnthropic({
105
+ name: "convexGateway.messages",
106
+ baseURL: gatewayBaseURL(),
107
+ authToken: placeholderCredential,
108
+ fetch: (input, init) => gatewayModelFetch(modelId, input, init),
109
+ });
110
+ return gatewayLanguageModel(
111
+ modelId,
112
+ provider.messages(sdkModelId(modelId, "anthropic")),
113
+ );
114
+ };
115
+
116
+ convexGateway.responses = function (modelId: string): GatewayLanguageModel {
117
+ const provider = createOpenAI({
118
+ name: "convexGateway.responses",
119
+ baseURL: gatewayBaseURL(),
120
+ apiKey: placeholderCredential,
121
+ fetch: (input, init) => gatewayModelFetch(modelId, input, init),
122
+ });
123
+ return gatewayLanguageModel(
124
+ modelId,
125
+ provider.responses(sdkModelId(modelId, "openai")),
126
+ defaultSettingsMiddleware({
127
+ settings: { providerOptions: { openai: { store: false } } },
128
+ }),
129
+ );
130
+ };
131
+
132
+ convexGateway.embeddingModel = function (modelId: string): EmbeddingModel {
133
+ return wrapEmbeddingModel({
134
+ model: createGatewayProvider().embeddingModel(modelId),
135
+ middleware: {
136
+ specificationVersion: "v4",
137
+ overrideMaxEmbeddingsPerCall: () => maxEmbeddingsPerCall,
32
138
  },
33
139
  });
34
- return provider(modelId);
35
- }
140
+ };