Skip to content

Instantly share code, notes, and snippets.

@herissondev
Created August 13, 2025 14:55
Show Gist options
  • Save herissondev/fc0bbebd87a8ca4cf930a8f5df100062 to your computer and use it in GitHub Desktop.
Save herissondev/fc0bbebd87a8ca4cf930a8f5df100062 to your computer and use it in GitHub Desktop.
Minimal AI agent in elixir
defmodule ElixirAiAgent do
@moduledoc """
A minimal ai agent implementation showcasing how simple it is to build AI agents in Elixir.
Combines agent logic and server management in one module.
"""
use GenServer
alias LangChain.Chains.LLMChain
alias LangChain.Message
defstruct [:id, :name, :chain]
# Client API
def start_agent(name, config \\ %{}) do
GenServer.start_link(__MODULE__, {name, config}, name: via_tuple(name))
end
def chat(agent_name, message) do
GenServer.call(via_tuple(agent_name), {:chat, message})
end
# Server callbacks
def init({name, config}) do
agent = %ElixirAiAgent{
id: :crypto.strong_rand_bytes(8),
name: name,
chain: config[:chain] || LLMChain.new!()
}
{:ok, agent}
end
def handle_call({:chat, message}, _from, agent) do
user_message = Message.new_user!(message)
updated_chain = LLMChain.add_message(agent.chain, user_message)
case LLMChain.run(updated_chain) do
{:ok, final_chain} ->
updated_agent = %{agent | chain: final_chain}
response = final_chain.last_message
{:reply, {:ok, response}, updated_agent}
{:error, _, reason} ->
{:reply, {:error, reason}, agent}
end
end
# Helper functions
defp via_tuple(name), do: {:via, Registry, {SimpleAgentRegistry, name}}
end
# # Start the registry first
# Registry.start_link(keys: :unique, name: SimpleAgentRegistry)
#
# # Create and use an agent
# {:ok, _pid} = SimpleAgent.start_agent("my_agent")
# {:ok, response} = SimpleAgent.chat("my_agent", "Hello, how are you?")
# IO.puts(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment