ConnectOnionConnectOnion

Quick Start Guide

Get up and running with ConnectOnion in under 2 minutes.

Estimated time: 2 minutes to first working agent

1
Install ConnectOnion

Terminal
$pip install connectonion

2
Create Your First Meta-Agent

Initialize a ConnectOnion development assistant with powerful built-in capabilities:

Terminal
$mkdir meta-agent
$cd meta-agent
$co init

Files created:

meta-agent/
├──🐍agent.py# Your meta-agent with tools
├──prompt.md# Main system prompt
├──prompts/# Specialized prompts
├──metagent.md
├──docs_retrieve_prompt.md
├──answer_prompt.md
└──think_prompt.md
├──.env.example# API key template
├──.gitignore# Git config
└──.co/# ConnectOnion config
├──config.toml
└──docs/
└──connectonion.md

Your meta-agent includes:

  • answer_connectonion_question() - Expert answers from embedded docs
  • create_agent_from_template() - Generate complete agent code
  • generate_tool_code() - Create tool functions
  • create_test_for_agent() - Generate pytest test suites
  • think() - Self-reflection to analyze tasks
  • generate_todo_list() - Create structured plans (uses GPT-4o-mini)
  • suggest_project_structure() - Architecture recommendations

3
Set Up Your API Key

Terminal
$cp .env.example .env

Then edit .env and add your OpenAI API key:

.env
# OpenAI API Configuration
OPENAI_API_KEY=sk-your-actual-api-key-here

4
Try These Commands

Your meta-agent can help you build ConnectOnion projects:

main.py
1# Learn about ConnectOnion 2result = agent.input("What is ConnectOnion and how do tools work?") 3print(result)
Python REPL
Interactive
>>> result = agent.input("What is ConnectOnion and how do tools work?")
>>> print(result)
ConnectOnion is a Python framework for building AI agents with a focus on simplicity.
Here's how it works:
 
1. **Agent Creation**: Create agents with a name, tools, and optional system prompt
2. **Tools**: Functions that agents can call. Any Python function can be a tool!
3. **Automatic Schema Generation**: Type hints are converted to OpenAI function schemas
4. **Iteration Control**: Use max_iterations to prevent infinite loops
5. **Built-in Logging**: All agent interactions are automatically logged to `.co/logs/`
 
Tools work by:
- Converting Python functions to OpenAI-compatible schemas
- The agent decides when to call tools based on the task
- Tool results are fed back to the agent for further processing
- Multiple tools can be called in sequence to complete complex tasks
main.py
1# Generate agent code 2result = agent.input("Create a web scraper agent") 3print(result[:500] + "...") # Show first 500 chars
Python REPL
Interactive
>>> result = agent.input("Create a web scraper agent")
>>> print(result[:500] + "...")
Here's a complete web scraper agent using ConnectOnion:
 
```python
from connectonion import Agent
import requests
from bs4 import BeautifulSoup
 
def scrape_url(url: str) -> str:
"""Scrape content from a URL."""
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.get_text()[:1000]
 
def extract_links(url: str) -> list[str]:
"""Extract all links from a webpage."""
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
return [a['href'] for a in soup.find_all('a', href=True)]...
main.py
1# Create tool functions 2result = agent.input("Generate a tool for sending emails") 3print(result)
Python REPL
Interactive
>>> result = agent.input("Generate a tool for sending emails")
>>> print(result)
Here's an email sending tool for your agent:
 
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 
def send_email(to: str, subject: str, body: str, from_email: str = "agent@example.com") -> str:
"""Send an email to the specified recipient.
Args:
to: Recipient email address
subject: Email subject line
body: Email body content
from_email: Sender email address
Returns:
Status message indicating success or failure
"""
try:
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# Configure your SMTP server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, 'your_app_password')
server.send_message(msg)
server.quit()
return f"Email sent successfully to {to}"
except Exception as e:
return f"Failed to send email: {str(e)}"
```
 
Usage: agent = Agent("mailer", tools=[send_email])

5
Alternative: Playwright Web Automation

For web automation tasks, use the Playwright template:

Terminal
$co init --template playwright

Stateful browser tools included:

start_browser() - Launch browser
navigate() - Go to URLs
scrape_content() - Extract content
fill_form() - Complete forms
take_screenshot() - Capture pages
extract_links() - Get all links
click() - Click elements
execute_javascript() - Run JS

Note: Requires pip install playwright && playwright install

6
Create a Custom Tool Agent

You can also create agents from scratch with custom tools:

main.py
1from connectonion import Agent 2 3def calculate(expression: str) -> str: 4 """Safely evaluate mathematical expressions.""" 5 try: 6 allowed_chars = set('0123456789+-*/()., ') 7 if all(c in allowed_chars for c in expression): 8 result = eval(expression) 9 return f"Result: {result}" 10 else: 11 return "Error: Invalid characters" 12 except Exception as e: 13 return f"Error: {str(e)}" 14 15# Create agent with the tool 16agent = Agent( 17 name="calculator", 18 tools=[calculate], 19 system_prompt="You are a helpful math tutor.", 20 max_iterations=5 # Simple calculations need few iterations 21) 22 23# Use the agent 24response = agent.input("What is 42 * 17 + 25?") 25print(response)
Python REPL
Interactive
Let me calculate that for you.
 
42 * 17 = 714
714 + 25 = 739
 
The answer is 739.

7
Debugging with @xray

Use the @xray decorator to see what your agent is thinking:

main.py
1from connectonion import Agent 2from connectonion.decorators import xray 3 4@xray 5def calculate(expression: str) -> str: 6 """Math tool with debugging enabled.""" 7 print(f"[SEARCH] Agent '{xray.agent.name}' is calculating: {expression}") 8 print(f"[SEARCH] User's original request: {xray.task}") 9 print(f"[SEARCH] This is iteration #{xray.iteration}" 10 11 result = eval(expression) 12 return f"Result: {result}" 13 14agent = Agent("debug_calc", tools=[calculate], max_iterations=5) 15response = agent.input("What's 50 + 30?") 16print(response)
Python REPL
Interactive
[SEARCH] Agent 'debug_calc' is calculating: 50 + 30
[SEARCH] User's original request: What's 50 + 30?
[SEARCH] This is iteration #1
Result: 80
 
The result is 80.

What's Next?