Skip to content

Commit 110716c

Browse files
committed
add streaming example to README
1 parent a9b899b commit 110716c

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

README.md

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md).
188188
</details>
189189
<!-- End Standalone functions [standalone-funcs] -->
190190

191-
<!-- Start Server-sent event streaming [eventstream] -->
191+
<!-- No Server-sent event streaming [eventstream] -->
192192
## Server-sent event streaming
193193

194194
[Server-sent events][mdn-sse] are used to stream content from certain
@@ -224,9 +224,50 @@ run();
224224

225225
```
226226

227+
You can also pass the `stream` parameter to the `complete` method to control streaming behavior dynamically:
228+
229+
```typescript
230+
import { OpenRouter } from "open-router";
231+
232+
const openRouter = new OpenRouter({
233+
bearerAuth: process.env["OPENROUTER_BEARER_AUTH"] ?? "",
234+
});
235+
236+
async function run() {
237+
const isStreaming = true; // Set to false for non-streaming response
238+
239+
const result = await openRouter.chat.complete({
240+
model: "openai/gpt-3.5-turbo",
241+
stream: isStreaming,
242+
messages: [
243+
{
244+
role: "user",
245+
content: "Hello, how are you?",
246+
},
247+
],
248+
});
249+
250+
// Handle response based on stream setting
251+
if (isStreaming) {
252+
console.log("Streaming response:");
253+
for await (const chunk of result) {
254+
if (chunk.data?.choices?.[0]?.delta?.content) {
255+
process.stdout.write(chunk.data.choices[0].delta.content);
256+
}
257+
}
258+
console.log("\n\nStreaming completed");
259+
} else {
260+
console.log("Non-streaming response:");
261+
console.log(JSON.stringify(result, null, 2));
262+
}
263+
}
264+
265+
run();
266+
```
267+
227268
[mdn-sse]: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
228269
[mdn-for-await-of]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
229-
<!-- End Server-sent event streaming [eventstream] -->
270+
<!-- No Server-sent event streaming [eventstream] -->
230271

231272
<!-- Start Retries [retries] -->
232273
## Retries

0 commit comments

Comments
 (0)