Skip to main content

Feature-rich interactive CLI for AI agents with token tracking, prompt templates, aliases, and configuration

Project description

Basic Agent Chat Loop

PyPI version Python 3.8+ Tests codecov License: MIT

A feature-rich, interactive CLI for AI agents with token tracking, prompt templates, agent aliases, and extensive configuration options.

Features

  • ๐Ÿท๏ธ Agent Aliases - Save agents as short names (chat_loop pete instead of full paths)
  • ๐Ÿ“ฆ Auto-Setup - Automatically install agent dependencies from requirements.txt or pyproject.toml
  • ๐Ÿ”” Audio Notifications - Play sound when agent completes a turn (cross-platform support)
  • ๐ŸŽต Harmony Support - Specialized processing for OpenAI Harmony format (gpt-oss models)
  • ๐Ÿ“œ Command History - Navigate previous queries with โ†‘โ†“ arrows (persisted to ~/.chat_history)
  • โœ๏ธ Multi-line Input - Type \\ to enter multi-line mode with Ctrl+D to cancel and โ†‘ to edit previous lines
  • ๐Ÿ’พ Session Management - Save, resume, and search previous conversations with full context restoration
  • ๐Ÿ“‹ Copy Commands - Copy responses, queries, code blocks, or entire conversations to clipboard
  • ๐Ÿ’ฐ Token Tracking - Track tokens and costs per query and session
  • ๐Ÿ“ Prompt Templates - Reusable prompts from ~/.prompts/
  • โš™๏ธ Configuration - YAML-based config with per-agent overrides
  • ๐Ÿ“Š Status Bar - Real-time metrics (queries, tokens, duration)
  • ๐Ÿ“ˆ Session Summary - Full statistics displayed on exit
  • ๐ŸŽจ Rich Formatting - Enhanced markdown rendering with syntax highlighting
  • ๐Ÿ”„ Error Recovery - Automatic retry logic with exponential backoff
  • ๐Ÿ” Agent Metadata - Display model, tools, and capabilities

Installation

Quick Install (Recommended)

pip install basic-agent-chat-loop

That's it! The package will automatically create:

  • ~/.chatrc - Configuration file with recommended defaults
  • ~/.prompts/ - Sample prompt templates (on first use)

Platform-Specific Options

Windows: Command history support (pyreadline3) is now installed automatically on Windows - no extra steps needed!

AWS Bedrock integration:

pip install basic-agent-chat-loop[bedrock]

From Source

For development or the latest features:

git clone https://github.com/Open-Agent-Tools/Basic-Agent-Chat-Loop.git
cd Basic-Agent-Chat-Loop
pip install -e ".[dev]"

See docs/INSTALL.md for detailed installation instructions and troubleshooting.

Quick Start

Basic Usage

# Run with agent path
chat_loop path/to/your/agent.py

# Or use an alias (after saving)
chat_loop myagent

Agent Aliases

Save frequently used agents for quick access:

# Save an agent as an alias
chat_loop --save-alias myagent path/to/agent.py

# Use the alias from anywhere
chat_loop myagent

# List all saved aliases
chat_loop --list-aliases

# Remove an alias
chat_loop --remove-alias myagent

Example with real agents:

# Save your agents
chat_loop --save-alias pete ~/agents/product_manager/agent.py
chat_loop --save-alias dev ~/agents/senior_developer/agent.py

# Use them from anywhere
cd ~/projects/my-app
chat_loop dev  # Get coding help
chat_loop pete  # Get product feedback

Aliases are stored in ~/.chat_aliases and work from any directory.

Auto-Setup Dependencies

Automatically install agent dependencies with the --auto-setup flag (or -a for short):

# Auto-install dependencies when running an agent
chat_loop myagent --auto-setup
chat_loop path/to/agent.py -a

# Works with any of these dependency files:
# - requirements.txt (most common)
# - pyproject.toml (modern Python projects)
# - setup.py (legacy projects)

Smart detection: If you run an agent without --auto-setup and dependency files are detected, you'll see a helpful suggestion:

