@ai-sdk/fireworks 0.0.0-8777c42a-20250115032312 → 0.0.0-98261322-20260122142521

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.
@@ -0,0 +1,196 @@
1
+ import { ImageModelV3, SharedV3Warning } from '@ai-sdk/provider';
2
+ import {
3
+ combineHeaders,
4
+ convertImageModelFileToDataUri,
5
+ createBinaryResponseHandler,
6
+ createStatusCodeErrorResponseHandler,
7
+ FetchFunction,
8
+ postJsonToApi,
9
+ } from '@ai-sdk/provider-utils';
10
+ import { FireworksImageModelId } from './fireworks-image-options';
11
+
12
+ interface FireworksImageModelBackendConfig {
13
+ urlFormat: 'workflows' | 'workflows_edit' | 'image_generation';
14
+ supportsSize?: boolean;
15
+ supportsEditing?: boolean;
16
+ }
17
+
18
+ const modelToBackendConfig: Partial<
19
+ Record<FireworksImageModelId, FireworksImageModelBackendConfig>
20
+ > = {
21
+ 'accounts/fireworks/models/flux-1-dev-fp8': {
22
+ urlFormat: 'workflows',
23
+ },
24
+ 'accounts/fireworks/models/flux-1-schnell-fp8': {
25
+ urlFormat: 'workflows',
26
+ },
27
+ 'accounts/fireworks/models/flux-kontext-pro': {
28
+ urlFormat: 'workflows_edit',
29
+ supportsEditing: true,
30
+ },
31
+ 'accounts/fireworks/models/flux-kontext-max': {
32
+ urlFormat: 'workflows_edit',
33
+ supportsEditing: true,
34
+ },
35
+ 'accounts/fireworks/models/playground-v2-5-1024px-aesthetic': {
36
+ urlFormat: 'image_generation',
37
+ supportsSize: true,
38
+ },
39
+ 'accounts/fireworks/models/japanese-stable-diffusion-xl': {
40
+ urlFormat: 'image_generation',
41
+ supportsSize: true,
42
+ },
43
+ 'accounts/fireworks/models/playground-v2-1024px-aesthetic': {
44
+ urlFormat: 'image_generation',
45
+ supportsSize: true,
46
+ },
47
+ 'accounts/fireworks/models/stable-diffusion-xl-1024-v1-0': {
48
+ urlFormat: 'image_generation',
49
+ supportsSize: true,
50
+ },
51
+ 'accounts/fireworks/models/SSD-1B': {
52
+ urlFormat: 'image_generation',
53
+ supportsSize: true,
54
+ },
55
+ };
56
+
57
+ function getUrlForModel(
58
+ baseUrl: string,
59
+ modelId: FireworksImageModelId,
60
+ hasInputImage: boolean,
61
+ ): string {
62
+ const config = modelToBackendConfig[modelId];
63
+
64
+ switch (config?.urlFormat) {
65
+ case 'image_generation':
66
+ return `${baseUrl}/image_generation/${modelId}`;
67
+ case 'workflows_edit':
68
+ // Kontext models: use base URL for editing (no suffix)
69
+ return `${baseUrl}/workflows/${modelId}`;
70
+ case 'workflows':
71
+ default:
72
+ // Standard FLUX models: use text_to_image for generation,
73
+ // but if input_image provided, some models may support editing
74
+ if (hasInputImage && config?.supportsEditing) {
75
+ return `${baseUrl}/workflows/${modelId}`;
76
+ }
77
+ return `${baseUrl}/workflows/${modelId}/text_to_image`;
78
+ }
79
+ }
80
+
81
+ interface FireworksImageModelConfig {
82
+ provider: string;
83
+ baseURL: string;
84
+ headers: () => Record<string, string>;
85
+ fetch?: FetchFunction;
86
+ _internal?: {
87
+ currentDate?: () => Date;
88
+ };
89
+ }
90
+
91
+ export class FireworksImageModel implements ImageModelV3 {
92
+ readonly specificationVersion = 'v3';
93
+ readonly maxImagesPerCall = 1;
94
+
95
+ get provider(): string {
96
+ return this.config.provider;
97
+ }
98
+
99
+ constructor(
100
+ readonly modelId: FireworksImageModelId,
101
+ private config: FireworksImageModelConfig,
102
+ ) {}
103
+
104
+ async doGenerate({
105
+ prompt,
106
+ n,
107
+ size,
108
+ aspectRatio,
109
+ seed,
110
+ providerOptions,
111
+ headers,
112
+ abortSignal,
113
+ files,
114
+ mask,
115
+ }: Parameters<ImageModelV3['doGenerate']>[0]): Promise<
116
+ Awaited<ReturnType<ImageModelV3['doGenerate']>>
117
+ > {
118
+ const warnings: Array<SharedV3Warning> = [];
119
+
120
+ const backendConfig = modelToBackendConfig[this.modelId];
121
+ if (!backendConfig?.supportsSize && size != null) {
122
+ warnings.push({
123
+ type: 'unsupported',
124
+ feature: 'size',
125
+ details:
126
+ 'This model does not support the `size` option. Use `aspectRatio` instead.',
127
+ });
128
+ }
129
+
130
+ // Use supportsSize as a proxy for whether the model does not support
131
+ // aspectRatio. This invariant holds for the current set of models.
132
+ if (backendConfig?.supportsSize && aspectRatio != null) {
133
+ warnings.push({
134
+ type: 'unsupported',
135
+ feature: 'aspectRatio',
136
+ details: 'This model does not support the `aspectRatio` option.',
137
+ });
138
+ }
139
+
140
+ // Handle files for image editing
141
+ const hasInputImage = files != null && files.length > 0;
142
+ let inputImage: string | undefined;
143
+
144
+ if (hasInputImage) {
145
+ inputImage = convertImageModelFileToDataUri(files[0]);
146
+
147
+ if (files.length > 1) {
148
+ warnings.push({
149
+ type: 'other',
150
+ message:
151
+ 'Fireworks only supports a single input image. Additional images are ignored.',
152
+ });
153
+ }
154
+ }
155
+
156
+ // Warn about mask - Fireworks Kontext models don't support explicit masks
157
+ if (mask != null) {
158
+ warnings.push({
159
+ type: 'unsupported',
160
+ feature: 'mask',
161
+ details:
162
+ 'Fireworks Kontext models do not support explicit masks. Use the prompt to describe the areas to edit.',
163
+ });
164
+ }
165
+
166
+ const splitSize = size?.split('x');
167
+ const currentDate = this.config._internal?.currentDate?.() ?? new Date();
168
+ const { value: response, responseHeaders } = await postJsonToApi({
169
+ url: getUrlForModel(this.config.baseURL, this.modelId, hasInputImage),
170
+ headers: combineHeaders(this.config.headers(), headers),
171
+ body: {
172
+ prompt,
173
+ aspect_ratio: aspectRatio,
174
+ seed,
175
+ samples: n,
176
+ ...(inputImage && { input_image: inputImage }),
177
+ ...(splitSize && { width: splitSize[0], height: splitSize[1] }),
178
+ ...(providerOptions.fireworks ?? {}),
179
+ },
180
+ failedResponseHandler: createStatusCodeErrorResponseHandler(),
181
+ successfulResponseHandler: createBinaryResponseHandler(),
182
+ abortSignal,
183
+ fetch: this.config.fetch,
184
+ });
185
+
186
+ return {
187
+ images: [response],
188
+ warnings,
189
+ response: {
190
+ timestamp: currentDate,
191
+ modelId: this.modelId,
192
+ headers: responseHeaders,
193
+ },
194
+ };
195
+ }
196
+ }
@@ -0,0 +1,12 @@
1
+ // https://fireworks.ai/models?type=image
2
+ export type FireworksImageModelId =
3
+ | 'accounts/fireworks/models/flux-1-dev-fp8'
4
+ | 'accounts/fireworks/models/flux-1-schnell-fp8'
5
+ | 'accounts/fireworks/models/flux-kontext-pro'
6
+ | 'accounts/fireworks/models/flux-kontext-max'
7
+ | 'accounts/fireworks/models/playground-v2-5-1024px-aesthetic'
8
+ | 'accounts/fireworks/models/japanese-stable-diffusion-xl'
9
+ | 'accounts/fireworks/models/playground-v2-1024px-aesthetic'
10
+ | 'accounts/fireworks/models/SSD-1B'
11
+ | 'accounts/fireworks/models/stable-diffusion-xl-1024-v1-0'
12
+ | (string & {});
@@ -0,0 +1,198 @@
1
+ import { describe, it, expect, vi, beforeEach, Mock } from 'vitest';
2
+ import { createFireworks } from './fireworks-provider';
3
+ import { LanguageModelV3, EmbeddingModelV3 } from '@ai-sdk/provider';
4
+ import { loadApiKey } from '@ai-sdk/provider-utils';
5
+ import {
6
+ OpenAICompatibleChatLanguageModel,
7
+ OpenAICompatibleCompletionLanguageModel,
8
+ OpenAICompatibleEmbeddingModel,
9
+ } from '@ai-sdk/openai-compatible';
10
+ import { FireworksImageModel } from './fireworks-image-model';
11
+
12
+ // Add type assertion for the mocked class
13
+ const OpenAICompatibleChatLanguageModelMock =
14
+ OpenAICompatibleChatLanguageModel as unknown as Mock;
15
+
16
+ vi.mock('@ai-sdk/openai-compatible', () => {
17
+ // Create mock constructor functions that behave like classes
18
+ const createMockConstructor = (providerName: string) => {
19
+ const mockConstructor = vi.fn().mockImplementation(function (
20
+ this: any,
21
+ modelId: string,
22
+ settings: any,
23
+ ) {
24
+ this.provider = providerName;
25
+ this.modelId = modelId;
26
+ this.settings = settings;
27
+ });
28
+ return mockConstructor;
29
+ };
30
+
31
+ return {
32
+ OpenAICompatibleChatLanguageModel: createMockConstructor('fireworks.chat'),
33
+ OpenAICompatibleCompletionLanguageModel: createMockConstructor(
34
+ 'fireworks.completion',
35
+ ),
36
+ OpenAICompatibleEmbeddingModel: createMockConstructor(
37
+ 'fireworks.embedding',
38
+ ),
39
+ };
40
+ });
41
+
42
+ vi.mock('@ai-sdk/provider-utils', async () => {
43
+ const actual = await vi.importActual('@ai-sdk/provider-utils');
44
+ return {
45
+ ...actual,
46
+ loadApiKey: vi.fn().mockReturnValue('mock-api-key'),
47
+ withoutTrailingSlash: vi.fn(url => url),
48
+ };
49
+ });
50
+
51
+ vi.mock('./fireworks-image-model', () => ({
52
+ FireworksImageModel: vi.fn(),
53
+ }));
54
+
55
+ describe('FireworksProvider', () => {
56
+ let mockLanguageModel: LanguageModelV3;
57
+ let mockEmbeddingModel: EmbeddingModelV3;
58
+
59
+ beforeEach(() => {
60
+ // Mock implementations of models
61
+ mockLanguageModel = {
62
+ // Add any required methods for LanguageModelV3
63
+ } as LanguageModelV3;
64
+ mockEmbeddingModel = {
65
+ // Add any required methods for EmbeddingModelV3
66
+ } as EmbeddingModelV3;
67
+
68
+ // Reset mocks
69
+ vi.clearAllMocks();
70
+ });
71
+
72
+ describe('createFireworks', () => {
73
+ it('should create a FireworksProvider instance with default options', () => {
74
+ const provider = createFireworks();
75
+ const model = provider('model-id');
76
+
77
+ // Use the mocked version
78
+ const constructorCall =
79
+ OpenAICompatibleChatLanguageModelMock.mock.calls[0];
80
+ const config = constructorCall[1];
81
+ config.headers();
82
+
83
+ expect(loadApiKey).toHaveBeenCalledWith({
84
+ apiKey: undefined,
85
+ environmentVariableName: 'FIREWORKS_API_KEY',
86
+ description: 'Fireworks API key',
87
+ });
88
+ });
89
+
90
+ it('should create a FireworksProvider instance with custom options', () => {
91
+ const options = {
92
+ apiKey: 'custom-key',
93
+ baseURL: 'https://custom.url',
94
+ headers: { 'Custom-Header': 'value' },
95
+ };
96
+ const provider = createFireworks(options);
97
+ const model = provider('model-id');
98
+
99
+ const constructorCall =
100
+ OpenAICompatibleChatLanguageModelMock.mock.calls[0];
101
+ const config = constructorCall[1];
102
+ config.headers();
103
+
104
+ expect(loadApiKey).toHaveBeenCalledWith({
105
+ apiKey: 'custom-key',
106
+ environmentVariableName: 'FIREWORKS_API_KEY',
107
+ description: 'Fireworks API key',
108
+ });
109
+ });
110
+
111
+ it('should return a chat model when called as a function', () => {
112
+ const provider = createFireworks();
113
+ const modelId = 'foo-model-id';
114
+
115
+ const model = provider(modelId);
116
+ expect(model).toBeInstanceOf(OpenAICompatibleChatLanguageModel);
117
+ });
118
+ });
119
+
120
+ describe('chatModel', () => {
121
+ it('should construct a chat model with correct configuration', () => {
122
+ const provider = createFireworks();
123
+ const modelId = 'fireworks-chat-model';
124
+
125
+ const model = provider.chatModel(modelId);
126
+
127
+ expect(model).toBeInstanceOf(OpenAICompatibleChatLanguageModel);
128
+ });
129
+ });
130
+
131
+ describe('completionModel', () => {
132
+ it('should construct a completion model with correct configuration', () => {
133
+ const provider = createFireworks();
134
+ const modelId = 'fireworks-completion-model';
135
+
136
+ const model = provider.completionModel(modelId);
137
+
138
+ expect(model).toBeInstanceOf(OpenAICompatibleCompletionLanguageModel);
139
+ });
140
+ });
141
+
142
+ describe('embeddingModel', () => {
143
+ it('should construct a text embedding model with correct configuration', () => {
144
+ const provider = createFireworks();
145
+ const modelId = 'fireworks-embedding-model';
146
+
147
+ const model = provider.embeddingModel(modelId);
148
+
149
+ expect(model).toBeInstanceOf(OpenAICompatibleEmbeddingModel);
150
+ });
151
+ });
152
+
153
+ describe('image', () => {
154
+ it('should construct an image model with correct configuration', () => {
155
+ const provider = createFireworks();
156
+ const modelId = 'accounts/fireworks/models/flux-1-dev-fp8';
157
+
158
+ const model = provider.image(modelId);
159
+
160
+ expect(model).toBeInstanceOf(FireworksImageModel);
161
+ expect(FireworksImageModel).toHaveBeenCalledWith(
162
+ modelId,
163
+ expect.objectContaining({
164
+ provider: 'fireworks.image',
165
+ baseURL: 'https://api.fireworks.ai/inference/v1',
166
+ }),
167
+ );
168
+ });
169
+
170
+ it('should use default settings when none provided', () => {
171
+ const provider = createFireworks();
172
+ const modelId = 'accounts/fireworks/models/flux-1-dev-fp8';
173
+
174
+ const model = provider.image(modelId);
175
+
176
+ expect(model).toBeInstanceOf(FireworksImageModel);
177
+ expect(FireworksImageModel).toHaveBeenCalledWith(
178
+ modelId,
179
+ expect.any(Object),
180
+ );
181
+ });
182
+
183
+ it('should respect custom baseURL', () => {
184
+ const customBaseURL = 'https://custom.api.fireworks.ai';
185
+ const provider = createFireworks({ baseURL: customBaseURL });
186
+ const modelId = 'accounts/fireworks/models/flux-1-dev-fp8';
187
+
188
+ provider.image(modelId);
189
+
190
+ expect(FireworksImageModel).toHaveBeenCalledWith(
191
+ modelId,
192
+ expect.objectContaining({
193
+ baseURL: customBaseURL,
194
+ }),
195
+ );
196
+ });
197
+ });
198
+ });
@@ -0,0 +1,172 @@
1
+ import {
2
+ OpenAICompatibleChatLanguageModel,
3
+ OpenAICompatibleCompletionLanguageModel,
4
+ OpenAICompatibleEmbeddingModel,
5
+ ProviderErrorStructure,
6
+ } from '@ai-sdk/openai-compatible';
7
+ import {
8
+ EmbeddingModelV3,
9
+ ImageModelV3,
10
+ LanguageModelV3,
11
+ ProviderV3,
12
+ } from '@ai-sdk/provider';
13
+ import {
14
+ FetchFunction,
15
+ loadApiKey,
16
+ withoutTrailingSlash,
17
+ withUserAgentSuffix,
18
+ } from '@ai-sdk/provider-utils';
19
+ import { z } from 'zod/v4';
20
+ import { FireworksChatModelId } from './fireworks-chat-options';
21
+ import { FireworksCompletionModelId } from './fireworks-completion-options';
22
+ import { FireworksEmbeddingModelId } from './fireworks-embedding-options';
23
+ import { FireworksImageModel } from './fireworks-image-model';
24
+ import { FireworksImageModelId } from './fireworks-image-options';
25
+ import { VERSION } from './version';
26
+
27
+ export type FireworksErrorData = z.infer<typeof fireworksErrorSchema>;
28
+
29
+ const fireworksErrorSchema = z.object({
30
+ error: z.string(),
31
+ });
32
+
33
+ const fireworksErrorStructure: ProviderErrorStructure<FireworksErrorData> = {
34
+ errorSchema: fireworksErrorSchema,
35
+ errorToMessage: data => data.error,
36
+ };
37
+
38
+ export interface FireworksProviderSettings {
39
+ /**
40
+ Fireworks API key. Default value is taken from the `FIREWORKS_API_KEY`
41
+ environment variable.
42
+ */
43
+ apiKey?: string;
44
+ /**
45
+ Base URL for the API calls.
46
+ */
47
+ baseURL?: string;
48
+ /**
49
+ Custom headers to include in the requests.
50
+ */
51
+ headers?: Record<string, string>;
52
+ /**
53
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
54
+ or to provide a custom fetch implementation for e.g. testing.
55
+ */
56
+ fetch?: FetchFunction;
57
+ }
58
+
59
+ export interface FireworksProvider extends ProviderV3 {
60
+ /**
61
+ Creates a model for text generation.
62
+ */
63
+ (modelId: FireworksChatModelId): LanguageModelV3;
64
+
65
+ /**
66
+ Creates a chat model for text generation.
67
+ */
68
+ chatModel(modelId: FireworksChatModelId): LanguageModelV3;
69
+
70
+ /**
71
+ Creates a completion model for text generation.
72
+ */
73
+ completionModel(modelId: FireworksCompletionModelId): LanguageModelV3;
74
+
75
+ /**
76
+ Creates a chat model for text generation.
77
+ */
78
+ languageModel(modelId: FireworksChatModelId): LanguageModelV3;
79
+
80
+ /**
81
+ Creates a text embedding model for text generation.
82
+ */
83
+ embeddingModel(modelId: FireworksEmbeddingModelId): EmbeddingModelV3;
84
+
85
+ /**
86
+ * @deprecated Use `embeddingModel` instead.
87
+ */
88
+ textEmbeddingModel(modelId: FireworksEmbeddingModelId): EmbeddingModelV3;
89
+
90
+ /**
91
+ Creates a model for image generation.
92
+ */
93
+ image(modelId: FireworksImageModelId): ImageModelV3;
94
+
95
+ /**
96
+ Creates a model for image generation.
97
+ */
98
+ imageModel(modelId: FireworksImageModelId): ImageModelV3;
99
+ }
100
+
101
+ const defaultBaseURL = 'https://api.fireworks.ai/inference/v1';
102
+
103
+ export function createFireworks(
104
+ options: FireworksProviderSettings = {},
105
+ ): FireworksProvider {
106
+ const baseURL = withoutTrailingSlash(options.baseURL ?? defaultBaseURL);
107
+ const getHeaders = () =>
108
+ withUserAgentSuffix(
109
+ {
110
+ Authorization: `Bearer ${loadApiKey({
111
+ apiKey: options.apiKey,
112
+ environmentVariableName: 'FIREWORKS_API_KEY',
113
+ description: 'Fireworks API key',
114
+ })}`,
115
+ ...options.headers,
116
+ },
117
+ `ai-sdk/fireworks/${VERSION}`,
118
+ );
119
+
120
+ interface CommonModelConfig {
121
+ provider: string;
122
+ url: ({ path }: { path: string }) => string;
123
+ headers: () => Record<string, string>;
124
+ fetch?: FetchFunction;
125
+ }
126
+
127
+ const getCommonModelConfig = (modelType: string): CommonModelConfig => ({
128
+ provider: `fireworks.${modelType}`,
129
+ url: ({ path }) => `${baseURL}${path}`,
130
+ headers: getHeaders,
131
+ fetch: options.fetch,
132
+ });
133
+
134
+ const createChatModel = (modelId: FireworksChatModelId) => {
135
+ return new OpenAICompatibleChatLanguageModel(modelId, {
136
+ ...getCommonModelConfig('chat'),
137
+ errorStructure: fireworksErrorStructure,
138
+ });
139
+ };
140
+
141
+ const createCompletionModel = (modelId: FireworksCompletionModelId) =>
142
+ new OpenAICompatibleCompletionLanguageModel(modelId, {
143
+ ...getCommonModelConfig('completion'),
144
+ errorStructure: fireworksErrorStructure,
145
+ });
146
+
147
+ const createEmbeddingModel = (modelId: FireworksEmbeddingModelId) =>
148
+ new OpenAICompatibleEmbeddingModel(modelId, {
149
+ ...getCommonModelConfig('embedding'),
150
+ errorStructure: fireworksErrorStructure,
151
+ });
152
+
153
+ const createImageModel = (modelId: FireworksImageModelId) =>
154
+ new FireworksImageModel(modelId, {
155
+ ...getCommonModelConfig('image'),
156
+ baseURL: baseURL ?? defaultBaseURL,
157
+ });
158
+
159
+ const provider = (modelId: FireworksChatModelId) => createChatModel(modelId);
160
+
161
+ provider.specificationVersion = 'v3' as const;
162
+ provider.completionModel = createCompletionModel;
163
+ provider.chatModel = createChatModel;
164
+ provider.languageModel = createChatModel;
165
+ provider.embeddingModel = createEmbeddingModel;
166
+ provider.textEmbeddingModel = createEmbeddingModel;
167
+ provider.image = createImageModel;
168
+ provider.imageModel = createImageModel;
169
+ return provider;
170
+ }
171
+
172
+ export const fireworks = createFireworks();
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ export type {
2
+ FireworksEmbeddingModelId,
3
+ FireworksEmbeddingProviderOptions,
4
+ } from './fireworks-embedding-options';
5
+ export { FireworksImageModel } from './fireworks-image-model';
6
+ export type { FireworksImageModelId } from './fireworks-image-options';
7
+ export { fireworks, createFireworks } from './fireworks-provider';
8
+ export type {
9
+ FireworksProvider,
10
+ FireworksProviderSettings,
11
+ FireworksErrorData,
12
+ } from './fireworks-provider';
13
+ export { VERSION } from './version';
package/src/version.ts ADDED
@@ -0,0 +1,6 @@
1
+ // Version string of this package injected at build time.
2
+ declare const __PACKAGE_VERSION__: string | undefined;
3
+ export const VERSION: string =
4
+ typeof __PACKAGE_VERSION__ !== 'undefined'
5
+ ? __PACKAGE_VERSION__
6
+ : '0.0.0-test';