|
| 1 | +import { parseSSEResponse } from '~utils/sse' |
| 2 | +import { AbstractBot, SendMessageParams } from '../abstract-bot' |
| 3 | +import { requestHostPermission } from '~app/utils/permissions' |
| 4 | +import { ChatError, ErrorCode } from '~utils/errors' |
| 5 | +import { createConversation } from './api' |
| 6 | +import { uuid } from '~utils' |
| 7 | + |
| 8 | +function generateMessageId() { |
| 9 | + return uuid().replace(/-/g, '') |
| 10 | +} |
| 11 | + |
| 12 | +interface ConversationContext { |
| 13 | + conversationId: string |
| 14 | + lastMessageId?: string |
| 15 | +} |
| 16 | + |
| 17 | +export class QianwenWebBot extends AbstractBot { |
| 18 | + private conversationContext?: ConversationContext |
| 19 | + |
| 20 | + async doSendMessage(params: SendMessageParams) { |
| 21 | + if (!(await requestHostPermission('https://qianwen.aliyun.com/'))) { |
| 22 | + throw new ChatError('Missing qianwen.aliyun.com permission', ErrorCode.MISSING_HOST_PERMISSION) |
| 23 | + } |
| 24 | + |
| 25 | + if (!this.conversationContext) { |
| 26 | + const conversationId = await createConversation(params.prompt) |
| 27 | + this.conversationContext = { conversationId } |
| 28 | + } |
| 29 | + |
| 30 | + const resp = await fetch('https://qianwen.aliyun.com/conversation', { |
| 31 | + method: 'POST', |
| 32 | + signal: params.signal, |
| 33 | + headers: { |
| 34 | + 'Content-Type': 'application/json', |
| 35 | + 'X-Xsrf-Token': '7a3dae93-1d29-4eb6-9940-34efad5a2b78', |
| 36 | + }, |
| 37 | + body: JSON.stringify({ |
| 38 | + action: 'next', |
| 39 | + msgId: generateMessageId(), |
| 40 | + parentMsgId: this.conversationContext.lastMessageId || '0', |
| 41 | + contents: [{ contentType: 'text', content: params.prompt }], |
| 42 | + timeout: 17, |
| 43 | + sessionId: this.conversationContext.conversationId, |
| 44 | + model: '', |
| 45 | + userAction: 'chat', |
| 46 | + openSearch: true, |
| 47 | + }), |
| 48 | + }) |
| 49 | + |
| 50 | + await parseSSEResponse(resp, (message) => { |
| 51 | + console.debug('qianwen sse', message) |
| 52 | + const data = JSON.parse(message) |
| 53 | + const text = data.content[0] |
| 54 | + if (text) { |
| 55 | + params.onEvent({ type: 'UPDATE_ANSWER', data: { text } }) |
| 56 | + } |
| 57 | + if (data.stopReason === 'stop') { |
| 58 | + this.conversationContext!.lastMessageId = data.msgId |
| 59 | + params.onEvent({ type: 'DONE' }) |
| 60 | + } |
| 61 | + }) |
| 62 | + } |
| 63 | + |
| 64 | + resetConversation() { |
| 65 | + this.conversationContext = undefined |
| 66 | + } |
| 67 | + |
| 68 | + get name() { |
| 69 | + return 'Tongyi Qianwen' |
| 70 | + } |
| 71 | +} |
0 commit comments