default-protocol.vue 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <script setup lang="tsx">
  2. import { TagsOutlined } from '@ant-design/icons-vue';
  3. import { Button, Flex } from 'ant-design-vue';
  4. import { Bubble, ThoughtChain, XStream } from 'ant-design-x-vue';
  5. import { computed, ref } from 'vue';
  6. defineOptions({ name: 'AXXStreamDefaultProtocol' });
  7. const contentChunks = ['He', 'llo', ', w', 'or', 'ld!'];
  8. function mockReadableStream() {
  9. const sseChunks: string[] = [];
  10. for (let i = 0; i < contentChunks.length; i++) {
  11. const sseEventPart = `event: message\ndata: {"id":"${i}","content":"${contentChunks[i]}"}\n\n`;
  12. sseChunks.push(sseEventPart);
  13. }
  14. return new ReadableStream({
  15. async start(controller) {
  16. for (const chunk of sseChunks) {
  17. await new Promise((resolve) => setTimeout(resolve, 100));
  18. controller.enqueue(new TextEncoder().encode(chunk));
  19. }
  20. controller.close();
  21. },
  22. });
  23. }
  24. const lines = ref<Record<string, string>[]>([]);
  25. const content = computed(() => lines.value.map((line) => JSON.parse(line.data).content).join(''));
  26. async function readStream() {
  27. // 🌟 Read the stream
  28. for await (const chunk of XStream({
  29. readableStream: mockReadableStream(),
  30. })) {
  31. console.log(chunk);
  32. lines.value = [...lines.value, chunk];
  33. }
  34. }
  35. defineRender(() => {
  36. return (
  37. <Flex gap={8}>
  38. <div>
  39. {/* -------------- Emit -------------- */}
  40. <Button type="primary" onClick={readStream} style={{ marginBottom: '16px' }}>
  41. Mock Default Protocol - SSE
  42. </Button>
  43. {/* -------------- Content Concat -------------- */}
  44. {content.value && <Bubble content={content.value} />}
  45. </div>
  46. <div>
  47. <ThoughtChain
  48. items={
  49. lines.value.length
  50. ? [
  51. {
  52. title: 'Mock Default Protocol - Log',
  53. status: 'success',
  54. icon: <TagsOutlined />,
  55. content: (
  56. <pre style={{ overflow: 'scroll' }}>
  57. {lines.value.map((i) => (
  58. <code key={i.data}>{i.data}</code>
  59. ))}
  60. </pre>
  61. ),
  62. },
  63. ]
  64. : []
  65. }
  66. />
  67. </div>
  68. </Flex>
  69. )
  70. });
  71. </script>
  72. <style scoped>
  73. pre {
  74. width: 'auto';
  75. margin: 0;
  76. code {
  77. display: block;
  78. padding: 12px 16px;
  79. font-size: 14px;
  80. }
  81. }
  82. </style>