Current section
Files
Jump to
Current section
Files
lib/superintelligence/ai_agent/agent.ex
defmodule Superintelligence.AIAgent.Agent do
use GenServer
require Logger
@moduledoc """
Individual AI agent that can autonomously execute tasks.
"""
def start_link(opts) do
name = Keyword.get(opts, :name, __MODULE__)
GenServer.start_link(__MODULE__, opts, name: via_tuple(name))
end
@impl true
def init(opts) do
{:ok, %{
name: Keyword.get(opts, :name, "agent_#{:rand.uniform(1000)}"),
config: Keyword.get(opts, :config, %{}),
status: :idle,
current_task: nil,
stats: %{
tasks_completed: 0,
tasks_failed: 0,
total_execution_time: 0
}
}}
end
# Client API
def execute_task(agent_name, task) do
GenServer.call(via_tuple(agent_name), {:execute_task, task})
end
def get_status(agent_name) do
GenServer.call(via_tuple(agent_name), :get_status)
end
def get_stats(agent_name) do
GenServer.call(via_tuple(agent_name), :get_stats)
end
# Server Callbacks
@impl true
def handle_call({:execute_task, task}, _from, state) do
if state.status == :busy do
{:reply, {:error, "Agent is busy"}, state}
else
# Start task execution
start_time = System.monotonic_time(:millisecond)
# Execute the task using the Brain
result = Superintelligence.AIAgent.Brain.process_task(task)
# Calculate execution time
execution_time = System.monotonic_time(:millisecond) - start_time
# Update stats
new_stats = case result do
{:ok, _} ->
%{state.stats |
tasks_completed: state.stats.tasks_completed + 1,
total_execution_time: state.stats.total_execution_time + execution_time
}
{:error, _} ->
%{state.stats |
tasks_failed: state.stats.tasks_failed + 1,
total_execution_time: state.stats.total_execution_time + execution_time
}
end
{:reply, result, %{state | status: :idle, current_task: nil, stats: new_stats}}
end
end
@impl true
def handle_call(:get_status, _from, state) do
{:reply, %{
name: state.name,
status: state.status,
current_task: state.current_task
}, state}
end
@impl true
def handle_call(:get_stats, _from, state) do
{:reply, state.stats, state}
end
# Private Functions
defp via_tuple(name) do
{:via, Registry, {Superintelligence.AIAgent.Registry, name}}
end
end