52 lines
1.9 KiB
TypeScript
52 lines
1.9 KiB
TypeScript
// File: frontend/lib/api.ts (新建或修改)
|
|
// Description: 用于调用后端 API 的工具函数
|
|
|
|
import axios from "axios";
|
|
|
|
// 从环境变量读取后端 API 地址,如果没有则使用默认值
|
|
// 确保在 .env.local 文件中定义 NEXT_PUBLIC_API_URL=http://localhost:8000/api/v1
|
|
const API_BASE_URL =
|
|
process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000/api/v1";
|
|
|
|
// 创建 axios 实例,可以设置一些全局配置
|
|
const apiClient = axios.create({
|
|
baseURL: API_BASE_URL,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
/**
|
|
* 发送聊天消息到后端
|
|
* @param message 用户输入的消息文本
|
|
* @returns AI 的回复文本
|
|
* @throws 如果 API 请求失败则抛出错误
|
|
*/
|
|
export const sendChatMessage = async (message: string): Promise<string> => {
|
|
try {
|
|
// 发送 POST 请求到后端的 /chat/ 端点
|
|
const response = await apiClient.post("/chat/", { message });
|
|
// 检查响应数据和 reply 字段是否存在
|
|
if (response.data && response.data.reply) {
|
|
return response.data.reply; // 返回 AI 的回复
|
|
} else {
|
|
// 如果响应格式不符合预期,抛出错误
|
|
throw new Error("Invalid response format from server");
|
|
}
|
|
} catch (error) {
|
|
console.error("Error calling chat API:", error); // 在控制台打印详细错误
|
|
// 检查是否是 Axios 错误并且有响应体
|
|
if (axios.isAxiosError(error) && error.response) {
|
|
// 尝试从响应体中获取错误详情,否则提供通用消息
|
|
throw new Error(
|
|
error.response.data?.detail || "Failed to communicate with server"
|
|
);
|
|
}
|
|
// 如果不是 Axios 错误或没有响应体,抛出通用错误
|
|
throw new Error("Failed to send message. Please try again.");
|
|
}
|
|
};
|
|
|
|
// --- 你可以在这里添加调用其他后端 API 的函数 ---
|
|
// export const getWorkflows = async () => { ... };
|