OpenAI.Agent behaviour (openai_agents v0.1.2)

Defines the behavior for OpenAI agents.

An agent is a module that can process inputs, use tools, delegate to other agents, and produce structured outputs.

Example

defmodule MyApp.WeatherAgent do
  use OpenAI.Agent

  @impl true
  def configure do
    %{
      name: "weather_assistant",
      instructions: "You are a helpful weather assistant.",
      model: "gpt-4.1-mini",
      tools: [MyApp.Tools.GetWeather],
      output_schema: MyApp.Schemas.WeatherReport
    }
  end

  @impl true
  def on_start(context, agent_state) do
    # Optional lifecycle callback
    {:ok, agent_state}
  end
end

Summary

Functions

Gets the configuration for an agent module.

Gets the instructions for an agent, resolving dynamic instructions if needed.

Validates an agent module has the required callbacks.

Types

agent_config()

@type agent_config() :: %{
  :name => String.t(),
  :instructions => String.t() | function(),
  optional(:model) => String.t(),
  optional(:model_settings) => map(),
  optional(:tools) => [module()],
  optional(:handoffs) => [module()],
  optional(:input_guardrails) => [module()],
  optional(:output_guardrails) => [module()],
  optional(:output_schema) => module(),
  optional(:hooks) => module(),
  optional(:mcp_servers) => [map()]
}

agent_state()

@type agent_state() :: any()

context()

@type context() :: any()

Callbacks

configure()

@callback configure() :: agent_config()

on_end(context, agent_state)

(optional)
@callback on_end(context(), agent_state()) :: {:ok, agent_state()} | {:error, term()}

on_start(context, agent_state)

(optional)
@callback on_start(context(), agent_state()) :: {:ok, agent_state()} | {:error, term()}

Functions

get_config(agent_module)

@spec get_config(module()) :: agent_config()

Gets the configuration for an agent module.

get_instructions(agent_module, context)

@spec get_instructions(module(), map()) :: {:ok, String.t()} | {:error, term()}

Gets the instructions for an agent, resolving dynamic instructions if needed.

validate_agent(agent_module)

@spec validate_agent(module()) :: :ok | {:error, String.t()}

Validates an agent module has the required callbacks.