Repository navigation
Expand file tree
/
Copy pathexample-streaming-chat.ts
More file actions
104 lines (87 loc) · 3.74 KB
/
Copy pathexample-streaming-chat.ts
File metadata and controls
104 lines (87 loc) · 3.74 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
#!/usr/bin/env node
/**
* SAP AI Provider - Streaming Chat Example
*
* This example demonstrates streaming chat completion using the SAP AI Provider
* with the Vercel AI SDK's streamText function.
*
* 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 { streamText } 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";
/** Consumes text incrementally while reporting final usage after completion. */
async function streamingChatExample() {
console.log("🧪 Streaming Chat with Vercel AI SDK (streamText)\n");
try {
// 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");
}
console.log("🔄 Creating SAP AI provider...");
const provider = createSAPAIProvider();
const model = provider("gpt-4.1");
console.log("📡 Starting streaming response...\n");
let streamError: unknown;
const result = streamText({
model,
onError: ({ error }) => {
streamError = error;
},
prompt: "Write a short story about a cat who learns to code.",
});
let characterCount = 0;
for await (const textPart of result.textStream) {
process.stdout.write(textPart);
characterCount += textPart.length;
}
// textStream omits error events; preserve the original error for the handler below.
if (streamError !== undefined) {
throw streamError instanceof Error
? streamError
: new Error("Streaming failed", { cause: streamError });
}
console.log("\n\n✅ Stream finished");
console.log("📄 Total characters:", characterCount);
// Get usage after stream completes
const finalUsage = await result.usage;
console.log(
"📊 Usage:",
`${String(finalUsage.inputTokens)} prompt + ${String(finalUsage.outputTokens)} completion tokens`,
);
} 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("❌ Streaming 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");
}
}
streamingChatExample().catch((error: unknown) => {
process.exitCode = 1;
console.error("Example failed:", error instanceof Error ? error.name : "Unknown error");
});
export { streamingChatExample };