Overview
Basic logging helps you debug issues and track agent interactions.Basic Logging
Log important events for debugging.- JavaScript
- Python
- HTTPie
Copy
import { AGIClient } from 'agi';
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message }) => {
return `${timestamp} - ${level} - ${message}`;
})
),
transports: [new winston.transports.Console()]
});
const client = new AGIClient({ apiKey: 'your_api_key' });
async function runTaskWithLogging(task) {
const startTime = Date.now();
let session = null;
try {
session = await client.createSession('agi-0');
logger.info(`Session created: ${session.session_id}`);
await client.sendMessage(session.session_id, task);
logger.info(`Message sent to ${session.session_id}`);
const result = await client.waitForCompletion(session.session_id);
const duration = ((Date.now() - startTime) / 1000).toFixed(2);
logger.info(`Task completed in ${duration}s`);
return result;
} catch (e) {
const duration = ((Date.now() - startTime) / 1000).toFixed(2);
logger.error(`Task failed after ${duration}s: ${e.message}`);
throw e;
} finally {
if (session) {
await client.deleteSession(session.session_id);
logger.info(`Session deleted: ${session.session_id}`);
}
}
}
Copy
import logging
from pyagi import AGIClient
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
client = AGIClient(api_key="your_api_key")
def run_task_with_logging(task):
start_time = datetime.utcnow()
session = None
try:
session = client.session("agi-0")
logger.info(f"Session created: {session.session_id}")
session.send_message(task)
logger.info(f"Message sent to {session.session_id}")
result = session.wait_for_completion()
duration = (datetime.utcnow() - start_time).total_seconds()
logger.info(f"Task completed in {duration:.2f}s")
return result
except Exception as e:
duration = (datetime.utcnow() - start_time).total_seconds()
logger.error(f"Task failed after {duration:.2f}s: {e}")
raise
finally:
if session:
session.delete()
logger.info(f"Session deleted: {session.session_id}")
Copy
# Log session creation
SESSION=$(http POST https://api.agi.tech/v1/sessions \
Authorization:"Bearer $AGI_API_KEY" \
agent_name=agi-0 | jq -r '.session_id')
echo "$(date) - INFO - Session created: $SESSION"
# Log message sent
http POST https://api.agi.tech/v1/sessions/$SESSION/message \
Authorization:"Bearer $AGI_API_KEY" \
message="$TASK"
echo "$(date) - INFO - Message sent to $SESSION"
# Log completion
START=$(date +%s)
# ... polling logic ...
END=$(date +%s)
DURATION=$((END - START))
echo "$(date) - INFO - Task completed in ${DURATION}s"
# Log session deletion
http DELETE https://api.agi.tech/v1/sessions/$SESSION \
Authorization:"Bearer $AGI_API_KEY"
echo "$(date) - INFO - Session deleted: $SESSION"
Track Performance
Monitor task duration and success rates.- JavaScript
- Python
- HTTPie
Copy
function trackPerformance(taskFunc) {
return async function(...args) {
const startTime = Date.now();
let success = false;
try {
const result = await taskFunc(...args);
success = true;
return result;
} finally {
const duration = ((Date.now() - startTime) / 1000).toFixed(2);
logger.info(`Task ${success ? 'succeeded' : 'failed'} in ${duration}s`);
}
};
}
// Usage
const checkPrice = trackPerformance(async (product) => {
// ... task implementation ...
});
Copy
import time
def track_performance(task_func):
"""Decorator to track task performance"""
def wrapper(*args, **kwargs):
start_time = time.time()
success = False
try:
result = task_func(*args, **kwargs)
success = True
return result
finally:
duration = time.time() - start_time
logger.info(f"Task {'succeeded' if success else 'failed'} in {duration:.2f}s")
return wrapper
# Usage
@track_performance
def check_price(product):
# ... task implementation ...
pass
Copy
# Track performance with timestamps
START=$(date +%s)
# Run your API calls...
http POST https://api.agi.tech/v1/sessions/$SESSION_ID/message \
Authorization:"Bearer $AGI_API_KEY" \
message="$TASK"
# ... polling logic ...
END=$(date +%s)
DURATION=$((END - START))
echo "Task completed in ${DURATION}s"
Best Practices
Log Key Events
Log session creation, completion, and errors
Track Duration
Monitor task execution time
Log Errors
Always log errors with context
Use Structured Logs
Use JSON format for easier parsing