chat_loop myagent
๐Ÿ’ก Found requirements.txt in agent directory. Run with --auto-setup (or -a) to install dependencies automatically

What gets installed:

  • requirements.txt โ†’ pip install -r requirements.txt
  • pyproject.toml โ†’ pip install -e <agent_directory>
  • setup.py โ†’ pip install -e <agent_directory>

This makes sharing agents easierโ€”just include a requirements.txt with your agent and users can install everything with one command.

Prompt Templates

The package automatically creates sample templates in ~/.prompts/ on first use:

  • explain.md - Explain code in detail
  • review.md - Code review with best practices
  • debug.md - Help debugging issues
  • optimize.md - Performance optimization suggestions
  • test.md - Generate test cases
  • document.md - Add documentation

Use templates in chat:

chat_loop myagent
You: /review src/app.py
You: /explain utils.py
You: /test my_function

Create custom templates:

# Create your own template
cat > ~/.prompts/security.md <<'EOF'
# Security Review

Please review this code for security vulnerabilities:

{input}

Focus on:
- Input validation
- Authentication/authorization
- Data sanitization
- Common security patterns
EOF

# Use it in chat
You: /security auth.py

Configuration

A configuration file (~/.chatrc) is automatically created on first use with recommended defaults. You can customize it to your preferences:

features:
  show_tokens: true           # Display token counts
  show_metadata: true         # Show agent model/tools info
  rich_enabled: true          # Enhanced formatting

ui:
  show_status_bar: true       # Top status bar
  show_duration: true         # Query duration

audio:
  enabled: true               # Play sound when agent completes
  notification_sound: null    # Custom WAV file (null = bundled sound)

behavior:
  max_retries: 3              # Retry attempts on failure
  timeout: 120.0              # Request timeout (seconds)

# Per-agent overrides
agents:
  'Product Pete':
    features:
      show_tokens: false
    audio:
      enabled: false          # Disable audio for this agent

Audio Notifications

Audio notifications alert you when the agent completes a response. Enabled by default with a bundled notification sound.

Platforms supported:

  • macOS (using afplay)
  • Linux (using aplay or paplay)
  • Windows (using winsound)

Configure audio in ~/.chatrc:

audio:
  enabled: true
  notification_sound: null    # Use bundled sound

  # Or specify a custom WAV file:
  # notification_sound: /path/to/custom.wav

Per-agent overrides:

agents:
  'Silent Agent':
    audio:
      enabled: false  # Disable audio for this agent

See CONFIG.md for full configuration options.

Commands

Command Description
help Show help message
info Show agent details (model, tools)
templates List available prompt templates
sessions List all saved conversation sessions
/name Use prompt template from ~/.prompts/name.md
resume <#> Resume a previous session by number or ID
copy Copy last response to clipboard (see variants below)
clear Clear screen and reset agent session
exit, quit Exit chat (shows session summary)

Session Management

Save conversations automatically:

# Enable auto-save in config
features:
  auto_save: true

Resume a previous conversation:

# In chat - list sessions
You: sessions

Available Sessions (3):
  1. MyAgent - Jan 26, 14:30 - 15 queries - $0.48
     "Can you help me build a REST API..."

  2. MyAgent - Jan 25, 09:15 - 7 queries - $0.23
     "Explain async/await in Python..."

# Resume by number
You: resume 1

# Or resume on startup
chat_loop myagent --resume
chat_loop myagent --resume 1
chat_loop myagent --resume myagent_20250126_143022

List all saved sessions:

chat_loop --list-sessions

Sessions are saved to ~/agent-conversations/ by default (configurable).

Copy Commands

Quickly copy content to clipboard:

Available copy commands:

# Copy last agent response (default)
You: copy

# Copy your last query
You: copy query

# Copy entire conversation as markdown
You: copy all

# Copy only code blocks from last response
You: copy code

Example workflow:

You: Write a Python function to reverse a string

Agent: Here's a function to reverse a string:

    def reverse_string(s):
        return s[::-1]

You: copy code
โœ“ Copied code blocks from last response to clipboard

