Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

image-generation-example.ts

93 lines2.8 KB

1import { AI } from "@tanstack/ai";
2import { OpenAIAdapter } from "@tanstack/ai-openai";
3
4// Initialize AI with OpenAI adapter
5const ai = new AI({
6 adapters: {
7 openai: new OpenAIAdapter({
8 apiKey: process.env.OPENAI_API_KEY || "",
9 }),
10 },
11});
13// Example 1: Generate a single image with DALL-E 3
14async function generateSingleImage() {
15 const result = await ai.image({
16 adapter: "openai",
17 model: "dall-e-3", // Type-safe! Only "dall-e-3" | "dall-e-2" are allowed
18 prompt: "A beautiful sunset over mountains with a lake in the foreground",
19 size: "1024x1024",
20 providerOptions: {
21 openai: {
22 quality: "hd",
23 style: "vivid",
24 },
25 },
26 });
28 console.log("Generated image:", result.image?.mediaType);
29 console.log("Base64 data URL:", result.image?.base64.substring(0, 50) + "...");
30 console.log("Binary data length:", result.image?.uint8Array.length);
31}
33// Example 2: Generate multiple images with DALL-E 2
34async function generateMultipleImages() {
35 const result = await ai.image({
36 adapter: "openai",
37 model: "dall-e-2", // Type-safe model selection
38 prompt: "A cute cat wearing a hat",
39 n: 3, // Generate 3 images
40 size: "512x512",
41 });
43 console.log(`Generated ${result.images?.length} images`);
44 result.images?.forEach((image, i) => {
45 console.log(`Image ${i + 1}:`, image.mediaType);
46 });
47}
49// Example 3: Using fallback pattern (if openai fails, try another adapter)
50// Note: Currently only OpenAI supports image generation, but the API is ready for more adapters
51async function withFallback() {
52 const result = await ai.image({
53 adapter: "openai",
54 model: "dall-e-3",
55 prompt: "A futuristic cityscape at night",
56 // The AI class will automatically fall back to other adapters if primary fails
57 // and they support image generation
58 });
60 console.log("Generated with fallback support:", result.image?.mediaType);
61}
63// Example 4: Type safety - these will show TypeScript errors:
64async function typeErrorExamples() {
65 // ❌ Error: "invalid-model" is not assignable to "dall-e-3" | "dall-e-2"
66 // await ai.image({
67 // adapter: "openai",
68 // model: "invalid-model",
69 // prompt: "test",
70 // });
72 // ❌ Error: anthropic adapter doesn't have imageModels
73 // await ai.image({
74 // adapter: "anthropic",
75 // model: "claude-3-opus-20240229",
76 // prompt: "test",
77 // });
78}
80// Run examples
81async function main() {
82 console.log("=== Single Image Generation ===");
83 await generateSingleImage();
85 console.log("\n=== Multiple Images Generation ===");
86 await generateMultipleImages();
88 console.log("\n=== With Fallback ===");
89 await withFallback();
90}
92// Uncomment to run:
93// main().catch(console.error);