Repository navigation
Expand file tree
/
Copy pathexample-image-recognition.ts
More file actions
169 lines (148 loc) · 5.48 KB
/
Copy pathexample-image-recognition.ts
File metadata and controls
169 lines (148 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/env node
/**
* SAP AI Provider - Image Recognition Example
*
* This example demonstrates multi-modal capabilities (text + images)
* using the SAP AI Provider with vision-enabled models.
*
* Authentication:
* - On SAP BTP: Automatically uses service binding (VCAP_SERVICES)
* - Locally: Set AICORE_SERVICE_KEY environment variable with your service key JSON
*/
// Load environment variables
import "dotenv/config";
import { APICallError, LoadAPIKeyError, NoSuchModelError } from "@ai-sdk/provider";
import { generateText } from "ai";
// In an application, import from the published V4 entrypoint:
// import { createSAPAIProvider } from "@jerome-benoit/sap-ai-provider/v4";
import { createSAPAIProvider } from "../src/index-v4";
import { parseSAPErrorResponseBody } from "./parse-sap-error-response-body.js";
/** Sends the embedded PNG together with a text question for visual interpretation. */
async function imageRecognitionExample() {
console.log("🖼️ SAP AI Image Recognition Example\n");
// Verify AICORE_SERVICE_KEY is set for local development
if (!process.env.AICORE_SERVICE_KEY && !process.env.VCAP_SERVICES) {
console.warn("⚠️ Warning: AICORE_SERVICE_KEY environment variable not set.");
console.warn(" Set it in your .env file or environment for local development.\n");
}
try {
const provider = createSAPAIProvider();
// Example 1: Using a public URL
console.log("📸 Example 1: Public URL Image");
console.log("==============================");
const { text: urlResponse } = await generateText({
messages: [
{
content: [
{
text: "What do you see in this image?",
type: "text",
},
{
data: {
type: "url",
url: new URL(
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/280px-PNG_transparency_demonstration_1.png",
),
},
mediaType: "image/png",
type: "file",
},
],
role: "user",
},
],
model: provider("gpt-4.1"),
});
console.log("🤖 Response:", urlResponse);
console.log("");
// Example 2: Using base64 encoded image
console.log("📸 Example 2: Base64 Encoded Image");
console.log("==================================");
// Small 1x1 semi-transparent yellow PNG for demo
const base64Image =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
const { text: base64Response } = await generateText({
messages: [
{
content: [
{
text: "Describe this image in detail.",
type: "text",
},
{
data: { data: base64Image, type: "data" },
mediaType: "image/png",
type: "file",
},
],
role: "user",
},
],
model: provider("gpt-4.1"),
});
console.log("🤖 Response:", base64Response);
console.log("");
// Example 3: Multiple images analysis
console.log("📸 Example 3: Multiple Images Analysis");
console.log("=====================================");
const { text: multiResponse } = await generateText({
messages: [
{
content: [
{
text: "Compare these two images and tell me what you notice:",
type: "text",
},
{
data: {
type: "url",
url: new URL(
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/280px-PNG_transparency_demonstration_1.png",
),
},
mediaType: "image/png",
type: "file",
},
{
data: { data: base64Image, type: "data" },
mediaType: "image/png",
type: "file",
},
],
role: "user",
},
],
model: provider("gpt-4.1"),
});
console.log("🤖 Response:", multiResponse);
console.log("");
console.log("✅ All examples completed successfully!");
} catch (error: unknown) {
process.exitCode = 1;
if (error instanceof LoadAPIKeyError) {
console.error("❌ Authentication Error:", error.name);
} else if (error instanceof NoSuchModelError) {
console.error("❌ Model Not Found:", error.modelId);
} else if (error instanceof APICallError) {
console.error("❌ API Call Error:", error.statusCode, error.name);
// Parse SAP-specific metadata
const sapError = parseSAPErrorResponseBody(error.responseBody);
if (sapError?.error.request_id) {
console.error(" SAP Request ID:", sapError.error.request_id);
}
} else {
const errorName = error instanceof Error ? error.name : "Unknown error";
console.error("❌ Example failed:", errorName);
}
console.error("\n💡 Troubleshooting tips:");
console.error(" - Ensure AICORE_SERVICE_KEY is set with valid credentials");
console.error(" - Check that your SAP AI Core instance is accessible");
console.error(" - Verify the model is available in your deployment");
}
}
imageRecognitionExample().catch((error: unknown) => {
process.exitCode = 1;
console.error("Example failed:", error instanceof Error ? error.name : "Unknown error");
});
export { imageRecognitionExample };