first commit
This commit is contained in:
85
app/service/initializeCoze.ts
Normal file
85
app/service/initializeCoze.ts
Normal file
@ -0,0 +1,85 @@
|
||||
import cozeService from './cozeService';
|
||||
import type { CozeConfig } from '../types/types';
|
||||
|
||||
/**
|
||||
* 初始化Coze服务
|
||||
* 这个函数应该在客户端组件中调用,因为API密钥需要在客户端安全管理
|
||||
*
|
||||
* @param config Coze配置信息,包含API密钥和Bot ID
|
||||
* @returns 是否初始化成功
|
||||
*/
|
||||
export const initializeCoze = (config: CozeConfig): boolean => {
|
||||
try {
|
||||
// 验证配置
|
||||
if (!config.apiKey || !config.botId) {
|
||||
console.error('Missing Coze API key or Bot ID');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 设置凭证并初始化客户端
|
||||
cozeService.setCredentials(config.apiKey, config.botId);
|
||||
|
||||
console.log('Coze service initialized successfully');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Coze service:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 从环境变量或localStorage加载Coze配置
|
||||
* 在实际应用中,建议使用更安全的方式存储API密钥
|
||||
*/
|
||||
export const loadCozeConfig = (): CozeConfig | null => {
|
||||
try {
|
||||
// 在实际应用中,你可能会从环境变量或安全存储中获取这些值
|
||||
// 这里我们从localStorage中读取作为示例
|
||||
const storedConfig = localStorage.getItem('cozeConfig');
|
||||
if (storedConfig) {
|
||||
return JSON.parse(storedConfig);
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Failed to load Coze configuration:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存Coze配置到localStorage
|
||||
* 在实际应用中,建议使用更安全的方式存储API密钥
|
||||
*/
|
||||
export const saveCozeConfig = (config: CozeConfig): boolean => {
|
||||
try {
|
||||
localStorage.setItem('cozeConfig', JSON.stringify(config));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to save Coze configuration:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取已初始化的Coze服务实例
|
||||
* @returns CozeService实例
|
||||
*/
|
||||
export function getCozeService() {
|
||||
return cozeService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查Coze服务是否已初始化
|
||||
* @returns boolean 是否已初始化
|
||||
*/
|
||||
export function isCozeInitialized(): boolean {
|
||||
return cozeService.isInitialized();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置Coze对话
|
||||
*/
|
||||
export function resetCozeConversation(): void {
|
||||
cozeService.resetConversation();
|
||||
}
|
||||
Reference in New Issue
Block a user