Files
agent/app/service/initializeCoze.ts
2025-10-16 21:24:18 +08:00

85 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();
}