# Now paste into your editor with Cmd+V (Mac) or Ctrl+V (Windows/Linux)

Multi-line Input

Press \\ to enter multi-line mode:

You: \\
... def factorial(n):
...     if n <= 1:
...         return 1
...     return n * factorial(n - 1)
...
[Press Enter on empty line to submit]

Token Tracking

During Chat

When show_tokens: true in config:

------------------------------------------------------------
Time: 6.3s โ”‚ 1 cycle โ”‚ Tokens: 4.6K (in: 4.4K, out: 237) โ”‚ Cost: $0.017

Session Summary

Always shown on exit:

============================================================
Session Summary
------------------------------------------------------------
  Duration: 12m 34s
  Queries: 15
  Tokens: 67.8K (in: 45.2K, out: 22.6K)
  Total Cost: $0.475
============================================================

Programmatic Usage

from basic_agent_chat_loop import ChatLoop

# Create chat interface
chat = ChatLoop(
    agent=your_agent,
    name="My Agent",
    description="Agent description",
    config_path=Path("~/.chatrc")  # Optional
)

# Run interactive loop
chat.run()

Harmony Format Support

The chat loop includes built-in support for the OpenAI Harmony response format (designed for gpt-oss open-weight models). Harmony support is included by default in all installations.

What is Harmony?

Harmony is OpenAI's response formatting standard for their open-weight model series (gpt-oss). It provides:

  • Structured conversation handling with multiple output channels
  • Reasoning output generation (internal analysis separate from final response)
  • Function call management with namespaces
  • Tool usage tracking and structured outputs

Automatic Detection

The chat loop automatically detects Harmony agents by checking for:

  • Explicit uses_harmony attribute on the agent
  • Model names containing "gpt-oss" or "harmony"
  • Harmony-specific methods or attributes
  • Agent class names containing "harmony"

Enhanced Display

When a Harmony agent is detected, responses are automatically processed to:

  • Extract and display multiple output channels (analysis, commentary, final)
  • Highlight internal reasoning separately from the final response
  • Detect and format tool calls appropriately
  • Parse structured Harmony response formats

Detailed Thinking Mode

By default, only the final response is shown. You can enable detailed thinking mode to see the agent's internal reasoning with labeled prefixes:

Configuration:

# In ~/.chatrc or .chatrc
harmony:
  show_detailed_thinking: false  # Default - only show final response

With detailed thinking enabled (true):

๐Ÿ’ญ [REASONING]
I need to analyze this query for potential bottlenecks...

๐Ÿ“Š [ANALYSIS]
Looking at the query structure:
- Multiple table joins without proper indexes
- WHERE clause filtering happens after the joins

๐Ÿ“ [COMMENTARY]
This is a common pattern I see in legacy codebases...

๐Ÿ’ฌ [RESPONSE]
Here are three optimizations for your database query...

With detailed thinking disabled (false, default):

Here are three optimizations for your database query...

Example

# Your agent using Harmony
class MyHarmonyAgent:
    uses_harmony = True  # Explicit marker

    def __call__(self, query):
        # Agent returns Harmony-formatted response
        return harmony_response

# Chat loop will automatically detect and handle Harmony format
chat_loop my_harmony_agent

Requirements

Core Dependencies

  • Python 3.9+ (required by openai-harmony dependency)
  • pyyaml>=6.0.1 - Configuration file parsing
  • rich>=13.7.0 - Enhanced terminal rendering
  • pyperclip>=1.8.0 - Clipboard support for copy commands
  • openai-harmony>=0.0.8 - OpenAI Harmony format support (built-in)
  • pyreadline3>=3.4.1 - Command history on Windows (auto-installed on Windows)

Optional Dependencies

  • anthropic-bedrock>=0.8.0 - AWS Bedrock integration (install with [bedrock])

Built-in Features

  • readline (built-in on Unix) - Command history on macOS/Linux

Platform Support

  • โœ… macOS - Full support with native readline
  • โœ… Linux - Full support with native readline
  • โœ… Windows - Full support with automatic pyreadline3 installation

