Skip to content

Quick Start

This guide will help you get started with nagents in minutes.

Basic Usage

1. Create a Provider

First, create a provider with your API credentials:

from nagents import Provider, ProviderType

provider = Provider(
    provider_type=ProviderType.OPENAI_COMPATIBLE,
    api_key="sk-...",
    model="gpt-4o-mini",
)
from nagents import Provider, ProviderType

provider = Provider(
    provider_type=ProviderType.ANTHROPIC,
    api_key="sk-ant-...",
    model="claude-3-5-sonnet-20241022",
)
from nagents import Provider, ProviderType

provider = Provider(
    provider_type=ProviderType.GEMINI_NATIVE,
    api_key="...",
    model="gemini-2.0-flash",
)

2. Create a Session Manager

Required Component

The session_manager parameter is required when creating an Agent. It handles conversation persistence.

from pathlib import Path
from nagents import SessionManager

session_manager = SessionManager(Path("sessions.db"))

3. Create an Agent

from nagents import Agent

agent = Agent(
    provider=provider,
    session_manager=session_manager,
    system_prompt="You are a helpful assistant.",  # (1)!
    streaming=True,
)
  1. The system prompt is optional but recommended to define the agent's behavior.

4. Run a Conversation

import asyncio
from nagents import TextChunkEvent


async def main():
    try:
        async for event in agent.run("What is the capital of France?"):
            if isinstance(event, TextChunkEvent):
                print(event.chunk, end="", flush=True)
        print()  # newline at end
    finally:
        await agent.close()


asyncio.run(main())

Complete Example

Here's a complete, runnable example:

basic_agent.py
import asyncio
import os
from pathlib import Path
from nagents import Agent, ErrorEvent, Provider, ProviderType, SessionManager, TextChunkEvent


async def main():
    # 1. Create provider
    provider = Provider(
        provider_type=ProviderType.OPENAI_COMPATIBLE,
        api_key=os.environ["OPENAI_API_KEY"],
        model=os.environ["OPENAI_MODEL"],
    )

    # 2. Create session manager
    session_manager = SessionManager(Path("sessions.db"))

    # 3. Create agent
    agent = Agent(
        provider=provider,
        session_manager=session_manager,
        streaming=True,
    )

    # 4. Run conversation
    try:
        async for event in agent.run("Hello! What can you help me with?"):
            if isinstance(event, TextChunkEvent):
                print(event.chunk, end="", flush=True)
            elif isinstance(event, ErrorEvent):
                print(f"\nError: {event.message}")
        print()
    finally:
        await agent.close()


if __name__ == "__main__":
    asyncio.run(main())

Set OPENAI_API_KEY and OPENAI_MODEL before running the complete example. Choose a model available to your account; model names elsewhere on this page are illustrative, not a guarantee of current availability. streaming=True is required for chunk output because agents default to non-streaming. In that mode, read the answer from DoneEvent.final_text instead.


With Tools

Define Python functions as tools that the agent can call:

agent_with_tools.py
from nagents import Agent, Provider, ProviderType, SessionManager
from pathlib import Path


def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"The weather in {city} is sunny, 22°C"


def multiply(a: float, b: float) -> float:
    """Multiply two numbers."""
    return a * b


async def main():
    provider = Provider(...)
    session_manager = SessionManager(Path("sessions.db"))

    agent = Agent(
        provider=provider,
        session_manager=session_manager,
        tools=[get_weather, multiply],  # (1)!
    )

    async for event in agent.run("What's the weather in Paris?"):
        ...
  1. Pass functions directly - nagents automatically generates the tool schema from type hints and docstrings.

Tool Documentation

Always include docstrings in your tool functions! The LLM uses them to understand when and how to call each tool.


With Session Persistence

Sessions allow the agent to remember previous conversations:

persistent_sessions.py
from pathlib import Path
from nagents import Agent, SessionManager, Provider, ProviderType


async def main():
    provider = Provider(...)
    session_manager = SessionManager(Path("sessions.db"))

    agent = Agent(provider=provider, session_manager=session_manager)

    # First conversation - use a specific session ID
    async for event in agent.run(
        "Remember my name is Alice",
        session_id="user-123",  # (1)!
    ):
        ...

    # Later, continue the same session
    async for event in agent.run(
        "What's my name?",
        session_id="user-123",  # (2)!
    ):
        # Agent will remember: "Your name is Alice"
        ...
  1. Use a consistent session ID to maintain conversation history.
  2. Same session ID = same conversation context.

Handling Events

nagents emits various event types during generation:

event_handling.py
from nagents import (
    TextChunkEvent,
    TextDoneEvent,
    ToolCallEvent,
    ToolResultEvent,
    ErrorEvent,
    DoneEvent,
)

async for event in agent.run("Hello"):
    match event:
        case TextChunkEvent(chunk=chunk):
            print(chunk, end="")

        case ToolCallEvent(name=name, arguments=args):
            print(f"\n:material-tools: Calling tool: {name}")

        case ToolResultEvent(result=result):
            print(f":material-check: Tool result: {result}")

        case ErrorEvent(message=msg):
            print(f":material-alert: Error: {msg}")

        case DoneEvent(final_text=text, usage=usage):
            print(f"\n---")
            print(f"Total tokens: {usage.total_tokens}")
            if usage.session:
                print(f"Session tokens: {usage.session.total_tokens}")
Event Types Reference
Event Description
TextChunkEvent Streaming text chunk
TextDoneEvent Complete model-response text (also emitted after streaming)
ToolCallEvent Model is calling a tool
ToolResultEvent Tool execution completed
ErrorEvent Error occurred
DoneEvent Generation complete

Next Steps

  • Configuration


    Learn about generation parameters and HTTP logging.

    Configuration

  • Tools Guide


    Create powerful tools for your agent.

    Tools

  • Sessions Guide


    Manage conversation persistence.

    Sessions