default-protocol.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <script setup lang="ts">
  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, h } from 'vue';
  6. defineOptions({ name: 'AXXStreamDefaultProtocolSetup' });
  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(() =>
  26. lines.value.map((line) => JSON.parse(line.data).content).join(''),
  27. );
  28. async function readStream() {
  29. // 🌟 Read the stream
  30. for await (const chunk of XStream({
  31. readableStream: mockReadableStream(),
  32. })) {
  33. console.log(chunk);
  34. lines.value = [...lines.value, chunk];
  35. }
  36. }
  37. </script>
  38. <template>
  39. <Flex :gap="8">
  40. <div>
  41. <!-- -------------- Emit -------------- -->
  42. <Button
  43. type="primary"
  44. :style="{ marginBottom: '16px' }"
  45. @click="readStream"
  46. >
  47. Mock Default Protocol - SSE
  48. </Button>
  49. <!-- -------------- Content Concat -------------- -->
  50. <Bubble
  51. v-if="content"
  52. :content="content"
  53. />
  54. </div>
  55. <div>
  56. <ThoughtChain
  57. :items="
  58. lines.length
  59. ? [
  60. {
  61. title: 'Mock Default Protocol - Log',
  62. status: 'success',
  63. icon: h(TagsOutlined),
  64. content: h('pre', { style: { overflow: 'scroll' } }, [
  65. lines.map((i) => h('code', { key: i.data }, i.data)),
  66. ]),
  67. },
  68. ]
  69. : []
  70. "
  71. />
  72. </div>
  73. </Flex>
  74. </template>
  75. <style scoped>
  76. pre {
  77. width: 'auto';
  78. margin: 0;
  79. code {
  80. display: block;
  81. padding: 12px 16px;
  82. font-size: 14px;
  83. }
  84. }
  85. </style>