O

ouhammmourachid / ai-chat-history

Public

Store conversations and messages for your LLM app: per-user history, auto titles, token usage, and an endpoint that returns messages ready to send to any LLM API.

  • Other
  • 0 deploys
  • 0 forks

AI Chat History for LLM apps

Store conversations and messages for your LLM app: per-user history, auto titles, token usage, and an endpoint that returns messages ready to send to any LLM API.

What you get

  • Conversations and messages per user, with system prompt and model
  • Conversations are titled from the first user message
  • Token usage per message, summed at GET /api/conversations/{id}/usage
  • GET /api/conversations/{id}/llm returns { system, model, messages: [{ role, content }] }
  • Messages are append-only (no edits), so history stays trustworthy
  • Provider-agnostic: works with Claude, OpenAI, Gemini or local models

Collections

conversations

FieldTypeNotes
titletextAuto-filled from the first message
user (required)relation → usersSet by a hook to the signed-in user
modeltexte.g. the model id you call
system_prompttext
archivedbool
last_message_atdateSet automatically
ActionWho can do it
List / viewuser = @request.auth.id
Createsigned-in users
Updateuser = @request.auth.id
Deleteuser = @request.auth.id

messages

FieldTypeNotes
conversation (required)relation → conversations
role (required)selectsystem, user, assistant, tool
contenttext
modeltextModel that produced it
tokens_innumber
tokens_outnumber
metadatajsonTool calls, finish reason, anything else
ActionWho can do it
List / viewconversation.user = @request.auth.id
Createsigned-in users
Updatesuperusers only
Deleteconversation.user = @request.auth.id

Hooks

All hooks are in pb_hooks/main.pb.js and commented.

Quick start

import PocketBase from "pocketbase"
const pb = new PocketBase("https://YOUR-INSTANCE.pocketshub.com")

const convo = await pb.collection("conversations").create({ model: "your-model-id" })
await pb.collection("messages").create({ conversation: convo.id, role: "user", content: "Hi!" })

// Ready to send to your LLM:
const { system, messages } = await pb.send(`/api/conversations/${convo.id}/llm`, {})

// Save the reply with its usage:
await pb.collection("messages").create({
  conversation: convo.id, role: "assistant", content: reply, tokens_in: 12, tokens_out: 40,
})

Notes

  • Call the LLM from your server (or a PocketBase hook) so your API key never reaches the browser.

License

MIT

conversations
  • id
  • title
  • usersingle
  • model
  • system_prompt
  • archived
  • last_message_at
  • created
  • updated
messages
  • id
  • conversationsingle
  • rolesingle
  • content
  • model
  • tokens_in
  • tokens_out
  • metadata
  • created
  • updated

2 collections, 1 relation. Hover a collection to trace its relations

main.pb.js107 lines
/// <reference path="../pb_data/types.d.ts" />

// Conversations belong to the signed-in user who starts them.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to start a conversation.")
    e.record.set("user", e.auth.id)
  }
  e.next()
}, "conversations")

onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth() && e.record.original().getString("user") !== e.record.getString("user")) {
    throw new ForbiddenError("A conversation can't be moved to another user.")
  }
  e.next()
}, "conversations")

// Messages can only be added to your own conversations.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to add messages.")
    let conversation
    try {
      conversation = e.app.findRecordById("conversations", e.record.getString("conversation"))
    } catch (_) {
      throw new BadRequestError("Conversation not found.")
    }
    if (conversation.getString("user") !== e.auth.id) {
      throw new ForbiddenError("That conversation isn't yours.")
    }
  }
  e.next()
}, "messages")

// After each message: bump last_message_at, and title the conversation from its first user message.
onRecordAfterCreateSuccess((e) => {
  try {
    const conversation = e.app.findRecordById("conversations", e.record.getString("conversation"))
    conversation.set("last_message_at", new DateTime())
    if (!conversation.getString("title") && e.record.getString("role") === "user") {
      const text = e.record.getString("content").replace(/\s+/g, " ").trim()
      conversation.set("title", text.length > 60 ? text.slice(0, 57) + "..." : text)
    }
    e.app.save(conversation)
  } catch (err) {
    e.app.logger().warn("Could not update conversation", "message", e.record.id, "error", String(err))
  }
  e.next()
}, "messages")

// GET /api/conversations/{id}/llm  -> messages in the { role, content } shape LLM APIs take.
routerAdd(
  "GET",
  "/api/conversations/{id}/llm",
  (e) => {
    let conversation
    try {
      conversation = $app.findRecordById("conversations", e.request.pathValue("id"))
    } catch (_) {
      throw new NotFoundError("Conversation not found.")
    }
    if (conversation.getString("user") !== e.auth.id) throw new NotFoundError("Conversation not found.")

    const messages = $app.findRecordsByFilter(
      "messages",
      "conversation = {:id}",
      "created",
      2000,
      0,
      { id: conversation.id },
    )
    return e.json(200, {
      system: conversation.getString("system_prompt"),
      model: conversation.getString("model"),
      messages: messages.map((m) => ({ role: m.getString("role"), content: m.getString("content") })),
    })
  },
  $apis.requireAuth(),
)

// GET /api/conversations/{id}/usage  -> { messages, tokens_in, tokens_out }
routerAdd(
  "GET",
  "/api/conversations/{id}/usage",
  (e) => {
    let conversation
    try {
      conversation = $app.findRecordById("conversations", e.request.pathValue("id"))
    } catch (_) {
      throw new NotFoundError("Conversation not found.")
    }
    if (conversation.getString("user") !== e.auth.id) throw new NotFoundError("Conversation not found.")

    const result = new DynamicModel({ messages: 0, tokens_in: 0, tokens_out: 0 })
    $app
      .db()
      .newQuery(
        "SELECT COUNT(*) AS messages, COALESCE(SUM(tokens_in), 0) AS tokens_in, COALESCE(SUM(tokens_out), 0) AS tokens_out " +
          "FROM messages WHERE conversation = {:id}",
      )
      .bind({ id: conversation.id })
      .one(result)
    return e.json(200, result)
  },
  $apis.requireAuth(),
)