Nous AI
Nous is an AI agent framework for Elixir and OTP. Give an agent a job in one line, then send it a message.
agent = Nous.new("openai:gpt-4o-mini", instructions: "Reply with just the French phrase I ask for.")
{:ok, reply} = Nous.run(agent, "How do I say good evening?")
IO.puts(reply.output)
# Bonsoir !
Continue the conversation, give the agent an Elixir function as a tool, or stream its answer into LiveView. For longer-lived applications, Nous can supervise agent sessions, search memory and coordinate agents, and check for regressions offline.
Hex package · API reference · Changelog
Installation
Add Nous to your application's dependencies and run mix deps.get. Use Elixir 1.18+ and OTP 27+.
{:nous, "~> 0.21.1"}
For the live walkthrough, set OPENAI_API_KEY and start iex -S mix, or use a model on your local server. To try the weather agent without credentials, jump to the offline check.
Quick Start
Continue the conversation
Run the translator example above in IEx. Then pass reply.context back so the agent knows which greeting you want to change.
{:ok, morning} = Nous.run(agent, "Make that a morning greeting.", context: reply.context)
IO.puts(morning.output)
# Bonjour !
Give the agent a tool
With a tool-capable model, the agent can call your application for data. Put this module in lib/my_app/weather.ex or paste it into IEx. The fixed forecasts make it easy to see whether the agent actually used your data. Replace the lookup with your application's function when you're ready.
defmodule MyApp.Weather do
@forecasts %{"paris" => "sunny, 24°C", "oslo" => "light rain, 9°C", "tokyo" => "cloudy, 18°C"}
def tool do
Nous.Tool.from_function(&lookup/2,
name: "get_weather",
description: "Get the current weather for a city.",
parameters: %{
"type" => "object",
"properties" => %{"city" => %{"type" => "string"}},
"required" => ["city"]
}
)
end
defp lookup(_ctx, %{"city" => city}) do
forecast = Map.get(@forecasts, String.downcase(city), "no forecast available")
"#{city}: #{forecast}"
end
end
agent = Nous.new("openai:gpt-4o-mini", tools: [MyApp.Weather.tool()])
{:ok, result} = Nous.run(agent, "Use get_weather to check the weather in Tokyo.")
IO.puts(result.output)
result.usage.tool_calls
The answer should mention cloudy skies and 18°C. The tool count tells you whether the model called your function. Pass the returned context into the next turn so the agent can refer to the forecast.
{:ok, follow_up} = Nous.run(agent, "Would I need a jacket there?", context: result.context)
IO.puts(follow_up.output)
Define a named agent
import Nous.DSL
trip =
agent "Trip calculator" do
model "openai:gpt-4o-mini"
fallback ["ollama:qwen3"]
instructions "Round distances to one decimal place."
prompt "How many miles is a 42.2 km marathon?"
tool miles(km: :number), fn km -> km * 0.621371 end
end
{:ok, result} = Nous.run(trip)
Pass a task to Nous.run/2 to override the default prompt. Use tools [MyApp.Weather.tool()] for existing tools or mcp helpdesk: [:get_ticket] for tools available through an authorized MCP connection. To keep the definition in YAML or JSON, use Nous.load_agent!/2 with the names that file may select.
Run the four progressive examples offline, or read the agent definition and MCP guide.
For user-scoped MCP tools, pass the authenticated user's principal: on every run, including when you resume a conversation. Nous uses that identity when discovering tools and again when invoking them.
Stream the run into LiveView
Capture the view's PID before starting the background task. Inside the task, run the same agent with streaming enabled.
Nous.run(agent, prompt, stream: true, notify_pid: view)
The view receives {:tool_result, result} when the tool finishes and {:agent_delta, text} as the model writes. The LiveView walkthrough includes the form, event handlers, and failure path.
Check tool use offline
The packaged example uses a scripted model and the same Tokyo forecast. From a Mix project with Nous installed, save a baseline and compare a second run.
mix nous.eval --task Nous.Eval.Examples.Basic --k 3 --seed 1 --set-baseline weather-demo
mix nous.eval --task Nous.Eval.Examples.Basic --k 3 --seed 1 --baseline weather-demo
Expect five cases and 15 passing samples. The Tokyo case checks that the agent called get_weather with the city argument. To see a regression, use a checkout of Nous and follow the editable exercise. Changing one tool description breaks the weather cases while the arithmetic cases still pass.
Generate and stream text
For a single prompt, call the model directly. generate_text returns the completed string. stream_text returns an enumerable of text chunks you can write as they arrive.
model = "openai:gpt-4o-mini"
{:ok, text} = Nous.generate_text(model, "Explain OTP supervision in one sentence.")
IO.puts(text)
{:ok, chunks} = Nous.stream_text(model, "Give an example of a supervisor restarting a worker.")
Enum.each(chunks, &IO.write/1)
Return structured data
Set output_type: when another function needs to consume the answer. This example extracts two fields from a forecast and returns them as an Elixir map.
extractor = Nous.new("openai:gpt-4o-mini", output_type: %{city: :string, celsius: :integer})
{:ok, %{output: forecast}} = Nous.run(extractor, "Tokyo will be cloudy today with a high of 18°C.")
forecast.celsius
# => 18
For an application record, use an embedded Ecto schema and add changeset validations. The guide also covers raw JSON schemas and retries after validation errors. Structured output guide
Supported Providers
Use the same model string in the text helpers, Nous.new/2, and the named-agent DSL.
| Where the model runs | Provider prefixes | Setup |
|---|---|---|
| Hosted APIs | openai:, anthropic:, gemini:, groq:, mistral:, openrouter:, together: |
Configure the provider’s API key. |
| Google Vertex AI | vertex_ai: |
Configure your Google Cloud project and credentials. Vertex AI setup |
| Local model server | ollama:, lmstudio:, vllm:, sglang: |
Start the server and use its loaded model ID. Pass base_url: for vLLM. |
| In the BEAM process | llamacpp: |
Load a GGUF model with the optional llama_cpp_ex dependency and pass its handle as llamacpp_model:. |
| Other OpenAI-compatible endpoints | custom: |
Supply the endpoint’s base URL and credentials if required. Custom providers |
For example, with qwen3 available in Ollama, Nous.generate_text("ollama:qwen3", "Hello!") runs locally. Set fallback: to an ordered list of backup models to retry eligible provider failures, such as rate limits. Provider configuration · Fallback chains
Built-in tools
Give the agent just the tools its task needs. For example, a release assistant can read the project's changelog using a workspace root supplied by the application at run time.
reader = Nous.new("openai:gpt-4o-mini", tools: [Nous.Tools.FileRead])
{:ok, release} =
Nous.run(reader, "Read CHANGELOG.md and summarize the latest release.",
deps: %{workspace_root: File.cwd!()}
)
IO.puts(release.output)
Add FileGlob to find files by pattern or FileGrep to search their contents. Nous.Tools.WebFetch fetches a web page by URL. For tools that can change the workspace, such as Nous.Tools.FileEdit and Nous.Tools.Bash, supply an approval handler. Choose a sandbox mode to confine shell subprocesses. Tool development · Permissions
If your application uses Nous.Tools.Bash or :command hooks, also add {:net_runner, "~> 1.4.1"} to its dependencies.
Memory, research, and workflows
- Remember facts across conversations. The memory plugin gives the agent tools to remember, recall, and forget. Start with ETS for in-memory lookup, or use SQLite or DuckDB for persistent storage and hybrid text and vector search. Memory guide
- Answer questions over a document collection. The knowledge base ingests documents into linked entries the agent can query. Deep Research handles open-ended questions by searching sources and writing a report with citations. Knowledge base · Deep Research
- Coordinate multi-step work. Define a workflow graph when your application controls the sequence, branches, and checkpoints. Use sub-agent delegation when a model should assign tasks, or a supervised team when agents need roles and shared state. Workflows · Sub-agent example · Teams
Taking an agent into production
| When you need to… | Start here |
|---|---|
| Give tools application data or execute independent calls in parallel | Run context and dependencies · Tool development |
| Let the model write a program that calls several tools in one turn | Code Mode |
| Package reusable instructions or intercept a tool call | Skills · Hooks |
| Require human approval or screen input and tool calls | Permissions and approvals · DecisionGuard |
| Route each turn to a model based on the task | Decision models and routing |
| Keep a session in a supervised GenServer or cancel a run from a view | LiveView and AgentServer |
| Tune connection pooling or use pull-based streaming backpressure | Req and Hackney backends |
| Trace model requests and tool calls or export Prometheus metrics | Observability |
| Compare a prompt or model change against a CI baseline | Evaluation · Versioned profiles and optimization |
| Exercise a multi-turn conversation or score redacted production samples | Simulated users · Online evaluation |
For setup problems or upgrades, see Troubleshooting and the Migration guide. Browse all guides for more.
Run in Livebook
Open a notebook in Livebook to run it interactively. Each notebook installs Nous via Mix.install/2.
| Notebook | What it covers |
|---|---|
First call, first agent, streaming, reading result.usage |
|
| Custom tools, permissions, an interactive approval handler | |
| Ingest, retrieve, and query a knowledge base with Kino inputs |
See the examples collection for runnable scripts and AGENTS.md for coding-agent integration.
Contributing
Contributions welcome. See CONTRIBUTING.md for setup, test commands, code-quality checks, project layout, and the security rules that apply to all code in the repo.
License
Apache 2.0 - see LICENSE
Credits
- Inspired by Pydantic AI — Nous brings the same agent-shaped API to Elixir, layered on OTP for supervision and Phoenix for the UI story.
- HTTP: Req + Finch