|
| 1 | +import 'dotenv/config'; |
| 2 | +import {Pipe, printStreamToStdout, StreamText} from '../../pipes/pipes'; |
| 3 | + |
| 4 | +// You can write your own — or use printStreamToStdout() from the SDK. |
| 5 | +const helperPrintStream = async (stream: StreamText) => { |
| 6 | + for await (const chunk of stream) { |
| 7 | + // Streaming text part — a single word or several. |
| 8 | + const textPart = chunk.choices[0]?.delta?.content || ''; |
| 9 | + |
| 10 | + // Demo: Print the stream — you can use it however. |
| 11 | + process.stdout.write(textPart); |
| 12 | + } |
| 13 | +}; |
| 14 | + |
| 15 | +const printChat = async ({ |
| 16 | + userMessage, |
| 17 | + stream, |
| 18 | +}: { |
| 19 | + userMessage: string; |
| 20 | + stream: StreamText; |
| 21 | +}) => { |
| 22 | + console.log(`\n`); |
| 23 | + console.log(`User: `, userMessage); |
| 24 | + console.log(`AI: `); |
| 25 | + await printStreamToStdout(stream); |
| 26 | +}; |
| 27 | + |
| 28 | +const myGeneratePipe = async () => { |
| 29 | + console.log('\n============= GENERATE PIPE ============='); |
| 30 | + |
| 31 | + // Initiate the Pipe. |
| 32 | + const myPipe = new Pipe({ |
| 33 | + apiKey: process.env.LANGBASE_SDK_GENERATE_PIPE!, |
| 34 | + }); |
| 35 | + |
| 36 | + // Generate the text by asking a question. |
| 37 | + const userMsg = 'Who is an AI Engineer?'; |
| 38 | + let {stream} = await myPipe.streamText({ |
| 39 | + messages: [{role: 'user', content: userMsg}], |
| 40 | + }); |
| 41 | + |
| 42 | + // Print. |
| 43 | + await printChat({userMessage: userMsg, stream}); |
| 44 | +}; |
| 45 | + |
| 46 | +const myChatPipe = async () => { |
| 47 | + console.log('\n\n============= CHAT PIPE ============='); |
| 48 | + |
| 49 | + // Initiate the Pipe. |
| 50 | + const myPipe = new Pipe({ |
| 51 | + apiKey: process.env.LANGBASE_SDK_CHAT_PIPE!, |
| 52 | + }); |
| 53 | + |
| 54 | + // Message 1: Tell the AI about something. |
| 55 | + const userMsg1 = 'My company is ⌘ Langbase.'; |
| 56 | + let {stream, threadId} = await myPipe.streamText({ |
| 57 | + messages: [{role: 'user', content: userMsg1}], |
| 58 | + chat: true, |
| 59 | + }); |
| 60 | + |
| 61 | + await printChat({userMessage: userMsg1, stream}); |
| 62 | + |
| 63 | + // Message 2: Ask the AI about what you told in previous message. |
| 64 | + const userMsg2 = 'What is the name of my company?'; |
| 65 | + const {stream: stream2} = await myPipe.streamText({ |
| 66 | + messages: [{role: 'user', content: userMsg2}], |
| 67 | + threadId, |
| 68 | + chat: true, |
| 69 | + }); |
| 70 | + await printChat({userMessage: userMsg2, stream: stream2}); |
| 71 | +}; |
| 72 | + |
| 73 | +(async () => { |
| 74 | + await myGeneratePipe(); |
| 75 | + await myChatPipe(); |
| 76 | +})(); |
0 commit comments