import $configuration from "../$configuration";
import Axios from "axios";
import $notice from "../$notice";
import {iTableAiOperatePlcMeta} from "../AutoTable/utils/AutoTable.utils";
import $dialog from "../$dialog";
import i18n from "../../i18n";
import AiChatBox, {iChatBoxHistory} from "../AiChatBox";
import {createSimpleDate} from "../createSimpleDate";
import {uuid} from "@peryl/utils/uuid";
import {PlainObject} from "@peryl/utils/event";
import {defer} from "@peryl/utils/defer";
import {toArray} from "@peryl/utils/toArray";
import {iEffects} from "@peryl/utils/createEffects";
export const $ai = (() => {
/**
* 获取模型服务信息
* @author 韦胜健
* @date 2025/5/20 19:26
*/
const getConfig = (): iAiConfiguration => {
const aiConfig = $configuration.get('aiConfig');
if (!aiConfig) {
throw new Error('There is a lack of aiConfig when initializing the $configuration.');
}
return aiConfig;
};
/**
* 带对话历史的模型调用
* @author 韦胜健
* @date 2025/5/20 19:26
*/
const chatHistories = async (histories: iAiHistory[], _aiConfig?: iAiConfiguration): Promise<{ message: string, chatData: iAiChatResponse }> => {
const axios = Axios.create();
const aiConfig = _aiConfig || getConfig();
try {
const resp = await axios.request({
method: 'post',
url: aiConfig.url,
headers: {
'Authorization': `Bearer ${aiConfig.key}`,
"Content-Type": 'application/json'
},
data: {
"model": aiConfig.model,
"messages": histories
}
});
const result = resp.data;
let message = result.choices[0].message.content;
if (message.slice(0, 7) === '```json' && message.slice(-3) === '```') {
message = message.slice(7, -3).trim();
}
return { message, chatData: result };
} catch (e: any) {
$notice.error((e.message || JSON.stringify(e)) + '\n' + e.response?.data?.error?.message);
throw e;
}
};
/**
* 带提示词的模型调用
* @author 韦胜健
* @date 2025/5/20 19:26
*/
const chatSystem = async (userContent: string, systemContent?: string, _aiConfig?: iAiConfiguration) => {
const messages: iAiHistory[] = [{ "role": "user", "content": userContent }];
if (!!systemContent) {
messages.unshift({ "role": "system", "content": systemContent });
}
return chatHistories(messages, _aiConfig);
};
/**
* 基础的模型调用
* @author 韦胜健
* @date 2025/5/20 19:27
*/
const chat = async (userContent: string, _aiConfig?: iAiConfiguration): Promise<{ message: string, chatData: iAiChatResponse }> => {
return chatSystem(userContent, '', _aiConfig);
};
/**
* 流式调用
* @author 韦胜健
* @date 2025/5/20 19:27
*/
const chatStream = async (
{
aiConfig: _aiConfig,
messages,
onReceiving,
onFinish,
onThinking,
onThinkEnd,
onThinkStart,
abortEffects,
}: iAiChatStreamParameter
) => {
const aiConfig = _aiConfig ?? getConfig();
const controller = new AbortController();
!!abortEffects && abortEffects.push(() => {controller.abort('abort stream.');});
// 发送请求
const response = await fetch(aiConfig.url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${aiConfig.key}`,
"Content-Type": 'application/json'
},
body: JSON.stringify({
"model": aiConfig.model,
"messages": messages,
// "messages": [{ role: 'user', content: '你好' }],
stream: true // 请求流式响应
}),
signal: controller.signal,
});
if (!response.ok || !response.body) {throw response;}
// 创建一个解码器来处理UTF-8文本
const decoder = new TextDecoder("utf-8");
let isThinking = false;
let thinkText = '';
let fullText = '';
// 读取响应流
const reader = response.body.getReader();
let done = false;
while (!done) {
const { value, done: readerDone } = await reader.read();
done = readerDone;
if (done) {
console.log('Chat stream done...');
let message = fullText;
if (message.slice(0, 7) === '```json' && message.slice(-3) === '```') {
message = message.slice(7, -3).trim();
}
onReceiving({ fullText: fullText, chunkText: '' });
onFinish?.(message);
}
if (!value?.length) {
continue;
}
const receiveText = (() => {
let text = '';
let chunk = decoder.decode(value, { stream: true });
const pattern = /data: (.*)/g;
let match = pattern.exec(chunk);
while (match) {
if (match[1] === '[DONE]') {
return text;
} else {
const obj = JSON.parse(match[1]);
text += obj.choices[0].delta.content ?? '';
}
match = pattern.exec(chunk);
}
return text;
})();
if (receiveText.slice(0, 8) === '') {
isThinking = true;
// thinkText += receiveText;
onThinkStart?.();
onThinking?.(thinkText);
} else if (receiveText.slice(-8) === '') {
isThinking = false;
// thinkText += receiveText;
onThinkEnd?.();
onThinking?.(thinkText);
} else {
if (isThinking) {
thinkText += receiveText;
onThinking?.(thinkText);
} else {
fullText += receiveText;
onReceiving({ fullText: fullText, chunkText: receiveText });
}
}
}
return response;
};
/**
* 根据ai对话,将用户描述转化为表单数据对象,
* @author 韦胜健
* @date 2025/4/7 22:40
*/
const getFormDataByChat = async (fields: iTableAiOperatePlcMeta[], config?: { title?: string, placeholder?: string }): Promise => {
const dfd = defer();
fields = fields.filter(i =>
i.field != 'id' &&
i.field != 'createdAt' &&
i.field != 'createdBy' &&
i.field != 'updatedAt' &&
i.field != 'updatedBy'
);
const systemContent = `
当前时间是:${createSimpleDate()["YYYY-MM-DD HH:mm:ss"]}
你是一名专业的自然语言分析师,你需要将用户描述转化为一个json对象数据;这个json对象的属性是确定的,json对象的属性名来源于以下的字段的field,这个属性对应的值需要你从用户描述中获取,没有的话就给默认值null;
目前支持的字段:
${JSON.stringify(fields)}
注意的是,如果字段的filterType为date,那么这个字段的值为日期字符串,格式为YYYY-MM-DD
如果这个字段的filterType为datetime,那么这个字段的值为日期时间字符串,格式为YYYY-MM-DD HH:mm:ss,如果用户仅给出了日期没有给出时间,那么给一个默认的时间,当这个字段是开始日期时间时,这个时间的默认值为00:00:00;当这个字段是是结束日期时间时,这个时间的默认值为23:59:59;
如果用户给出的某个字段的值有多个,那么这个字段的值用数字来表示;
如果用户给了多条数据,那么你应该返回这个json对象数组;
最后你给我返回的数据格式为{data,message},如果能解析出来上面说的json对象的话就放在这个结果的data属性中;如果遇到错误,比如用户指定了一个无法识别的字段,则需要将错误原因写在结果的message中;
如果用户提问其他的问题,一律拒绝回答;
`.trim();
const close = $dialog({
title: config?.title || i18n.$it('table.aiButton').d('AI对话'),
position: 'right',
noFoot: true,
width: '500px',
render: () => (
)
});
const handleMessage = async ({ message }: { message: string }): Promise => {
try {
const result: { data: PlainObject | PlainObject[], message?: string } = JSON.parse(message);
if (!!result.message) {
return [{ id: uuid(), role: 'assistant', content: result.message }];
} else {
close();
dfd.resolve(toArray(result.data));
return [];
}
} catch (e: any) {
console.error(e);
return [{ id: uuid(), role: 'assistant', content: JSON.stringify(e.message || e) }];
}
};
return dfd.promise;
};
return {
chat,
chatSystem,
chatHistories,
getConfig,
getFormDataByChat,
chatStream,
};
})();
export interface iAiConfiguration {
/*大模型的调用地址*/
url: string,
/*大模型的调用key*/
key: string,
/*调用的大模型名称*/
model: string,
}
export interface iAiHistory {
role: 'user' | 'assistant' | 'system';
content?: string;
}
export interface iAiChoice {
/**
* 模型停止生成 token 的原因。取值范围:
*
* stop:模型输出自然结束,或因命中请求参数 stop 中指定的字段而被截断。
* length:模型输出因达到模型输出限制而被截断。
* max_token:回答内容的长度限制。
* max_completion_tokens:思维链内容+回答内容的长度限制。
* context window :输入内容+思维链内容+回答内容的长度限制。
* content_filter:模型输出被内容审核拦截。
* tool_calls:模型调用了工具。
*
* @author 韦胜健
* @date 2025/4/5 21:37
*/
finish_reason: string,
/*当前元素在choices列表中的索引*/
index: number,
/**
* 当前内容的对数概率信息。
* 默认不返回输出 tokens 的对数概率,该值为null。
* 如需返回对数概率,请将请求参数 logprobs 设置为 true。
* @author 韦胜健
* @date 2025/4/5 21:38
*/
logprobs: any,
/*模型输出内容*/
message: iAiHistory
}
export interface iAiChatResponse {
/*iAiChoice*/
choices: iAiChoice[],
/*本次请求创建时间的 Unix 时间戳(秒)*/
created: number,
/*请求id*/
id: string,
/*调用的模型名称*/
model: string,
/*固定值chat.completion*/
object: string,
/**
* 本次请求是否使用了TPM保障包。
*
* scale:本次请求使用TPM保障包额度。
* default:本次请求未使用TPM保障包额度。
*
* @author 韦胜健
* @date 2025/4/5 21:41
*/
service_tier: string,
/*本次请求的 token 用量。*/
usage: {
/*模型生成的 token 数量。*/
completion_tokens: number,
/*本次请求花费的 token 的细节。其中reasoning_tokens是指输出思维链内容花费的 token 。*/
completion_tokens_details: {
reasoning_tokens: number,
},
/*输入的 prompt token 数量。*/
prompt_tokens: number,
/*prompt_tokens中命中上下文缓存的tokens数。需要开通上下文缓存功能,并创建缓存才会启用*/
prompt_tokens_details: {
cached_tokens: number,
},
/*本次请求消耗的总 token 数量(输入 + 输出)。*/
total_tokens: number,
}
}
export interface iAiChatStreamParameter {
aiConfig?: iAiConfiguration,
messages: iAiHistory[],
onReceiving: (data: { fullText: string, chunkText: string }) => void,
onFinish?: (fullText: string) => void,
onThinking?: (thinkText: string) => void,
onThinkStart?: () => void,
onThinkEnd?: () => void,
abortEffects?: iEffects,
}