basic.vue 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <script setup lang="ts">
  2. import { UserOutlined } from '@ant-design/icons-vue';
  3. import { Flex } from 'ant-design-vue';
  4. import { Bubble, Sender, useXAgent, useXChat, type BubbleListProps } from 'ant-design-x-vue';
  5. import { ref } from 'vue';
  6. defineOptions({ name: 'AXUseXChatBasicSetup' });
  7. const sleep = () => new Promise((resolve) => setTimeout(resolve, 1000));
  8. const roles: BubbleListProps['roles'] = {
  9. ai: {
  10. placement: 'start',
  11. avatar: { icon: UserOutlined, style: { background: '#fde3cf' } },
  12. typing: { step: 5, interval: 20 },
  13. style: {
  14. maxWidth: '600px',
  15. },
  16. },
  17. local: {
  18. placement: 'end',
  19. avatar: { icon: UserOutlined, style: { background: '#87d068' } },
  20. },
  21. };
  22. const mockSuccess = ref(false);
  23. const content = ref('');
  24. const senderLoading = ref(false);
  25. const setContent = (v: string) => {
  26. content.value = v;
  27. }
  28. // Agent for request
  29. const [agent] = useXAgent({
  30. request: async ({ message }, { onSuccess, onError }) => {
  31. senderLoading.value = true;
  32. await sleep();
  33. senderLoading.value = false;
  34. mockSuccess.value = !mockSuccess.value;
  35. if (mockSuccess.value) {
  36. onSuccess(`Mock success return. You said: ${message}`);
  37. }
  38. onError(new Error('Mock request failed'));
  39. },
  40. });
  41. // Chat messages
  42. const { onRequest, messages } = useXChat({
  43. agent: agent.value,
  44. requestPlaceholder: 'Waiting...',
  45. requestFallback: 'Mock failed return. Please try again later.',
  46. });
  47. </script>
  48. <template>
  49. <Flex
  50. vertical
  51. gap="middle"
  52. >
  53. <Bubble.List
  54. :roles="roles"
  55. :style="{ maxHeight: '300px' }"
  56. :items="messages.map(({ id, message, status }) => ({
  57. key: id,
  58. loading: status === 'loading',
  59. role: status === 'local' ? 'local' : 'ai',
  60. content: message,
  61. }))"
  62. />
  63. <Sender
  64. :loading="senderLoading"
  65. :value="content"
  66. :on-change="setContent"
  67. :on-submit="(nextContent) => {
  68. onRequest(nextContent);
  69. setContent('');
  70. }"
  71. />
  72. </Flex>
  73. </template>