Overview
This post shows how to stream LLM output from the SAP Cloud SDK for AI orchestration module into a CAP service and directly forward it to the browser over WebSockets.
It covers:
Enabling WebSocket support in CAP
Here's a quick demo that shows the end result:
You can also explore the full example project on GitHub
Prerequisites
Backend
CAP does not provide WebSocket support out of the box, but the community library makes it easy. Add it by running the following command inside the folder of your CAP application:
npm add -js-community/websocketTo stream LLM responses to your CAP service, add the orchestration module from the SAP Cloud SDK for AI:
npm add -ai-sdk/orchestrationService Definition (CDS)
You can expose a service over both OData and WebSocket by annotating the service:
@protocol: ['odata', 'websocket']
// @ws for websocket onlyevent storyChunk { message: String; }​function generateStory(topic : String) returns String;​
then, the client should also pass topic as a parameter
Key points:
Service implementation (JavaScript/TypeScript)
In your service handlers you can access WebSocket features via:
LLM streaming with the SAP Cloud SDK for AI orchestration module:
The orchestration module allows you to stream the output from an LLM. It also makes it easy to switch to another model of any provider later.
Flow:
const response = await orchestrationClient.stream({messages: messages});​for await (const chunk of response.stream) {​
and, for each chunk of text received, emit your CDS event via
req.context.ws.service.emit('storyChunk', { message: chunk })​Notes:
Frontend
The browser has a built-in WebSocket API - no extra library required.
Steps:
const protocol = window.location.protocol === "https:" ? "wss://" : "ws://";
const host = window.location.host;
socket.current = new WebSocket(protocol + host + "/api/ws/story"); // adjust path if needed​Notes (Approuter):
If you are calling the CAP service via the SAP Approuter:
"websockets": {
"enabled": true
}2. Set up handlers:
socket.onopen = () => {
console.log("WebSocket connected!")
};
socket.onmessage = (event) => {
const receivedMessage = JSON.parse(event.data);
if (receivedMessage.event === "storyChunk") {
console.log("Chunk:", receivedMessage.data.message);
}
};
socket.onerror = (err) => console.error("WebSocket error", err);
socket.onclose = () => console.log("WebSocket closed");​Summary
What we've achieved
We’ve seen how to integrate LLM output streaming into a CAP service by combining the SAP Cloud SDK for AI orchestration module with community WebSocket support, enabling real-time delivery of AI-generated content directly to a browser frontend.
Steps to achieve
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
| User | Count |
|---|---|
| 17 | |
| 16 | |
| 14 | |
| 13 | |
| 10 | |
| 10 | |
| 9 | |
| 9 | |
| 9 | |
| 9 |