Architecture

src/basic_agent_chat_loop/
โ”œโ”€โ”€ chat_loop.py          # Main orchestration
โ”œโ”€โ”€ chat_config.py        # Configuration management
โ”œโ”€โ”€ cli.py                # CLI entry point
โ”œโ”€โ”€ components/           # Modular components
โ”‚   โ”œโ”€โ”€ ui_components.py      # Colors, StatusBar
โ”‚   โ”œโ”€โ”€ token_tracker.py      # Token/cost tracking
โ”‚   โ”œโ”€โ”€ template_manager.py   # Prompt templates
โ”‚   โ”œโ”€โ”€ display_manager.py    # Display formatting
โ”‚   โ”œโ”€โ”€ agent_loader.py       # Agent loading
โ”‚   โ””โ”€โ”€ alias_manager.py      # Alias management
docs/
โ”œโ”€โ”€ ALIASES.md            # Alias system guide
โ”œโ”€โ”€ CONFIG.md             # Configuration reference
โ”œโ”€โ”€ INSTALL.md            # Installation instructions
โ””โ”€โ”€ Chat_TODO.md          # Roadmap and future features

Documentation

Development

Running Tests

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

Code Quality

# Format code
black src/ tests/

# Lint
ruff check src/ tests/

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details.

Changelog

See CHANGELOG.md for detailed version history.

Latest Release: v0.1.0 (2025-10-09)

Initial public release with:

  • ๐Ÿท๏ธ Agent alias system
  • ๐Ÿ“ Prompt templates with auto-setup
  • ๐Ÿ’ฐ Token tracking and cost estimation
  • โš™๏ธ YAML configuration with auto-setup
  • ๐Ÿ“Š Status bar and session summaries
  • ๐ŸŽจ Rich markdown rendering
  • ๐Ÿ”„ Automatic error recovery
  • ๐Ÿ“œ Persistent command history
  • โœ… 61% test coverage (158 tests)

Troubleshooting

See docs/TROUBLESHOOTING.md for common issues and solutions.

Quick fixes:

  • Package not found: Run pip install --upgrade basic-agent-chat-loop
  • Command not found: Ensure pip's bin directory is in your PATH
  • Import errors: Try reinstalling with pip install --force-reinstall basic-agent-chat-loop

Support

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

basic_agent_chat_loop-1.3.1.tar.gz (183.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

basic_agent_chat_loop-1.3.1-py3-none-any.whl (179.5 kB view details)

Uploaded Python 3

File details

Details for the file basic_agent_chat_loop-1.3.1.tar.gz.

File metadata

  • Download URL: basic_agent_chat_loop-1.3.1.tar.gz
  • Upload date:
  • Size: 183.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for basic_agent_chat_loop-1.3.1.tar.gz
Algorithm Hash digest
SHA256 06f8f20213bdeb01f3d0d257bfc280bb7e71e9ff359c8030c5c59110834c0615
MD5 9fa1dc2b0071cab323857520d5f565ce
BLAKE2b-256 329fe5e371e7c5c625d046eb9bd4d1b30cd330875472f3eec2b35b643c322634

See more details on using hashes here.

Provenance

The following attestation bundles were made for basic_agent_chat_loop-1.3.1.tar.gz:

Publisher: publish.yml on Open-Agent-Tools/Basic-Agent-Chat-Loop

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file basic_agent_chat_loop-1.3.1-py3-none-any.whl.

File metadata

File hashes

Hashes for basic_agent_chat_loop-1.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 799e6986fee35c2d1cd3ac153f28e5d399a6a5fb091ab37825c7867f03b43e4a
MD5 76d9ca950291cbb7235d05d12656dae8
BLAKE2b-256 6984ea238c63860344fc72d545e017d216deaf58070bd4174d2c0a1213433d6a

See more details on using hashes here.

Provenance

The following attestation bundles were made for basic_agent_chat_loop-1.3.1-py3-none-any.whl:

Publisher: publish.yml on Open-Agent-Tools/Basic-Agent-Chat-Loop

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page