promptsApi.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { apiUrl, getAgentHeaders } from "@/lib/config";
  2. export interface PromptItem {
  3. key: string;
  4. name: string;
  5. content: string;
  6. updated_at?: string;
  7. }
  8. export interface PromptsResponse {
  9. prompts: PromptItem[];
  10. }
  11. /** 获取所有提示词配置(用于「提示词」页) */
  12. export async function fetchPrompts(userId: number): Promise<PromptItem[]> {
  13. const res = await fetch(`${apiUrl("/agent/prompts")}?user_id=${userId}`, {
  14. cache: "no-store",
  15. headers: getAgentHeaders(),
  16. });
  17. if (!res.ok) {
  18. throw new Error("获取提示词配置失败");
  19. }
  20. const contentType = res.headers.get("content-type") ?? "";
  21. if (!contentType.includes("application/json")) {
  22. throw new Error(
  23. "提示词接口返回非 JSON,请确认:1) 后端已启动;2) 前端代理端口与后端一致(默认 8080,若后端在 18080 请在 frontend/.env.local 设置 NEXT_PUBLIC_BACKEND_PORT=18080 并重启前端)"
  24. );
  25. }
  26. const data: PromptsResponse = await res.json();
  27. return data.prompts ?? [];
  28. }
  29. /** 更新单条提示词(仅管理员) */
  30. export async function updatePrompt(
  31. userId: number,
  32. key: string,
  33. content: string
  34. ): Promise<void> {
  35. const res = await fetch(apiUrl("/agent/prompts"), {
  36. method: "PUT",
  37. headers: { "Content-Type": "application/json", ...getAgentHeaders() },
  38. body: JSON.stringify({ user_id: userId, key, content }),
  39. });
  40. if (!res.ok) {
  41. const err = await res.json().catch(() => ({}));
  42. throw new Error((err as { error?: string }).error || "更新提示词失败");
  43. }
  44. }