promptsApi.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. const err = await res.json().catch(() => ({}));
  19. throw new Error((err as { error?: string }).error || "获取提示词配置失败");
  20. }
  21. const contentType = res.headers.get("content-type") ?? "";
  22. if (!contentType.includes("application/json")) {
  23. throw new Error(
  24. "提示词接口返回非 JSON,请确认:1) 后端已启动;2) 前端代理端口与后端一致(默认 8080,若后端在 18080 请在 frontend/.env.local 设置 NEXT_PUBLIC_BACKEND_PORT=18080 并重启前端)"
  25. );
  26. }
  27. const data: PromptsResponse = await res.json();
  28. return data.prompts ?? [];
  29. }
  30. /** 更新单条提示词(仅管理员) */
  31. export async function updatePrompt(
  32. userId: number,
  33. key: string,
  34. content: string
  35. ): Promise<void> {
  36. const res = await fetch(apiUrl("/agent/prompts"), {
  37. method: "PUT",
  38. headers: { "Content-Type": "application/json", ...getAgentHeaders() },
  39. body: JSON.stringify({ user_id: userId, key, content }),
  40. });
  41. if (!res.ok) {
  42. const err = await res.json().catch(() => ({}));
  43. throw new Error((err as { error?: string }).error || "更新提示词失败");
  44. }
  45. }