api.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { ACCESS_CODE_PREFIX } from "../constant";
  2. import { ModelConfig, ModelType, useAccessStore } from "../store";
  3. import { ChatGPTApi } from "./platforms/openai";
  4. export const ROLES = ["system", "user", "assistant"] as const;
  5. export type MessageRole = (typeof ROLES)[number];
  6. export const Models = ["gpt-3.5-turbo", "gpt-4"] as const;
  7. export type ChatModel = ModelType;
  8. export interface RequestMessage {
  9. role: MessageRole;
  10. content: string;
  11. }
  12. export interface LLMConfig {
  13. model: string;
  14. temperature?: number;
  15. top_p?: number;
  16. stream?: boolean;
  17. presence_penalty?: number;
  18. frequency_penalty?: number;
  19. }
  20. export interface ChatOptions {
  21. messages: RequestMessage[];
  22. config: LLMConfig;
  23. onUpdate?: (message: string, chunk: string) => void;
  24. onFinish: (message: string) => void;
  25. onError?: (err: Error) => void;
  26. onController?: (controller: AbortController) => void;
  27. }
  28. export interface LLMUsage {
  29. used: number;
  30. total: number;
  31. }
  32. export abstract class LLMApi {
  33. abstract chat(options: ChatOptions): Promise<void>;
  34. abstract usage(): Promise<LLMUsage>;
  35. }
  36. export class ClientApi {
  37. public llm: LLMApi;
  38. constructor() {
  39. this.llm = new ChatGPTApi();
  40. }
  41. config() {}
  42. prompts() {}
  43. masks() {}
  44. }
  45. export const api = new ClientApi();
  46. export function getHeaders() {
  47. const accessStore = useAccessStore.getState();
  48. let headers: Record<string, string> = {
  49. "Content-Type": "application/json",
  50. };
  51. const makeBearer = (token: string) => `Bearer ${token.trim()}`;
  52. const validString = (x: string) => x && x.length > 0;
  53. // use user's api key first
  54. if (validString(accessStore.token)) {
  55. headers.Authorization = makeBearer(accessStore.token);
  56. } else if (
  57. accessStore.enabledAccessControl() &&
  58. validString(accessStore.accessCode)
  59. ) {
  60. headers.Authorization = makeBearer(
  61. ACCESS_CODE_PREFIX + accessStore.accessCode,
  62. );
  63. }
  64. return headers;
  65. }