aiChatService.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /**
  2. * AI Chat Service
  3. *
  4. * Integrates with external AI platform API for chat completions.
  5. * Supports both streaming and non-streaming responses.
  6. *
  7. * API Documentation:
  8. * Configuration is read from the frontend environment.
  9. * - Supports text, file_url, and image_url content types
  10. *
  11. * @module services/aiChatService
  12. */
  13. import { fetchWithTimeout } from '../utils/fetchWithTimeout';
  14. /**
  15. * Message content types
  16. */
  17. export type MessageContentType = 'text' | 'file_url' | 'image_url';
  18. /**
  19. * Message content item (for multi-modal messages)
  20. */
  21. export interface MessageContent {
  22. type: MessageContentType;
  23. text?: string;
  24. name?: string;
  25. url?: string;
  26. }
  27. /**
  28. * Chat message
  29. */
  30. export interface ChatMessage {
  31. role: 'user' | 'assistant' | 'system';
  32. content: string | MessageContent[];
  33. }
  34. /**
  35. * Chat completion request
  36. */
  37. export interface ChatCompletionRequest {
  38. /** Custom chat/conversation ID (e.g., user ID) */
  39. chatId: string;
  40. /** Whether to return streaming response */
  41. stream?: boolean;
  42. /** Whether to return intermediate process details */
  43. detail?: boolean;
  44. /** Chat messages */
  45. messages: ChatMessage[];
  46. }
  47. /**
  48. * Chat completion response (non-streaming)
  49. */
  50. export interface ChatCompletionResponse {
  51. /** Response message content */
  52. content: string;
  53. /** Knowledge base references (if any) */
  54. references?: {
  55. title: string;
  56. url: string;
  57. snippet: string;
  58. }[];
  59. /** Process details (if detail=true) */
  60. details?: unknown;
  61. }
  62. /**
  63. * Configuration for AI Chat API
  64. */
  65. interface AIChatConfig {
  66. apiUrl: string;
  67. }
  68. /**
  69. * Get AI Chat configuration from environment variables
  70. */
  71. const getAIChatConfig = (): AIChatConfig => {
  72. return {
  73. apiUrl: import.meta.env.VITE_AI_PROXY_URL || '/api/v1/ai/chat',
  74. };
  75. };
  76. /**
  77. * Send a chat completion request to AI platform
  78. *
  79. * @param request - Chat completion request
  80. * @returns Promise resolving to AI response
  81. * @throws {Error} When API call fails
  82. */
  83. export const sendChatCompletion = async (
  84. request: ChatCompletionRequest
  85. ): Promise<ChatCompletionResponse> => {
  86. try {
  87. const config = getAIChatConfig();
  88. const response = await fetchWithTimeout(config.apiUrl, {
  89. method: 'POST',
  90. headers: {
  91. 'Content-Type': 'application/json',
  92. },
  93. body: JSON.stringify({
  94. chatId: request.chatId,
  95. stream: request.stream ?? false,
  96. detail: request.detail ?? false,
  97. messages: request.messages,
  98. }),
  99. });
  100. if (!response.ok) {
  101. const errorText = await response.text();
  102. throw new Error(`AI API error (${response.status}): ${errorText}`);
  103. }
  104. const data = await response.json();
  105. // Extract content from response
  106. // The actual response format may vary, adjust based on API documentation
  107. const content = data.choices?.[0]?.message?.content || data.content || data.response || '';
  108. return {
  109. content,
  110. references: data.references,
  111. details: data.details,
  112. };
  113. } catch (error) {
  114. throw new Error('AI对话失败: ' + (error instanceof Error ? error.message : '未知错误'), {
  115. cause: error,
  116. });
  117. }
  118. };
  119. /**
  120. * Send a streaming chat completion request
  121. *
  122. * @param request - Chat completion request
  123. * @param onChunk - Callback for each chunk of streamed content
  124. * @returns Promise resolving when stream completes
  125. * @throws {Error} When API call fails
  126. */
  127. export const sendStreamingChatCompletion = async (
  128. request: ChatCompletionRequest,
  129. onChunk: (chunk: string) => void
  130. ): Promise<void> => {
  131. try {
  132. const config = getAIChatConfig();
  133. if (!config.apiUrl) {
  134. if (import.meta.env.PROD) {
  135. throw new Error('AI 服务未配置,请先配置服务端代理');
  136. }
  137. const mockResponse = await mockChatCompletion(request);
  138. for (const chunk of mockResponse.content.split(' ')) {
  139. await new Promise((resolve) => setTimeout(resolve, 50));
  140. onChunk(chunk + ' ');
  141. }
  142. return;
  143. }
  144. const response = await fetchWithTimeout(config.apiUrl, {
  145. method: 'POST',
  146. headers: {
  147. 'Content-Type': 'application/json',
  148. },
  149. body: JSON.stringify({
  150. ...request,
  151. stream: true,
  152. }),
  153. });
  154. if (!response.ok) {
  155. const errorText = await response.text();
  156. throw new Error(`AI API error (${response.status}): ${errorText}`);
  157. }
  158. // Process streaming response
  159. const reader = response.body?.getReader();
  160. if (!reader) {
  161. throw new Error('Response body is not readable');
  162. }
  163. const decoder = new TextDecoder();
  164. let buffer = '';
  165. while (true) {
  166. const { done, value } = await reader.read();
  167. if (done) break;
  168. buffer += decoder.decode(value, { stream: true });
  169. const lines = buffer.split('\n');
  170. buffer = lines.pop() || '';
  171. for (const line of lines) {
  172. if (line.trim() === '' || line.startsWith(':')) continue;
  173. if (line.startsWith('data: ')) {
  174. const data = line.slice(6);
  175. if (data === '[DONE]') continue;
  176. try {
  177. const json = JSON.parse(data);
  178. const content = json.choices?.[0]?.delta?.content || '';
  179. if (content) {
  180. onChunk(content);
  181. }
  182. } catch {
  183. // Failed to parse SSE data, skip this line
  184. }
  185. }
  186. }
  187. }
  188. } catch (error) {
  189. throw new Error('AI流式对话失败: ' + (error instanceof Error ? error.message : '未知错误'), {
  190. cause: error,
  191. });
  192. }
  193. };
  194. /**
  195. * Mock chat completion for testing/fallback
  196. * Used when API key is not configured or API is unavailable
  197. *
  198. * @param request - Chat completion request
  199. * @returns Mock AI response
  200. */
  201. const mockChatCompletion = async (
  202. request: ChatCompletionRequest
  203. ): Promise<ChatCompletionResponse> => {
  204. // Simulate network delay
  205. await new Promise((resolve) => setTimeout(resolve, 800));
  206. // Get the last user message
  207. const lastMessage = request.messages[request.messages.length - 1];
  208. const userContent =
  209. typeof lastMessage.content === 'string'
  210. ? lastMessage.content
  211. : lastMessage.content.find((c) => c.type === 'text')?.text || '';
  212. const lowerContent = userContent.toLowerCase();
  213. // Mock different responses based on content
  214. if (
  215. lowerContent.includes('生成') &&
  216. (lowerContent.includes('报告') || lowerContent.includes('文档'))
  217. ) {
  218. let reportType = '报告';
  219. if (lowerContent.includes('地质')) {
  220. reportType = '地质报告';
  221. } else if (lowerContent.includes('技术')) {
  222. reportType = '技术报告';
  223. } else if (lowerContent.includes('分析')) {
  224. reportType = '分析报告';
  225. }
  226. return {
  227. content: `好的,我已经为您准备了一份${reportType}。正在生成文档...`,
  228. };
  229. }
  230. if (lowerContent.includes('你好') || lowerContent.includes('hello')) {
  231. return {
  232. content: '您好!我是AI助手,很高兴为您服务。您可以让我帮您生成各种报告和文档。',
  233. };
  234. }
  235. // Default response
  236. return {
  237. content: `我理解您说的是:"${userContent}"。这是一个模拟响应(后端 AI 服务未配置)。`,
  238. };
  239. };
  240. /**
  241. * Helper: Create a simple text message
  242. */
  243. export const createTextMessage = (role: 'user' | 'assistant', text: string): ChatMessage => ({
  244. role,
  245. content: text,
  246. });
  247. /**
  248. * Helper: Create a multi-modal message with text and files
  249. */
  250. export const createMultiModalMessage = (role: 'user', contents: MessageContent[]): ChatMessage => ({
  251. role,
  252. content: contents,
  253. });
  254. /**
  255. * Export the AI chat service
  256. */
  257. export const aiChatService = {
  258. sendChatCompletion,
  259. sendStreamingChatCompletion,
  260. createTextMessage,
  261. createMultiModalMessage,
  262. };
  263. export default aiChatService;