UNPKG

neura-sdk

Version:

TypeScript SDK for interacting with the Neura AI API

56 lines (55 loc) 2.13 kB
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime"; import { useState, useEffect, useCallback, useRef } from 'react'; import { useNeura } from './NeuraProvider'; export const NeuraStream = ({ options, onChunk, onComplete, onError, children, }) => { const { sdk } = useNeura(); const [chunks, setChunks] = useState([]); const [fullText, setFullText] = useState(''); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Use a ref to keep track of the stream const streamRef = useRef(null); const startStream = useCallback(() => { // Reset state setChunks([]); setFullText(''); setLoading(true); setError(null); // Clean up previous stream if it exists if (streamRef.current) { streamRef.current.removeAllListeners(); } // Create a new stream const stream = sdk.createCompletionStream(options); streamRef.current = stream; let accumulatedText = ''; stream.on('chunk', (chunk) => { setChunks((prev) => [...prev, chunk]); accumulatedText += chunk.chunk; setFullText(accumulatedText); onChunk?.(chunk); }); stream.on('done', () => { setLoading(false); onComplete?.(accumulatedText); }); // Fix: Update the error handler to accept both Error and ProcessingError stream.on('error', (err) => { setError(err); setLoading(false); onError?.(err); }); }, [sdk, options, onChunk, onComplete, onError]); // Start streaming when the component mounts useEffect(() => { startStream(); // Clean up the stream when the component unmounts return () => { if (streamRef.current) { streamRef.current.removeAllListeners(); streamRef.current = null; } }; }, [startStream]); return _jsx(_Fragment, { children: children({ chunks, fullText, loading, error, restart: startStream }) }); };