Skip to content

Commit 1915dfa

Browse files
authored
Merge pull request #51 from cosmicjs/tony/ai
add: AI endpoints
2 parents 45adff6 + 245eabc commit 1915dfa

File tree

5 files changed

+187
-2
lines changed

5 files changed

+187
-2
lines changed

.changeset/seven-brooms-sip.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@cosmicjs/sdk': minor
3+
---
4+
5+
Adds AI methods: generateText and generateImage

README.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,82 @@ Use the `objects.deleteOne()` method to delete an Object by specifying the Objec
121121
await cosmic.objects.deleteOne('5ff75368c2dfa81a91695cec');
122122
```
123123

124+
## AI Capabilities
125+
126+
Cosmic provides AI-powered text and image generation capabilities through the SDK.
127+
128+
### Generate Text [[see docs](https://www.cosmicjs.com/docs/api/ai#generate-text)]
129+
130+
Use the `ai.generateText()` method to generate text content using AI models. You must provide either a `prompt` or `messages` parameter.
131+
132+
#### Using a simple prompt:
133+
134+
```jsx
135+
const textResponse = await cosmic.ai.generateText({
136+
prompt: 'Write a product description for a coffee mug',
137+
max_tokens: 500, // optional
138+
});
139+
140+
console.log(textResponse.text);
141+
console.log(textResponse.usage); // { input_tokens: 10, output_tokens: 150 }
142+
```
143+
144+
#### Using messages for chat-based models:
145+
146+
```jsx
147+
const chatResponse = await cosmic.ai.generateText({
148+
messages: [
149+
{ role: 'user', content: 'Tell me about coffee mugs' },
150+
{
151+
role: 'assistant',
152+
content: 'Coffee mugs are vessels designed to hold hot beverages...',
153+
},
154+
{ role: 'user', content: 'What materials are they typically made from?' },
155+
],
156+
max_tokens: 500, // optional
157+
});
158+
159+
console.log(chatResponse.text);
160+
console.log(chatResponse.usage);
161+
```
162+
163+
### Analyze Images and Files
164+
165+
The AI model can analyze images and files when generating text responses. This feature works with both the `prompt` and `messages` approaches.
166+
167+
```jsx
168+
const textWithImageResponse = await cosmic.ai.generateText({
169+
prompt: 'Describe this coffee mug and suggest improvements to its design',
170+
media_url: 'https://imgix.cosmicjs.com/your-image-url.jpg',
171+
max_tokens: 500,
172+
});
173+
174+
console.log(textWithImageResponse.text);
175+
console.log(textWithImageResponse.usage);
176+
```
177+
178+
### Generate Image [[see docs](https://www.cosmicjs.com/docs/api/ai#generate-image)]
179+
180+
Use the `ai.generateImage()` method to create AI-generated images based on text prompts.
181+
182+
```jsx
183+
const imageResponse = await cosmic.ai.generateImage({
184+
prompt: 'A serene mountain landscape at sunset',
185+
// Optional parameters
186+
metadata: { tags: ['landscape', 'mountains', 'sunset'] },
187+
folder: 'ai-generated-images',
188+
alt_text: 'A beautiful mountain landscape with a colorful sunset',
189+
});
190+
191+
// Access the generated image properties
192+
console.log(imageResponse.media.url); // Direct URL to the generated image
193+
console.log(imageResponse.media.imgix_url); // Imgix-enhanced URL for additional transformations
194+
console.log(imageResponse.media.width); // Image width
195+
console.log(imageResponse.media.height); // Image height
196+
console.log(imageResponse.media.alt_text); // Alt text for the image
197+
console.log(imageResponse.revised_prompt); // Potentially revised prompt used by the AI
198+
```
199+
124200
## Learn more
125201

126202
Go to the [Cosmic docs](https://www.cosmicjs.com/docs) to learn more capabilities.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@cosmicjs/sdk",
3-
"version": "1.3.2",
3+
"version": "1.3.4",
44
"description": "The official client module for Cosmic. This module helps you easily add dynamic content to your website or application using the Cosmic headless CMS.",
55
"keywords": [
66
"headlesscms",
@@ -63,4 +63,4 @@
6363
"npx eslint --fix"
6464
]
6565
}
66-
}
66+
}

src/clients/bucket/ai/index.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { BucketConfig, APIConfig } from '../../../types/config.types';
2+
import { requestHandler } from '../../../utils/request.handler';
3+
4+
export interface GenerateTextOptions {
5+
prompt?: string;
6+
media_url?: string;
7+
model?: string;
8+
max_tokens?: number;
9+
stream?: boolean;
10+
messages?: Array<{
11+
role: 'user' | 'assistant';
12+
content: string;
13+
}>;
14+
}
15+
16+
export interface GenerateImageOptions {
17+
prompt: string;
18+
model?: string;
19+
metadata?: Record<string, any>;
20+
folder?: string;
21+
alt_text?: string;
22+
}
23+
24+
export interface TextGenerationResponse {
25+
text: string;
26+
usage: {
27+
input_tokens: number;
28+
output_tokens: number;
29+
};
30+
}
31+
32+
export interface ImageGenerationResponse {
33+
media: {
34+
id: string;
35+
name: string;
36+
original_name: string;
37+
size: number;
38+
type: string;
39+
bucket: string;
40+
created_at: string;
41+
created_by: string | null;
42+
modified_at: string;
43+
modified_by: string | null;
44+
width: number;
45+
height: number;
46+
alt_text?: string;
47+
url: string;
48+
imgix_url: string;
49+
metadata?: Record<string, any>;
50+
folder?: string | null;
51+
};
52+
revised_prompt: string;
53+
}
54+
55+
export const aiChainMethods = (
56+
bucketConfig: BucketConfig,
57+
apiConfig: APIConfig
58+
) => {
59+
const { uploadUrl } = apiConfig;
60+
const { bucketSlug, writeKey } = bucketConfig;
61+
62+
const headers: Record<string, string> = {
63+
'Content-Type': 'application/json',
64+
};
65+
66+
if (writeKey) {
67+
headers.Authorization = `Bearer ${writeKey}`;
68+
}
69+
70+
return {
71+
generateText: async (
72+
options: GenerateTextOptions
73+
): Promise<TextGenerationResponse> => {
74+
if (!options.prompt && !options.messages) {
75+
throw new Error('Either prompt or messages must be provided');
76+
}
77+
const endpoint = `${uploadUrl}/buckets/${bucketSlug}/ai/text`;
78+
return requestHandler('POST', endpoint, options, headers);
79+
},
80+
81+
generateImage: async (
82+
options: GenerateImageOptions
83+
): Promise<ImageGenerationResponse> => {
84+
const endpoint = `${uploadUrl}/buckets/${bucketSlug}/ai/image`;
85+
return requestHandler('POST', endpoint, options, headers);
86+
},
87+
};
88+
};

src/clients/bucket/index.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,21 @@ import { mediaChainMethods } from './media';
44
import { objectsChainMethods } from './objects';
55
import { objectTypesChainMethods } from './objectTypes';
66
import { objectRevisionsChainMethods } from './objectRevisions';
7+
import { aiChainMethods } from './ai';
8+
import type {
9+
GenerateTextOptions,
10+
TextGenerationResponse,
11+
GenerateImageOptions,
12+
ImageGenerationResponse,
13+
} from './ai';
14+
15+
// Re-export the types
16+
export type {
17+
GenerateTextOptions,
18+
TextGenerationResponse,
19+
GenerateImageOptions,
20+
ImageGenerationResponse,
21+
};
722

823
export const createBucketClient = (config: BucketConfig) => {
924
const bucketConfig: BucketConfig = {
@@ -18,6 +33,7 @@ export const createBucketClient = (config: BucketConfig) => {
1833
objectTypes: objectTypesChainMethods(bucketConfig, apiConfig),
1934
objectRevisions: objectRevisionsChainMethods(bucketConfig, apiConfig),
2035
media: mediaChainMethods(bucketConfig, apiConfig),
36+
ai: aiChainMethods(bucketConfig, apiConfig),
2137
};
2238
};
2339

0 commit comments

Comments
 (0)