promptsApi.ts 1.5 KB

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