This commit is contained in:
@@ -1,5 +1,8 @@
|
|||||||
import Config
|
import Config
|
||||||
|
|
||||||
|
# Mark this as test environment
|
||||||
|
config :elixir_ai, :env, :test
|
||||||
|
|
||||||
# We don't run a server during test. If one is required,
|
# We don't run a server during test. If one is required,
|
||||||
# you can enable the server option below.
|
# you can enable the server option below.
|
||||||
config :elixir_ai, ElixirAiWeb.Endpoint,
|
config :elixir_ai, ElixirAiWeb.Endpoint,
|
||||||
@@ -16,3 +19,7 @@ config :phoenix, :plug_init_mode, :runtime
|
|||||||
# Enable helpful, but potentially expensive runtime checks
|
# Enable helpful, but potentially expensive runtime checks
|
||||||
config :phoenix_live_view,
|
config :phoenix_live_view,
|
||||||
enable_expensive_runtime_checks: true
|
enable_expensive_runtime_checks: true
|
||||||
|
|
||||||
|
# Configure the database for testing
|
||||||
|
# We use pool_size: 0 to prevent database connections during tests
|
||||||
|
config :elixir_ai, ElixirAi.Repo, pool_size: 0
|
||||||
|
|||||||
@@ -6,8 +6,6 @@ services:
|
|||||||
POSTGRES_PASSWORD: elixir_ai
|
POSTGRES_PASSWORD: elixir_ai
|
||||||
POSTGRES_DB: elixir_ai_dev
|
POSTGRES_DB: elixir_ai_dev
|
||||||
command: postgres -c hba_file=/etc/postgresql/pg_hba.conf
|
command: postgres -c hba_file=/etc/postgresql/pg_hba.conf
|
||||||
ports:
|
|
||||||
- 5432:5432
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
|
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
|
||||||
- ./postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf
|
- ./postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ defmodule ElixirAi.AiUtils.StreamLineUtils do
|
|||||||
%{
|
%{
|
||||||
"choices" => [%{"finish_reason" => "tool_calls"}],
|
"choices" => [%{"finish_reason" => "tool_calls"}],
|
||||||
"id" => id
|
"id" => id
|
||||||
} = message
|
}
|
||||||
) do
|
) do
|
||||||
# Logger.info("Received tool_calls_finished with message: #{inspect(message)}")
|
# Logger.info("Received tool_calls_finished with message: #{inspect(message)}")
|
||||||
send(server, {:ai_tool_call_end, id})
|
send(server, {:ai_tool_call_end, id})
|
||||||
|
|||||||
@@ -6,8 +6,9 @@ defmodule ElixirAi.Application do
|
|||||||
def start(_type, _args) do
|
def start(_type, _args) do
|
||||||
children = [
|
children = [
|
||||||
ElixirAiWeb.Telemetry,
|
ElixirAiWeb.Telemetry,
|
||||||
ElixirAi.Repo,
|
# Conditionally start Repo (skip in test environment)
|
||||||
{Task, fn -> ElixirAi.AiProvider.ensure_default_provider() end},
|
repo_child_spec(),
|
||||||
|
default_provider_task(),
|
||||||
{Cluster.Supervisor,
|
{Cluster.Supervisor,
|
||||||
[Application.get_env(:libcluster, :topologies, []), [name: ElixirAi.ClusterSupervisor]]},
|
[Application.get_env(:libcluster, :topologies, []), [name: ElixirAi.ClusterSupervisor]]},
|
||||||
{Phoenix.PubSub, name: ElixirAi.PubSub},
|
{Phoenix.PubSub, name: ElixirAi.PubSub},
|
||||||
@@ -40,4 +41,21 @@ defmodule ElixirAi.Application do
|
|||||||
ElixirAiWeb.Endpoint.config_change(changed, removed)
|
ElixirAiWeb.Endpoint.config_change(changed, removed)
|
||||||
:ok
|
:ok
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Skip Repo and related tasks in test environment
|
||||||
|
defp repo_child_spec do
|
||||||
|
if Application.get_env(:elixir_ai, :env) == :test do
|
||||||
|
Supervisor.child_spec({Task, fn -> :ok end}, id: :skip_repo)
|
||||||
|
else
|
||||||
|
ElixirAi.Repo
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defp default_provider_task do
|
||||||
|
if Application.get_env(:elixir_ai, :env) == :test do
|
||||||
|
Supervisor.child_spec({Task, fn -> :ok end}, id: :skip_default_provider)
|
||||||
|
else
|
||||||
|
{Task, fn -> ElixirAi.AiProvider.ensure_default_provider() end}
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ defmodule ElixirAi.ChatRunner do
|
|||||||
|
|
||||||
defp via(name), do: {:via, Horde.Registry, {ElixirAi.ChatRegistry, name}}
|
defp via(name), do: {:via, Horde.Registry, {ElixirAi.ChatRegistry, name}}
|
||||||
defp topic(name), do: "ai_chat:#{name}"
|
defp topic(name), do: "ai_chat:#{name}"
|
||||||
defp message_topic(name), do: "conversation_messages:#{name}"
|
def message_topic(name), do: "conversation_messages:#{name}"
|
||||||
|
|
||||||
def new_user_message(name, text_content) do
|
def new_user_message(name, text_content) do
|
||||||
GenServer.cast(via(name), {:user_message, text_content})
|
GenServer.cast(via(name), {:user_message, text_content})
|
||||||
@@ -28,14 +28,17 @@ defmodule ElixirAi.ChatRunner do
|
|||||||
def init(name) do
|
def init(name) do
|
||||||
messages =
|
messages =
|
||||||
case Conversation.find_id(name) do
|
case Conversation.find_id(name) do
|
||||||
{:ok, conv_id} -> Message.load_for_conversation(conv_id)
|
{:ok, conv_id} -> Message.load_for_conversation(conv_id, topic: message_topic(name))
|
||||||
_ -> []
|
_ -> []
|
||||||
end
|
end
|
||||||
|
|
||||||
last_message = List.last(messages)
|
last_message = List.last(messages)
|
||||||
|
|
||||||
if last_message && last_message.role == :user do
|
if last_message && last_message.role == :user do
|
||||||
Logger.info("Last message role was #{last_message.role}, requesting AI response for conversation #{name}")
|
Logger.info(
|
||||||
|
"Last message role was #{last_message.role}, requesting AI response for conversation #{name}"
|
||||||
|
)
|
||||||
|
|
||||||
request_ai_response(self(), messages, tools(self(), name))
|
request_ai_response(self(), messages, tools(self(), name))
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -48,7 +51,7 @@ defmodule ElixirAi.ChatRunner do
|
|||||||
tools: tools(self(), name),
|
tools: tools(self(), name),
|
||||||
ai_provider_url: Application.get_env(:elixir_ai, :ai_provider_url),
|
ai_provider_url: Application.get_env(:elixir_ai, :ai_provider_url),
|
||||||
ai_model: Application.get_env(:elixir_ai, :ai_model),
|
ai_model: Application.get_env(:elixir_ai, :ai_model),
|
||||||
ai_token: Application.get_env(:elixir_ai, :ai_token),
|
ai_token: Application.get_env(:elixir_ai, :ai_token)
|
||||||
}}
|
}}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
defmodule ElixirAi.ClusterSingleton do
|
defmodule ElixirAi.ClusterSingleton do
|
||||||
use GenServer
|
use GenServer
|
||||||
|
require Logger
|
||||||
|
|
||||||
@sync_delay_ms 200
|
@sync_delay_ms 200
|
||||||
|
|
||||||
@@ -7,25 +8,46 @@ defmodule ElixirAi.ClusterSingleton do
|
|||||||
|
|
||||||
def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
|
def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
|
||||||
|
|
||||||
@impl true
|
|
||||||
def init(_opts) do
|
def init(_opts) do
|
||||||
Process.send_after(self(), :start_singletons, @sync_delay_ms)
|
Process.send_after(self(), :start_singletons, @sync_delay_ms)
|
||||||
{:ok, :pending}
|
{:ok, :pending}
|
||||||
end
|
end
|
||||||
|
|
||||||
@impl true
|
def handle_info(:start_singletons, _state) do
|
||||||
def handle_info(:start_singletons, state) do
|
|
||||||
for module <- @singletons do
|
for module <- @singletons do
|
||||||
|
if singleton_exists?(module) do
|
||||||
|
Logger.debug(
|
||||||
|
"ClusterSingleton: singleton already exists, skipping start for #{inspect(module)}"
|
||||||
|
)
|
||||||
|
else
|
||||||
case Horde.DynamicSupervisor.start_child(ElixirAi.ChatRunnerSupervisor, module) do
|
case Horde.DynamicSupervisor.start_child(ElixirAi.ChatRunnerSupervisor, module) do
|
||||||
{:ok, _pid} -> :ok
|
{:ok, _pid} ->
|
||||||
{:error, {:already_started, _pid}} -> :ok
|
:ok
|
||||||
{:error, :already_present} -> :ok
|
|
||||||
|
{:error, {:already_started, _pid}} ->
|
||||||
|
:ok
|
||||||
|
|
||||||
|
{:error, :already_present} ->
|
||||||
|
:ok
|
||||||
|
|
||||||
{:error, reason} ->
|
{:error, reason} ->
|
||||||
require Logger
|
Logger.warning(
|
||||||
Logger.warning("ClusterSingleton: failed to start #{inspect(module)}: #{inspect(reason)}")
|
"ClusterSingleton: failed to start #{inspect(module)}: #{inspect(reason)}"
|
||||||
|
)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
{:noreply, :started}
|
{:noreply, :started}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
defp singleton_exists?(module) do
|
||||||
|
case Horde.Registry.lookup(ElixirAi.ChatRegistry, module) do
|
||||||
|
[{pid, _metadata} | _] when is_pid(pid) ->
|
||||||
|
true
|
||||||
|
|
||||||
|
_ ->
|
||||||
|
false
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -19,19 +19,8 @@ defmodule ElixirAi.ConversationManager do
|
|||||||
|
|
||||||
def init(_) do
|
def init(_) do
|
||||||
Logger.info("ConversationManager initializing...")
|
Logger.info("ConversationManager initializing...")
|
||||||
conversation_list = Conversation.all_names()
|
send(self(), :load_conversations)
|
||||||
Logger.info("Loaded #{length(conversation_list)} conversations from DB")
|
{:ok, :loading_conversations}
|
||||||
|
|
||||||
# Log each conversation and check for UTF-8 issues
|
|
||||||
Enum.each(conversation_list, fn conv ->
|
|
||||||
Logger.info(
|
|
||||||
"Conversation: #{inspect(conv, limit: :infinity, printable_limit: :infinity, binaries: :as_binaries)}"
|
|
||||||
)
|
|
||||||
end)
|
|
||||||
|
|
||||||
conversations = Map.new(conversation_list, fn %{name: name} -> {name, []} end)
|
|
||||||
Logger.info("Conversation map keys: #{inspect(Map.keys(conversations))}")
|
|
||||||
{:ok, conversations}
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def create_conversation(name, ai_provider_id) do
|
def create_conversation(name, ai_provider_id) do
|
||||||
@@ -50,6 +39,15 @@ defmodule ElixirAi.ConversationManager do
|
|||||||
GenServer.call(@name, {:get_messages, name})
|
GenServer.call(@name, {:get_messages, name})
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def handle_call(message, from, :loading_conversations) do
|
||||||
|
Logger.warning(
|
||||||
|
"Received call #{inspect(message)} from #{inspect(from)} while loading conversations. Retrying after delay."
|
||||||
|
)
|
||||||
|
|
||||||
|
Process.send_after(self(), {:retry_call, message, from}, 100)
|
||||||
|
{:noreply, :loading_conversations}
|
||||||
|
end
|
||||||
|
|
||||||
def handle_call({:create, name, ai_provider_id}, _from, conversations) do
|
def handle_call({:create, name, ai_provider_id}, _from, conversations) do
|
||||||
if Map.has_key?(conversations, name) do
|
if Map.has_key?(conversations, name) do
|
||||||
{:reply, {:error, :already_exists}, conversations}
|
{:reply, {:error, :already_exists}, conversations}
|
||||||
@@ -94,13 +92,37 @@ defmodule ElixirAi.ConversationManager do
|
|||||||
|
|
||||||
def handle_info({:store_message, name, message}, conversations) do
|
def handle_info({:store_message, name, message}, conversations) do
|
||||||
case Conversation.find_id(name) do
|
case Conversation.find_id(name) do
|
||||||
{:ok, conv_id} -> Message.insert(conv_id, message)
|
{:ok, conv_id} ->
|
||||||
_ -> :ok
|
Message.insert(conv_id, message, topic: ElixirAi.ChatRunner.message_topic(name))
|
||||||
|
|
||||||
|
_ ->
|
||||||
|
:ok
|
||||||
end
|
end
|
||||||
|
|
||||||
{:noreply, Map.update(conversations, name, [message], &(&1 ++ [message]))}
|
{:noreply, Map.update(conversations, name, [message], &(&1 ++ [message]))}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def handle_info(:load_conversations, _conversations) do
|
||||||
|
conversation_list = Conversation.all_names()
|
||||||
|
Logger.info("Loaded #{length(conversation_list)} conversations from DB")
|
||||||
|
|
||||||
|
conversations = Map.new(conversation_list, fn %{name: name} -> {name, []} end)
|
||||||
|
Logger.info("Conversation map keys: #{inspect(Map.keys(conversations))}")
|
||||||
|
# {:ok, conversations}
|
||||||
|
{:noreply, conversations}
|
||||||
|
end
|
||||||
|
|
||||||
|
def handle_info({:retry_call, message, from}, state) do
|
||||||
|
case handle_call(message, from, state) do
|
||||||
|
{:reply, reply, new_state} ->
|
||||||
|
GenServer.reply(from, reply)
|
||||||
|
{:noreply, new_state}
|
||||||
|
|
||||||
|
{:noreply, new_state} ->
|
||||||
|
{:noreply, new_state}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
defp start_and_subscribe(name) do
|
defp start_and_subscribe(name) do
|
||||||
result =
|
result =
|
||||||
case Horde.DynamicSupervisor.start_child(
|
case Horde.DynamicSupervisor.start_child(
|
||||||
@@ -114,7 +136,7 @@ defmodule ElixirAi.ConversationManager do
|
|||||||
|
|
||||||
case result do
|
case result do
|
||||||
{:ok, _pid} ->
|
{:ok, _pid} ->
|
||||||
Phoenix.PubSub.subscribe(ElixirAi.PubSub, "conversation_messages:#{name}")
|
Phoenix.PubSub.subscribe(ElixirAi.PubSub, ElixirAi.ChatRunner.message_topic(name))
|
||||||
result
|
result
|
||||||
|
|
||||||
_ ->
|
_ ->
|
||||||
|
|||||||
@@ -1,26 +1,32 @@
|
|||||||
defmodule ElixirAi.AiProvider do
|
defmodule ElixirAi.AiProvider do
|
||||||
import Ecto.Query
|
use ElixirAi.Data
|
||||||
alias ElixirAi.Repo
|
alias ElixirAi.Repo
|
||||||
alias ElixirAi.Data.AiProviderSchema
|
alias ElixirAi.Data.AiProviderSchema
|
||||||
require Logger
|
|
||||||
|
|
||||||
def all do
|
def all do
|
||||||
|
broadcast_error topic: "ai_providers" do
|
||||||
|
sql = "SELECT id, name, model_name FROM ai_providers"
|
||||||
|
result = Ecto.Adapters.SQL.query!(Repo, sql, [])
|
||||||
|
|
||||||
results =
|
results =
|
||||||
Repo.all(
|
Enum.map(result.rows, fn [id, name, model_name] ->
|
||||||
from(p in AiProviderSchema,
|
attrs = %{id: id, name: name, model_name: model_name} |> convert_id_to_string()
|
||||||
select: %{
|
|
||||||
id: p.id,
|
case Zoi.parse(AiProviderSchema.partial_schema(), attrs) do
|
||||||
name: p.name,
|
{:ok, valid} ->
|
||||||
model_name: p.model_name
|
struct(AiProviderSchema, valid)
|
||||||
}
|
|
||||||
)
|
{:error, errors} ->
|
||||||
)
|
Logger.error("Invalid provider data from DB: #{inspect(errors)}")
|
||||||
|> Enum.map(&convert_id_to_string/1)
|
raise ArgumentError, "Invalid provider data: #{inspect(errors)}"
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
|
||||||
Logger.debug("AiProvider.all() returning: #{inspect(results)}")
|
Logger.debug("AiProvider.all() returning: #{inspect(results)}")
|
||||||
|
|
||||||
results
|
results
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
# Convert binary UUID to string for frontend
|
# Convert binary UUID to string for frontend
|
||||||
defp convert_id_to_string(%{id: id} = provider) when is_binary(id) do
|
defp convert_id_to_string(%{id: id} = provider) when is_binary(id) do
|
||||||
@@ -30,19 +36,18 @@ defmodule ElixirAi.AiProvider do
|
|||||||
defp convert_id_to_string(provider), do: provider
|
defp convert_id_to_string(provider), do: provider
|
||||||
|
|
||||||
def create(attrs) do
|
def create(attrs) do
|
||||||
|
broadcast_error topic: "ai_providers" do
|
||||||
now = DateTime.truncate(DateTime.utc_now(), :second)
|
now = DateTime.truncate(DateTime.utc_now(), :second)
|
||||||
|
|
||||||
case Repo.insert_all("ai_providers", [
|
sql = """
|
||||||
[
|
INSERT INTO ai_providers (name, model_name, api_token, completions_url, inserted_at, updated_at)
|
||||||
name: attrs.name,
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
model_name: attrs.model_name,
|
"""
|
||||||
api_token: attrs.api_token,
|
|
||||||
completions_url: attrs.completions_url,
|
params = [attrs.name, attrs.model_name, attrs.api_token, attrs.completions_url, now, now]
|
||||||
inserted_at: now,
|
|
||||||
updated_at: now
|
Ecto.Adapters.SQL.query!(Repo, sql, params)
|
||||||
]
|
|
||||||
]) do
|
|
||||||
{1, _} ->
|
|
||||||
Phoenix.PubSub.broadcast(
|
Phoenix.PubSub.broadcast(
|
||||||
ElixirAi.PubSub,
|
ElixirAi.PubSub,
|
||||||
"ai_providers",
|
"ai_providers",
|
||||||
@@ -50,38 +55,52 @@ defmodule ElixirAi.AiProvider do
|
|||||||
)
|
)
|
||||||
|
|
||||||
:ok
|
:ok
|
||||||
|
|
||||||
_ ->
|
|
||||||
{:error, :db_error}
|
|
||||||
end
|
end
|
||||||
rescue
|
|
||||||
e in Ecto.ConstraintError ->
|
|
||||||
if e.constraint == "ai_providers_name_key",
|
|
||||||
do: {:error, :already_exists},
|
|
||||||
else: {:error, :db_error}
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def find_by_name(name) do
|
def find_by_name(name) do
|
||||||
case Repo.one(
|
broadcast_error topic: "ai_providers" do
|
||||||
from(p in "ai_providers",
|
sql = """
|
||||||
where: p.name == ^name,
|
SELECT id, name, model_name, api_token, completions_url
|
||||||
select: %{
|
FROM ai_providers
|
||||||
id: p.id,
|
WHERE name = $1
|
||||||
name: p.name,
|
LIMIT 1
|
||||||
model_name: p.model_name,
|
"""
|
||||||
api_token: p.api_token,
|
|
||||||
completions_url: p.completions_url
|
case Ecto.Adapters.SQL.query!(Repo, sql, [name]) do
|
||||||
|
%{rows: []} ->
|
||||||
|
{:error, :not_found}
|
||||||
|
|
||||||
|
%{rows: [[id, name, model_name, api_token, completions_url] | _]} ->
|
||||||
|
attrs =
|
||||||
|
%{
|
||||||
|
id: id,
|
||||||
|
name: name,
|
||||||
|
model_name: model_name,
|
||||||
|
api_token: api_token,
|
||||||
|
completions_url: completions_url
|
||||||
}
|
}
|
||||||
)
|
|> convert_id_to_string()
|
||||||
) do
|
|
||||||
nil -> {:error, :not_found}
|
case Zoi.parse(AiProviderSchema.schema(), attrs) do
|
||||||
provider -> {:ok, convert_id_to_string(provider)}
|
{:ok, valid} ->
|
||||||
|
{:ok, struct(AiProviderSchema, valid)}
|
||||||
|
|
||||||
|
{:error, errors} ->
|
||||||
|
Logger.error("Invalid provider data from DB: #{inspect(errors)}")
|
||||||
|
{:error, :invalid_data}
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def ensure_default_provider do
|
def ensure_default_provider do
|
||||||
case Repo.aggregate(from(p in "ai_providers"), :count) do
|
broadcast_error topic: "ai_providers" do
|
||||||
0 ->
|
sql = "SELECT COUNT(*) FROM ai_providers"
|
||||||
|
result = Ecto.Adapters.SQL.query!(Repo, sql, [])
|
||||||
|
|
||||||
|
case result.rows do
|
||||||
|
[[0]] ->
|
||||||
attrs = %{
|
attrs = %{
|
||||||
name: "default",
|
name: "default",
|
||||||
model_name: Application.fetch_env!(:elixir_ai, :ai_model),
|
model_name: Application.fetch_env!(:elixir_ai, :ai_model),
|
||||||
@@ -96,3 +115,4 @@ defmodule ElixirAi.AiProvider do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|||||||
@@ -1,103 +1,99 @@
|
|||||||
defmodule ElixirAi.Conversation do
|
defmodule ElixirAi.Conversation do
|
||||||
import Ecto.Query
|
use ElixirAi.Data
|
||||||
alias ElixirAi.Repo
|
alias ElixirAi.Repo
|
||||||
alias ElixirAi.Data.ConversationSchema
|
|
||||||
alias ElixirAi.Data.AiProviderSchema
|
|
||||||
require Logger
|
|
||||||
|
|
||||||
defmodule Provider do
|
defmodule Provider do
|
||||||
use Ecto.Schema
|
defstruct [:name, :model_name, :api_token, :completions_url]
|
||||||
import Ecto.Changeset
|
|
||||||
|
|
||||||
@primary_key false
|
def schema do
|
||||||
embedded_schema do
|
Zoi.object(%{
|
||||||
field(:name, :string)
|
name: Zoi.string(),
|
||||||
field(:model_name, :string)
|
model_name: Zoi.string(),
|
||||||
field(:api_token, :string)
|
api_token: Zoi.string(),
|
||||||
field(:completions_url, :string)
|
completions_url: Zoi.string()
|
||||||
end
|
})
|
||||||
|
|
||||||
def changeset(provider, attrs) do
|
|
||||||
provider
|
|
||||||
|> cast(attrs, [:name, :model_name, :api_token, :completions_url])
|
|
||||||
|> validate_required([:name, :model_name, :api_token, :completions_url])
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defmodule ConversationInfo do
|
defmodule ConversationInfo do
|
||||||
use Ecto.Schema
|
defstruct [:name, :provider]
|
||||||
import Ecto.Changeset
|
|
||||||
|
|
||||||
@primary_key false
|
def schema do
|
||||||
embedded_schema do
|
Zoi.object(%{
|
||||||
field(:name, :string)
|
name: Zoi.string(),
|
||||||
embeds_one(:provider, Provider)
|
provider:
|
||||||
end
|
Zoi.object(%{
|
||||||
|
name: Zoi.string(),
|
||||||
def changeset(conversation, attrs) do
|
model_name: Zoi.string(),
|
||||||
conversation
|
api_token: Zoi.string(),
|
||||||
|> cast(attrs, [:name])
|
completions_url: Zoi.string()
|
||||||
|> validate_required([:name])
|
})
|
||||||
|> cast_embed(:provider, with: &Provider.changeset/2, required: true)
|
})
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def all_names do
|
def all_names do
|
||||||
results =
|
broadcast_error topic: "conversations" do
|
||||||
Repo.all(
|
sql = """
|
||||||
from(c in ConversationSchema,
|
SELECT c.name, p.name, p.model_name, p.api_token, p.completions_url
|
||||||
left_join: p in AiProviderSchema,
|
FROM conversations c
|
||||||
on: c.ai_provider_id == p.id,
|
LEFT JOIN ai_providers p ON c.ai_provider_id = p.id
|
||||||
select: %{
|
"""
|
||||||
name: c.name,
|
|
||||||
|
result = Ecto.Adapters.SQL.query!(Repo, sql, [])
|
||||||
|
|
||||||
|
Enum.map(result.rows, fn [name, provider_name, model_name, api_token, completions_url] ->
|
||||||
|
attrs = %{
|
||||||
|
name: name,
|
||||||
provider: %{
|
provider: %{
|
||||||
name: p.name,
|
name: provider_name,
|
||||||
model_name: p.model_name,
|
model_name: model_name,
|
||||||
api_token: p.api_token,
|
api_token: api_token,
|
||||||
completions_url: p.completions_url
|
completions_url: completions_url
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
Enum.map(results, fn attrs ->
|
case Zoi.parse(ConversationInfo.schema(), attrs) do
|
||||||
changeset = ConversationInfo.changeset(%ConversationInfo{}, attrs)
|
{:ok, valid} ->
|
||||||
|
struct(ConversationInfo, Map.put(valid, :provider, struct(Provider, valid.provider)))
|
||||||
|
|
||||||
if changeset.valid? do
|
{:error, errors} ->
|
||||||
Ecto.Changeset.apply_changes(changeset)
|
Logger.error("Invalid conversation data: #{inspect(errors)}")
|
||||||
else
|
raise ArgumentError, "Invalid conversation data: #{inspect(errors)}"
|
||||||
Logger.error("Invalid conversation data: #{inspect(changeset.errors)}")
|
|
||||||
raise ArgumentError, "Invalid conversation data: #{inspect(changeset.errors)}"
|
|
||||||
end
|
end
|
||||||
end)
|
end)
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def create(name, ai_provider_id) when is_binary(ai_provider_id) do
|
def create(name, ai_provider_id) when is_binary(ai_provider_id) do
|
||||||
# Convert string UUID from frontend to binary UUID for database
|
broadcast_error topic: "conversations" do
|
||||||
case Ecto.UUID.dump(ai_provider_id) do
|
case Ecto.UUID.dump(ai_provider_id) do
|
||||||
{:ok, binary_id} ->
|
{:ok, binary_id} ->
|
||||||
Repo.insert_all("conversations", [
|
sql = """
|
||||||
[name: name, ai_provider_id: binary_id, inserted_at: now(), updated_at: now()]
|
INSERT INTO conversations (name, ai_provider_id, inserted_at, updated_at)
|
||||||
])
|
VALUES ($1, $2, $3, $4)
|
||||||
|> case do
|
"""
|
||||||
{1, _} -> :ok
|
|
||||||
_ -> {:error, :db_error}
|
timestamp = now()
|
||||||
end
|
params = [name, binary_id, timestamp, timestamp]
|
||||||
|
|
||||||
|
Ecto.Adapters.SQL.query!(Repo, sql, params)
|
||||||
|
:ok
|
||||||
|
|
||||||
:error ->
|
:error ->
|
||||||
{:error, :invalid_uuid}
|
{:error, :invalid_uuid}
|
||||||
end
|
end
|
||||||
rescue
|
end
|
||||||
e in Ecto.ConstraintError ->
|
|
||||||
if e.constraint == "conversations_name_index",
|
|
||||||
do: {:error, :already_exists},
|
|
||||||
else: {:error, :db_error}
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def find_id(name) do
|
def find_id(name) do
|
||||||
case Repo.one(from(c in ConversationSchema, where: c.name == ^name, select: c.id)) do
|
broadcast_error topic: "conversations" do
|
||||||
nil -> {:error, :not_found}
|
sql = "SELECT id FROM conversations WHERE name = $1 LIMIT 1"
|
||||||
id -> {:ok, id}
|
|
||||||
|
case Ecto.Adapters.SQL.query!(Repo, sql, [name]) do
|
||||||
|
%{rows: []} -> {:error, :not_found}
|
||||||
|
%{rows: [[id] | _]} -> {:ok, id}
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
32
lib/elixir_ai/data/data.ex
Normal file
32
lib/elixir_ai/data/data.ex
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
defmodule ElixirAi.Data do
|
||||||
|
defmacro __using__(_opts) do
|
||||||
|
quote do
|
||||||
|
import ElixirAi.Data
|
||||||
|
require Logger
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
defmacro broadcast_error(opts, do: block) do
|
||||||
|
topic = Keyword.get(opts, :topic)
|
||||||
|
build_with_db(block, topic)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp build_with_db(block, topic) do
|
||||||
|
quote do
|
||||||
|
try do
|
||||||
|
unquote(block)
|
||||||
|
rescue
|
||||||
|
exception ->
|
||||||
|
Logger.error("Database error: #{Exception.message(exception)}")
|
||||||
|
|
||||||
|
Phoenix.PubSub.broadcast(
|
||||||
|
ElixirAi.PubSub,
|
||||||
|
unquote(topic),
|
||||||
|
{:db_error, Exception.message(exception)}
|
||||||
|
)
|
||||||
|
|
||||||
|
{:error, :db_error}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
26
lib/elixir_ai/data/db_helpers.ex
Normal file
26
lib/elixir_ai/data/db_helpers.ex
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
defmodule ElixirAi.Data.DbHelpers do
|
||||||
|
@get_named_param ~r/\$\((\w+)\)/
|
||||||
|
|
||||||
|
def named_params_to_positional_params(query, params) do
|
||||||
|
param_occurrences = Regex.scan(@get_named_param, query)
|
||||||
|
|
||||||
|
{param_to_index, ordered_values} =
|
||||||
|
param_occurrences
|
||||||
|
|> Enum.reduce({%{}, []}, fn [_full_match, param_name], {index_map, values} ->
|
||||||
|
if Map.has_key?(index_map, param_name) do
|
||||||
|
{index_map, values}
|
||||||
|
else
|
||||||
|
next_index = map_size(index_map) + 1
|
||||||
|
param_value = Map.fetch!(params, param_name)
|
||||||
|
{Map.put(index_map, param_name, next_index), values ++ [param_value]}
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
|
||||||
|
positional_sql =
|
||||||
|
Regex.replace(@get_named_param, query, fn _full_match, param_name ->
|
||||||
|
"$#{param_to_index[param_name]}"
|
||||||
|
end)
|
||||||
|
|
||||||
|
{positional_sql, ordered_values}
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,49 +1,94 @@
|
|||||||
defmodule ElixirAi.Message do
|
defmodule ElixirAi.Message do
|
||||||
import Ecto.Query
|
use ElixirAi.Data
|
||||||
alias ElixirAi.Repo
|
alias ElixirAi.Repo
|
||||||
alias ElixirAi.Data.MessageSchema
|
alias ElixirAi.Data.MessageSchema
|
||||||
|
|
||||||
def load_for_conversation(conversation_id) do
|
def load_for_conversation(conversation_id, topic: topic) do
|
||||||
Repo.all(
|
broadcast_error topic: topic do
|
||||||
from m in MessageSchema,
|
with {:ok, db_conversation_id} <- dump_uuid(conversation_id) do
|
||||||
where: m.conversation_id == ^conversation_id,
|
sql = """
|
||||||
order_by: m.id,
|
SELECT role, content, reasoning_content, tool_calls, tool_call_id
|
||||||
select: %{
|
FROM messages
|
||||||
role: m.role,
|
WHERE conversation_id = $1
|
||||||
content: m.content,
|
ORDER BY id
|
||||||
reasoning_content: m.reasoning_content,
|
"""
|
||||||
tool_calls: m.tool_calls,
|
|
||||||
tool_call_id: m.tool_call_id
|
result = Ecto.Adapters.SQL.query!(Repo, sql, [db_conversation_id])
|
||||||
|
|
||||||
|
Enum.map(result.rows, fn row ->
|
||||||
|
raw = %{
|
||||||
|
role: Enum.at(row, 0),
|
||||||
|
content: Enum.at(row, 1),
|
||||||
|
reasoning_content: Enum.at(row, 2),
|
||||||
|
tool_calls: Enum.at(row, 3),
|
||||||
|
tool_call_id: Enum.at(row, 4)
|
||||||
}
|
}
|
||||||
)
|
|
||||||
|> Enum.map(&decode_message/1)
|
case Zoi.parse(MessageSchema.schema(), raw) do
|
||||||
|
{:ok, _valid} ->
|
||||||
|
struct(MessageSchema, decode_message(raw))
|
||||||
|
|
||||||
|
{:error, errors} ->
|
||||||
|
Logger.error("Invalid message data from DB: #{inspect(errors)}")
|
||||||
|
raise ArgumentError, "Invalid message data: #{inspect(errors)}"
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
else
|
||||||
|
:error -> []
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def insert(conversation_id, message) do
|
def insert(conversation_id, message, topic: topic) do
|
||||||
Repo.insert_all("messages", [
|
broadcast_error topic: topic do
|
||||||
[
|
with {:ok, db_conversation_id} <- dump_uuid(conversation_id) do
|
||||||
conversation_id: conversation_id,
|
sql = """
|
||||||
role: to_string(message.role),
|
INSERT INTO messages (
|
||||||
content: message[:content],
|
conversation_id, role, content, reasoning_content,
|
||||||
reasoning_content: message[:reasoning_content],
|
tool_calls, tool_call_id, inserted_at
|
||||||
tool_calls: encode_tool_calls(message[:tool_calls]),
|
) VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||||
tool_call_id: message[:tool_call_id],
|
"""
|
||||||
inserted_at: DateTime.truncate(DateTime.utc_now(), :second)
|
|
||||||
|
params = [
|
||||||
|
db_conversation_id,
|
||||||
|
to_string(message.role),
|
||||||
|
message[:content],
|
||||||
|
message[:reasoning_content],
|
||||||
|
encode_tool_calls(message[:tool_calls]),
|
||||||
|
message[:tool_call_id],
|
||||||
|
DateTime.truncate(DateTime.utc_now(), :second)
|
||||||
]
|
]
|
||||||
])
|
|
||||||
|
Ecto.Adapters.SQL.query!(Repo, sql, params)
|
||||||
|
Logger.debug("Inserted message for conversation_id=#{Ecto.UUID.cast!(conversation_id)}")
|
||||||
|
{:ok, 1}
|
||||||
|
else
|
||||||
|
:error ->
|
||||||
|
Logger.error("Invalid conversation_id for message insert: #{inspect(conversation_id)}")
|
||||||
|
{:error, :invalid_conversation_id}
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defp encode_tool_calls(nil), do: nil
|
defp encode_tool_calls(nil), do: nil
|
||||||
defp encode_tool_calls(calls), do: Jason.encode!(calls)
|
defp encode_tool_calls(calls), do: Jason.encode!(calls)
|
||||||
|
|
||||||
|
defp dump_uuid(id) when is_binary(id) and byte_size(id) == 16, do: {:ok, id}
|
||||||
|
defp dump_uuid(id) when is_binary(id), do: Ecto.UUID.dump(id)
|
||||||
|
defp dump_uuid(_), do: :error
|
||||||
|
|
||||||
defp decode_message(row) do
|
defp decode_message(row) do
|
||||||
row
|
row
|
||||||
|> Map.update!(:role, &String.to_existing_atom/1)
|
|> Map.update!(:role, &String.to_existing_atom/1)
|
||||||
|> Map.update(:tool_calls, nil, fn
|
|> Map.update(:tool_calls, nil, fn
|
||||||
nil -> nil
|
nil ->
|
||||||
|
nil
|
||||||
|
|
||||||
json when is_binary(json) ->
|
json when is_binary(json) ->
|
||||||
json |> Jason.decode!() |> Enum.map(&atomize_keys/1)
|
json |> Jason.decode!() |> Enum.map(&atomize_keys/1)
|
||||||
already_decoded -> Enum.map(already_decoded, &atomize_keys/1)
|
|
||||||
|
already_decoded ->
|
||||||
|
Enum.map(already_decoded, &atomize_keys/1)
|
||||||
end)
|
end)
|
||||||
|> drop_nil_fields()
|
|> drop_nil_fields()
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
defmodule ElixirAi.Data.AiProviderSchema do
|
defmodule ElixirAi.Data.AiProviderSchema do
|
||||||
use Ecto.Schema
|
defstruct [:id, :name, :model_name, :api_token, :completions_url, :inserted_at, :updated_at]
|
||||||
|
|
||||||
@primary_key {:id, :binary_id, autogenerate: true}
|
def schema do
|
||||||
@foreign_key_type :binary_id
|
Zoi.object(%{
|
||||||
|
id: Zoi.string(),
|
||||||
|
name: Zoi.string(),
|
||||||
|
model_name: Zoi.string(),
|
||||||
|
api_token: Zoi.string(),
|
||||||
|
completions_url: Zoi.string()
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
schema "ai_providers" do
|
def partial_schema do
|
||||||
field(:name, :string)
|
Zoi.object(%{
|
||||||
field(:model_name, :string)
|
id: Zoi.string(),
|
||||||
field(:api_token, :string)
|
name: Zoi.string(),
|
||||||
field(:completions_url, :string)
|
model_name: Zoi.string()
|
||||||
|
})
|
||||||
timestamps(type: :utc_datetime)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
defmodule ElixirAi.Data.ConversationSchema do
|
defmodule ElixirAi.Data.ConversationSchema do
|
||||||
use Ecto.Schema
|
defstruct [:id, :name, :ai_provider_id, :inserted_at, :updated_at]
|
||||||
|
|
||||||
@primary_key {:id, :binary_id, autogenerate: true}
|
def schema do
|
||||||
@foreign_key_type :binary_id
|
Zoi.object(%{
|
||||||
|
id: Zoi.string(),
|
||||||
schema "conversations" do
|
name: Zoi.string(),
|
||||||
field(:name, :string)
|
ai_provider_id: Zoi.string()
|
||||||
belongs_to(:ai_provider, ElixirAi.Data.AiProviderSchema, type: :binary_id)
|
})
|
||||||
|
|
||||||
timestamps(type: :utc_datetime)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
defmodule ElixirAi.Data.MessageSchema do
|
defmodule ElixirAi.Data.MessageSchema do
|
||||||
use Ecto.Schema
|
defstruct [
|
||||||
|
:id,
|
||||||
|
:conversation_id,
|
||||||
|
:role,
|
||||||
|
:content,
|
||||||
|
:reasoning_content,
|
||||||
|
:tool_calls,
|
||||||
|
:tool_call_id,
|
||||||
|
:inserted_at
|
||||||
|
]
|
||||||
|
|
||||||
@primary_key {:id, :id, autogenerate: true}
|
def schema do
|
||||||
|
Zoi.object(%{
|
||||||
schema "messages" do
|
role: Zoi.string()
|
||||||
belongs_to(:conversation, ElixirAi.Data.ConversationSchema, type: :binary_id)
|
})
|
||||||
field(:role, :string)
|
|
||||||
field(:content, :string)
|
|
||||||
field(:reasoning_content, :string)
|
|
||||||
field(:tool_calls, :map)
|
|
||||||
field(:tool_call_id, :string)
|
|
||||||
|
|
||||||
timestamps(inserted_at: :inserted_at, updated_at: false, type: :utc_datetime)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -134,8 +134,6 @@ defmodule ElixirAiWeb.AiProvidersLive do
|
|||||||
)
|
)
|
||||||
|> assign(error: nil)}
|
|> assign(error: nil)}
|
||||||
|
|
||||||
{:error, :already_exists} ->
|
|
||||||
{:noreply, assign(socket, error: "A provider with that name already exists")}
|
|
||||||
|
|
||||||
_ ->
|
_ ->
|
||||||
{:noreply, assign(socket, error: "Failed to create provider")}
|
{:noreply, assign(socket, error: "Failed to create provider")}
|
||||||
|
|||||||
@@ -7,24 +7,13 @@ defmodule ElixirAiWeb.HomeLive do
|
|||||||
def mount(_params, _session, socket) do
|
def mount(_params, _session, socket) do
|
||||||
if connected?(socket) do
|
if connected?(socket) do
|
||||||
Phoenix.PubSub.subscribe(ElixirAi.PubSub, "ai_providers")
|
Phoenix.PubSub.subscribe(ElixirAi.PubSub, "ai_providers")
|
||||||
|
send(self(), :load_data)
|
||||||
end
|
end
|
||||||
|
|
||||||
conversations = ConversationManager.list_conversations()
|
|
||||||
|
|
||||||
Logger.debug(
|
|
||||||
"Conversations: #{inspect(conversations, limit: :infinity, printable_limit: :infinity)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
ai_providers = AiProvider.all()
|
|
||||||
|
|
||||||
Logger.debug(
|
|
||||||
"AI Providers: #{inspect(ai_providers, limit: :infinity, printable_limit: :infinity)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
{:ok,
|
{:ok,
|
||||||
socket
|
socket
|
||||||
|> assign(conversations: conversations)
|
|> assign(conversations: [])
|
||||||
|> assign(ai_providers: ai_providers)
|
|> assign(ai_providers: [])
|
||||||
|> assign(new_name: "")
|
|> assign(new_name: "")
|
||||||
|> assign(error: nil)}
|
|> assign(error: nil)}
|
||||||
end
|
end
|
||||||
@@ -109,6 +98,25 @@ defmodule ElixirAiWeb.HomeLive do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def handle_info(:load_data, socket) do
|
||||||
|
conversations = ConversationManager.list_conversations()
|
||||||
|
|
||||||
|
Logger.debug(
|
||||||
|
"Conversations: #{inspect(conversations, limit: :infinity, printable_limit: :infinity)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
ai_providers = AiProvider.all()
|
||||||
|
|
||||||
|
Logger.debug(
|
||||||
|
"AI Providers: #{inspect(ai_providers, limit: :infinity, printable_limit: :infinity)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
{:noreply,
|
||||||
|
socket
|
||||||
|
|> assign(conversations: conversations)
|
||||||
|
|> assign(ai_providers: ai_providers)}
|
||||||
|
end
|
||||||
|
|
||||||
def handle_info({:provider_added, _attrs}, socket) do
|
def handle_info({:provider_added, _attrs}, socket) do
|
||||||
{:noreply, assign(socket, ai_providers: AiProvider.all())}
|
{:noreply, assign(socket, ai_providers: AiProvider.all())}
|
||||||
end
|
end
|
||||||
|
|||||||
3
mix.exs
3
mix.exs
@@ -59,7 +59,8 @@ defmodule ElixirAi.MixProject do
|
|||||||
{:ecto_sql, "~> 3.11"},
|
{:ecto_sql, "~> 3.11"},
|
||||||
{:postgrex, ">= 0.0.0"},
|
{:postgrex, ">= 0.0.0"},
|
||||||
{:horde, "~> 0.9"},
|
{:horde, "~> 0.9"},
|
||||||
{:credo, "~> 1.7", only: [:dev, :test], runtime: false}
|
{:credo, "~> 1.7", only: [:dev, :test], runtime: false},
|
||||||
|
{:zoi, "~> 0.17"}
|
||||||
]
|
]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
1
mix.lock
1
mix.lock
@@ -66,4 +66,5 @@
|
|||||||
"unicode_util_compat": {:hex, :unicode_util_compat, "0.7.1", "a48703a25c170eedadca83b11e88985af08d35f37c6f664d6dcfb106a97782fc", [:rebar3], [], "hexpm", "b3a917854ce3ae233619744ad1e0102e05673136776fb2fa76234f3e03b23642"},
|
"unicode_util_compat": {:hex, :unicode_util_compat, "0.7.1", "a48703a25c170eedadca83b11e88985af08d35f37c6f664d6dcfb106a97782fc", [:rebar3], [], "hexpm", "b3a917854ce3ae233619744ad1e0102e05673136776fb2fa76234f3e03b23642"},
|
||||||
"websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"},
|
"websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"},
|
||||||
"websock_adapter": {:hex, :websock_adapter, "0.5.9", "43dc3ba6d89ef5dec5b1d0a39698436a1e856d000d84bf31a3149862b01a287f", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "5534d5c9adad3c18a0f58a9371220d75a803bf0b9a3d87e6fe072faaeed76a08"},
|
"websock_adapter": {:hex, :websock_adapter, "0.5.9", "43dc3ba6d89ef5dec5b1d0a39698436a1e856d000d84bf31a3149862b01a287f", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "5534d5c9adad3c18a0f58a9371220d75a803bf0b9a3d87e6fe072faaeed76a08"},
|
||||||
|
"zoi": {:hex, :zoi, "0.17.1", "406aa87bb4181f41dee64336b75434367b7d3e88db813b0e6db0ae2d0f81f743", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "3a11bf3bc9189f988ac74e81b5d7ca0c689b2a20eed220746a7043aa528e2aab"},
|
||||||
}
|
}
|
||||||
|
|||||||
113
test/db_helper_test.exs
Normal file
113
test/db_helper_test.exs
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
defmodule SQLTest do
|
||||||
|
use ExUnit.Case
|
||||||
|
alias ElixirAi.Data.DbHelpers
|
||||||
|
|
||||||
|
test "converts simple named parameters" do
|
||||||
|
query = "SELECT * FROM users WHERE id = $(id) AND email = $(email)"
|
||||||
|
|
||||||
|
params = %{
|
||||||
|
"id" => 10,
|
||||||
|
"email" => "test@example.com"
|
||||||
|
}
|
||||||
|
|
||||||
|
assert DbHelpers.named_params_to_positional_params(query, params) ==
|
||||||
|
{
|
||||||
|
"SELECT * FROM users WHERE id = $1 AND email = $2",
|
||||||
|
[10, "test@example.com"]
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "reuses positional parameter for repeated named parameter" do
|
||||||
|
query = """
|
||||||
|
SELECT * FROM users
|
||||||
|
WHERE id = $(id)
|
||||||
|
OR owner_id = $(id)
|
||||||
|
"""
|
||||||
|
|
||||||
|
params = %{"id" => 42}
|
||||||
|
|
||||||
|
assert DbHelpers.named_params_to_positional_params(query, params) ==
|
||||||
|
{
|
||||||
|
"""
|
||||||
|
SELECT * FROM users
|
||||||
|
WHERE id = $1
|
||||||
|
OR owner_id = $1
|
||||||
|
""",
|
||||||
|
[42]
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "assigns parameters in order of first appearance" do
|
||||||
|
query = "SELECT * FROM items WHERE category = $(category) AND owner = $(owner)"
|
||||||
|
|
||||||
|
params = %{
|
||||||
|
"owner" => 5,
|
||||||
|
"category" => "books"
|
||||||
|
}
|
||||||
|
|
||||||
|
assert DbHelpers.named_params_to_positional_params(query, params) ==
|
||||||
|
{
|
||||||
|
"SELECT * FROM items WHERE category = $1 AND owner = $2",
|
||||||
|
["books", 5]
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "handles multiple distinct parameters" do
|
||||||
|
query = "INSERT INTO posts(title, body, author_id) VALUES($(title), $(body), $(author))"
|
||||||
|
|
||||||
|
params = %{
|
||||||
|
"title" => "Hello",
|
||||||
|
"body" => "World",
|
||||||
|
"author" => 7
|
||||||
|
}
|
||||||
|
|
||||||
|
assert DbHelpers.named_params_to_positional_params(query, params) ==
|
||||||
|
{
|
||||||
|
"INSERT INTO posts(title, body, author_id) VALUES($1, $2, $3)",
|
||||||
|
["Hello", "World", 7]
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "works when same parameter appears many times" do
|
||||||
|
query = """
|
||||||
|
SELECT *
|
||||||
|
FROM logs
|
||||||
|
WHERE user_id = $(user)
|
||||||
|
OR editor_id = $(user)
|
||||||
|
OR reviewer_id = $(user)
|
||||||
|
"""
|
||||||
|
|
||||||
|
params = %{"user" => 99}
|
||||||
|
|
||||||
|
assert DbHelpers.named_params_to_positional_params(query, params) ==
|
||||||
|
{
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM logs
|
||||||
|
WHERE user_id = $1
|
||||||
|
OR editor_id = $1
|
||||||
|
OR reviewer_id = $1
|
||||||
|
""",
|
||||||
|
[99]
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "raises if parameter is missing" do
|
||||||
|
query = "SELECT * FROM users WHERE id = $(id)"
|
||||||
|
|
||||||
|
params = %{}
|
||||||
|
|
||||||
|
assert_raise KeyError, fn ->
|
||||||
|
DbHelpers.named_params_to_positional_params(query, params)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
test "query without named parameters returns unchanged query and empty params" do
|
||||||
|
query = "SELECT * FROM users"
|
||||||
|
|
||||||
|
params = %{}
|
||||||
|
|
||||||
|
assert DbHelpers.named_params_to_positional_params(query, params) ==
|
||||||
|
{"SELECT * FROM users", []}
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
defmodule ElixirAiWeb.PageControllerTest do
|
defmodule ElixirAiWeb.PageControllerTest do
|
||||||
use ElixirAiWeb.ConnCase
|
use ElixirAiWeb.ConnCase
|
||||||
|
|
||||||
|
# homepage need db to test
|
||||||
test "GET /", %{conn: conn} do
|
test "GET /", %{conn: conn} do
|
||||||
conn = get(conn, ~p"/")
|
conn = get(conn, ~p"/")
|
||||||
assert html_response(conn, 200) =~ "Peace of mind from prototype to production"
|
assert html_response(conn, 200) =~ "Conversations"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user