Class: PromptObjects::Repositories::MessageRepository

Inherits:
BaseRepository
  • Object
show all
Defined in:
lib/prompt_objects/repositories/message_repository.rb

Instance Method Summary collapse

Methods inherited from BaseRepository

#initialize

Constructor Details

This class inherits a constructor from PromptObjects::Repositories::BaseRepository

Instance Method Details

#append(thread_id:, role:, content: nil, run_id: nil, turn_ordinal: nil, position: nil, from_po: nil, tool_calls: nil, tool_results: nil, usage: nil, message_uid: SecureRandom.uuid) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/prompt_objects/repositories/message_repository.rb', line 6

def append(thread_id:, role:, content: nil, run_id: nil, turn_ordinal: nil,
           position: nil, from_po: nil, tool_calls: nil, tool_results: nil,
           usage: nil, message_uid: SecureRandom.uuid)
  now = Time.now.utc.iso8601
  transaction do |db|
    position ||= next_position(db, thread_id, turn_ordinal)
    params = [
      thread_id, role.to_s, content, from_po, tool_calls && JSON.generate(tool_calls),
      tool_results && JSON.generate(tool_results), usage && JSON.generate(usage), now,
      message_uid, run_id, turn_ordinal, position
    ]
    db.execute(<<~SQL, params)
      INSERT INTO messages (
        session_id, role, content, from_po, tool_calls, tool_results, usage,
        created_at, message_uid, run_id, turn_ordinal, position
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    SQL
    db.execute("UPDATE sessions SET updated_at = ?, last_activity_at = ? WHERE id = ?", [now, now, thread_id])
    parse(db.get_first_row("SELECT * FROM messages WHERE id = last_insert_rowid()"))
  end
end

#list(thread_id:, through_turn: nil, after_id: 0, limit: 100) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/prompt_objects/repositories/message_repository.rb', line 28

def list(thread_id:, through_turn: nil, after_id: 0, limit: 100)
  rows = read do |db|
    if through_turn
      db.execute(<<~SQL, [thread_id, through_turn, after_id, limit])
        SELECT * FROM messages
        WHERE session_id = ? AND (turn_ordinal IS NULL OR turn_ordinal <= ?) AND id > ?
        ORDER BY COALESCE(turn_ordinal, 0), COALESCE(position, id), id
        LIMIT ?
      SQL
    else
      db.execute(<<~SQL, [thread_id, after_id, limit])
        SELECT * FROM messages
        WHERE session_id = ? AND id > ?
        ORDER BY COALESCE(turn_ordinal, 0), COALESCE(position, id), id
        LIMIT ?
      SQL
    end
  end
  rows.map { |row| parse(row) }
end