| 31 | * (e.g. `fetchLLM`). |
| 32 | */ |
| 33 | export function restStorage({ |
| 34 | baseUrl, |
| 35 | messageFormat = identityMessageFormat, |
| 36 | headers, |
| 37 | fetch: customFetch, |
| 38 | }: RestStorageOptions): ChatStorage { |
| 39 | const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis); |
| 40 | |
| 41 | const request = async (url: string, init?: RequestInit): Promise<Response> => { |
| 42 | const res = await fetchImpl(url, { |
| 43 | ...init, |
| 44 | headers: { |
| 45 | ...(init?.body ? { "Content-Type": "application/json" } : {}), |
| 46 | ...headers, |
| 47 | ...init?.headers, |
| 48 | }, |
| 49 | }); |
| 50 | if (!res.ok) { |
| 51 | throw new Error( |
| 52 | `restStorage: ${init?.method ?? "GET"} ${url} failed: ${res.status} ${res.statusText}`, |
| 53 | ); |
| 54 | } |
| 55 | return res; |
| 56 | }; |
| 57 | |
| 58 | return { |
| 59 | thread: { |
| 60 | async listThreads(cursor?: string) { |
| 61 | const url = cursor ? `${baseUrl}/get?cursor=${cursor}` : `${baseUrl}/get`; |
| 62 | const res = await request(url); |
| 63 | return res.json(); |
| 64 | }, |
| 65 | async createThread(firstMessage: UserMessage): Promise<Thread> { |
| 66 | const res = await request(`${baseUrl}/create`, { |
| 67 | method: "POST", |
| 68 | body: JSON.stringify({ messages: messageFormat.toApi([firstMessage]) }), |
| 69 | }); |
| 70 | return res.json(); |
| 71 | }, |
| 72 | async getMessages(threadId: string): Promise<Message[]> { |
| 73 | const res = await request(`${baseUrl}/get/${threadId}`); |
| 74 | const raw: unknown = await res.json(); |
| 75 | return messageFormat.fromApi(raw); |
| 76 | }, |
| 77 | async updateThread(thread: Thread): Promise<Thread> { |
| 78 | const res = await request(`${baseUrl}/update/${thread.id}`, { |
| 79 | method: "PATCH", |
| 80 | body: JSON.stringify(thread), |
| 81 | }); |
| 82 | return res.json(); |
| 83 | }, |
| 84 | async deleteThread(id: string): Promise<void> { |
| 85 | await request(`${baseUrl}/delete/${id}`, { method: "DELETE" }); |
| 86 | }, |
| 87 | }, |
| 88 | }; |
| 89 | } |