|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import {Button} from '@/components/ui/button'; |
| 4 | +import {Input} from '@/components/ui/input'; |
| 5 | +import {getRunner} from 'langbase'; |
| 6 | +import {useState} from 'react'; |
| 7 | + |
| 8 | +export default function RunStreamExample() { |
| 9 | + const [prompt, setPrompt] = useState(''); |
| 10 | + const [completion, setCompletion] = useState(''); |
| 11 | + const [loading, setLoading] = useState(false); |
| 12 | + |
| 13 | + const handleSubmit = async (e: React.FormEvent) => { |
| 14 | + e.preventDefault(); |
| 15 | + if (!prompt.trim() || loading) return; |
| 16 | + |
| 17 | + setLoading(true); |
| 18 | + setCompletion(''); |
| 19 | + |
| 20 | + try { |
| 21 | + const response = await fetch('/langbase/pipe/run-stream', { |
| 22 | + method: 'POST', |
| 23 | + body: JSON.stringify({prompt}), |
| 24 | + headers: {'Content-Type': 'text/plain'}, |
| 25 | + }); |
| 26 | + |
| 27 | + if (response.body) { |
| 28 | + const stream = getRunner(response.body); |
| 29 | + |
| 30 | + // Method #1 to get all of the chunk. |
| 31 | + for await (const chunk of stream) { |
| 32 | + const content = chunk?.choices[0]?.delta?.content; |
| 33 | + content && setCompletion(prev => prev + content); |
| 34 | + } |
| 35 | + |
| 36 | + // // Method #2 to get only the chunk's content as delta of the chunks |
| 37 | + // stream.on('content', content => { |
| 38 | + // setCompletion(prev => prev + content); |
| 39 | + // }); |
| 40 | + } |
| 41 | + } catch (error) { |
| 42 | + setLoading(false); |
| 43 | + console.error('Error:', error); |
| 44 | + } finally { |
| 45 | + setLoading(false); |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + return ( |
| 50 | + <div className="bg-neutral-200 rounded-md p-2 flex flex-col gap-2 w-full"> |
| 51 | + <div className="flex flex-col gap-2 w-full"> |
| 52 | + <p className="text-lg font-semibold"> |
| 53 | + 1. Stream Text{' '} |
| 54 | + <a |
| 55 | + className="text-indigo-500" |
| 56 | + href="https://langbase.com/docs/langbase-sdk/stream-text" |
| 57 | + > |
| 58 | + `pipe.run()` |
| 59 | + </a>{' '} |
| 60 | + with Route Handler |
| 61 | + </p> |
| 62 | + <p className="text-muted-foreground"> |
| 63 | + Ask a prompt to stream a text completion. |
| 64 | + </p> |
| 65 | + </div> |
| 66 | + <form |
| 67 | + onSubmit={handleSubmit} |
| 68 | + className="flex flex-col w-full items-center gap-2" |
| 69 | + > |
| 70 | + <Input |
| 71 | + type="text" |
| 72 | + placeholder="Enter prompt message here" |
| 73 | + onChange={e => setPrompt(e.target.value)} |
| 74 | + value={prompt} |
| 75 | + required |
| 76 | + /> |
| 77 | + <Button type="submit" className="w-full" disabled={loading}> |
| 78 | + {loading ? 'AI is thinking...' : 'Ask AI'} |
| 79 | + </Button> |
| 80 | + </form> |
| 81 | + {completion && ( |
| 82 | + <p className="mt-4"> |
| 83 | + <strong>Stream:</strong> {completion} |
| 84 | + </p> |
| 85 | + )} |
| 86 | + </div> |
| 87 | + ); |
| 88 | +} |
0 commit comments