persisting in postgres
This commit is contained in:
26
lib/elixir_ai/data/conversation.ex
Normal file
26
lib/elixir_ai/data/conversation.ex
Normal file
@@ -0,0 +1,26 @@
|
||||
defmodule ElixirAi.Conversation do
|
||||
import Ecto.Query
|
||||
alias ElixirAi.Repo
|
||||
|
||||
def all_names do
|
||||
Repo.all(from c in "conversations", select: c.name)
|
||||
end
|
||||
|
||||
def create(name) do
|
||||
case Repo.insert_all("conversations", [[id: Ecto.UUID.generate(), name: name, inserted_at: now(), updated_at: now()]]) do
|
||||
{1, _} -> :ok
|
||||
_ -> {:error, :db_error}
|
||||
end
|
||||
rescue
|
||||
e in Ecto.ConstraintError -> if e.constraint == "conversations_name_index", do: {:error, :already_exists}, else: {:error, :db_error}
|
||||
end
|
||||
|
||||
def find_id(name) do
|
||||
case Repo.one(from c in "conversations", where: c.name == ^name, select: c.id) do
|
||||
nil -> {:error, :not_found}
|
||||
id -> {:ok, id}
|
||||
end
|
||||
end
|
||||
|
||||
defp now, do: DateTime.truncate(DateTime.utc_now(), :second)
|
||||
end
|
||||
49
lib/elixir_ai/data/message.ex
Normal file
49
lib/elixir_ai/data/message.ex
Normal file
@@ -0,0 +1,49 @@
|
||||
defmodule ElixirAi.Message do
|
||||
import Ecto.Query
|
||||
alias ElixirAi.Repo
|
||||
|
||||
def load_for_conversation(conversation_id) do
|
||||
Repo.all(
|
||||
from m in "messages",
|
||||
where: m.conversation_id == ^conversation_id,
|
||||
order_by: m.position,
|
||||
select: %{
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
reasoning_content: m.reasoning_content,
|
||||
tool_calls: m.tool_calls,
|
||||
tool_call_id: m.tool_call_id
|
||||
}
|
||||
)
|
||||
|> Enum.map(&decode_message/1)
|
||||
end
|
||||
|
||||
def insert(conversation_id, message, position) do
|
||||
Repo.insert_all("messages", [
|
||||
[
|
||||
id: Ecto.UUID.generate(),
|
||||
conversation_id: conversation_id,
|
||||
role: to_string(message.role),
|
||||
content: message[:content],
|
||||
reasoning_content: message[:reasoning_content],
|
||||
tool_calls: encode_tool_calls(message[:tool_calls]),
|
||||
tool_call_id: message[:tool_call_id],
|
||||
position: position,
|
||||
inserted_at: DateTime.truncate(DateTime.utc_now(), :second)
|
||||
]
|
||||
])
|
||||
end
|
||||
|
||||
defp encode_tool_calls(nil), do: nil
|
||||
defp encode_tool_calls(calls), do: Jason.encode!(calls)
|
||||
|
||||
defp decode_message(row) do
|
||||
row
|
||||
|> Map.update!(:role, &String.to_existing_atom/1)
|
||||
|> drop_nil_fields()
|
||||
end
|
||||
|
||||
defp drop_nil_fields(map) do
|
||||
Map.reject(map, fn {_k, v} -> is_nil(v) end)
|
||||
end
|
||||
end
|
||||
5
lib/elixir_ai/data/repo.ex
Normal file
5
lib/elixir_ai/data/repo.ex
Normal file
@@ -0,0 +1,5 @@
|
||||
defmodule ElixirAi.Repo do
|
||||
use Ecto.Repo,
|
||||
otp_app: :elixir_ai,
|
||||
adapter: Ecto.Adapters.Postgres
|
||||
end
|
||||
Reference in New Issue
Block a user