basic.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <script setup lang="tsx">
  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: 'AXUseXChatBasic' });
  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. defineRender(() => {
  48. return (
  49. <Flex vertical gap="middle">
  50. <Bubble.List
  51. roles={roles}
  52. style={{ maxHeight: '300px' }}
  53. items={messages.value.map(({ id, message, status }) => ({
  54. key: id,
  55. loading: status === 'loading',
  56. role: status === 'local' ? 'local' : 'ai',
  57. content: message,
  58. }))}
  59. />
  60. <Sender
  61. loading={senderLoading.value}
  62. value={content.value}
  63. onChange={setContent}
  64. onSubmit={(nextContent) => {
  65. onRequest(nextContent);
  66. setContent('');
  67. }}
  68. />
  69. </Flex>
  70. )
  71. });
  72. </script>