reasoning.tsx 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Derived from vercel/ai-elements (skills/ai-elements/scripts/reasoning.tsx).
  3. * Copyright 2023 Vercel, Inc. Licensed under Apache-2.0.
  4. * Modified by ZCode: local integration, formatting and adaptations.
  5. * See THIRD-PARTY-NOTICES.md in the repository root for license and provenance.
  6. */
  7. "use client";
  8. import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";
  9. import { useCallback, useEffect, useState } from "react";
  10. const reasoningSteps = [
  11. "Let me think about this problem step by step.",
  12. "\n\nFirst, I need to understand what the user is asking for.",
  13. "\n\nThey want a reasoning component that opens automatically when streaming begins and closes when streaming finishes. The component should be composable and follow existing patterns in the codebase.",
  14. "\n\nThis seems like a collapsible component with state management would be the right approach.",
  15. ].join("");
  16. const Example = () => {
  17. const [content, setContent] = useState("");
  18. const [isStreaming, setIsStreaming] = useState(false);
  19. const [currentTokenIndex, setCurrentTokenIndex] = useState(0);
  20. const [tokens, setTokens] = useState<string[]>([]);
  21. // Function to chunk text into fake tokens of 3-4 characters
  22. const chunkIntoTokens = useCallback((text: string): string[] => {
  23. const chunks: string[] = [];
  24. let i = 0;
  25. while (i < text.length) {
  26. // Random size between 3-4
  27. const chunkSize = Math.floor(Math.random() * 2) + 3;
  28. chunks.push(text.slice(i, i + chunkSize));
  29. i += chunkSize;
  30. }
  31. return chunks;
  32. }, []);
  33. useEffect(() => {
  34. const tokenizedSteps = chunkIntoTokens(reasoningSteps);
  35. setTokens(tokenizedSteps);
  36. setContent("");
  37. setCurrentTokenIndex(0);
  38. setIsStreaming(true);
  39. }, [chunkIntoTokens]);
  40. useEffect(() => {
  41. if (!isStreaming || currentTokenIndex >= tokens.length) {
  42. if (isStreaming) {
  43. setIsStreaming(false);
  44. }
  45. return;
  46. }
  47. // Faster interval since we're streaming smaller chunks
  48. const timer = setTimeout(() => {
  49. setContent((prev) => prev + tokens[currentTokenIndex]);
  50. setCurrentTokenIndex((prev) => prev + 1);
  51. }, 25);
  52. return () => clearTimeout(timer);
  53. }, [isStreaming, currentTokenIndex, tokens]);
  54. return (
  55. <div className="w-full p-4" style={{ height: "300px" }}>
  56. <Reasoning className="w-full" isStreaming={isStreaming}>
  57. <ReasoningTrigger />
  58. <ReasoningContent>{content}</ReasoningContent>
  59. </Reasoning>
  60. </div>
  61. );
  62. };
  63. export default Example;