A production-ready Python module for Claude AI integration without API keys. Uses Claude CLI authentication to work seamlessly with Claude subscriptions.
- π No API Keys Required - Uses
claude auth loginauthentication - π³ Subscription Compatible - Works with Claude subscription instead of API access
- π Triple Fallback System - SDK β CLI β Graceful error handling
- πΎ Session Management - Persistent conversations and context
- β‘ Production Ready - Comprehensive error handling and logging
- ποΈ Simple Interface - Easy integration into any Python project
# Install the module
pip install claude-cli-auth
# Install Claude CLI (required)
npm install -g @anthropic-ai/claude-code
# Authenticate with Claude (one-time setup)
claude auth loginfrom claude_cli_auth import ClaudeAuthManager
from pathlib import Path
# Initialize the manager
claude = ClaudeAuthManager()
# Simple query
response = await claude.query(
"Explain this code briefly",
working_directory=Path(".")
)
print(response.content)
print(f"Cost: ${response.cost:.4f}")# Start a conversation
response = await claude.query(
"Create a Python function to calculate fibonacci numbers",
session_id="my-coding-session"
)
# Continue the conversation
response = await claude.query(
"Now add error handling and docstring to that function",
session_id="my-coding-session",
continue_session=True
)
print(response.content)from claude_cli_auth import AuthConfig, ClaudeAuthManager
# Custom configuration
config = AuthConfig(
timeout_seconds=60, # Query timeout
session_timeout_hours=24, # Session expiration
use_sdk=True, # Prefer SDK over CLI
enable_streaming=True, # Enable streaming responses
)
claude = ClaudeAuthManager(config=config)from claude_cli_auth import (
ClaudeAuthError,
ClaudeTimeoutError,
ClaudeSessionError
)
try:
response = await claude.query("Test query")
print(response.content)
except ClaudeAuthError as e:
print(f"Authentication issue: {e}")
# Run: claude auth login
except ClaudeTimeoutError as e:
print(f"Query timed out: {e}")
# Retry with longer timeout
except ClaudeSessionError as e:
print(f"Session problem: {e}")
# Create new session# Streaming responses
async def on_stream_update(update):
print(f"[{update.type}] {update.content}")
response = await claude.query(
"Write a complex Python script",
stream_callback=on_stream_update
)
# File context
response = await claude.query(
"Review this code and suggest improvements",
files=["app.py", "models.py"],
working_directory=Path("./src")
)
# Session management
sessions = claude.list_sessions()
session_info = claude.get_session("my-session")
if session_info:
print(f"Total cost: ${session_info.total_cost:.4f}")
print(f"Messages: {session_info.total_turns}")βββββββββββββββββββββββββββββββββββββββ
β Your Application β
βββββββββββββββββββββββββββββββββββββββ€
β ClaudeAuthManager β
β (Main Interface) β
βββββββββββββββββββββββββββββββββββββββ€
β Primary: Python SDK + CLI Auth β
β Fallback: Direct CLI Subprocess β
β Emergency: Error Recovery β
βββββββββββββββββββββββββββββββββββββββ€
β Claude CLI (~/.claude/) β
βββββββββββββββββββββββββββββββββββββββ
AuthManager- Session and credential managementCLIInterface- Direct CLI subprocess wrapperSDKInterface- Python SDK with CLI authentication (optional)ClaudeAuthManager- Unified API with intelligent fallbacks
- Python 3.8+
- Claude CLI - Install with
npm install -g @anthropic-ai/claude-code - Claude Authentication - Run
claude auth login(one-time setup)
"Claude CLI not authenticated"
claude auth login"Claude CLI not found"
npm install -g @anthropic-ai/claude-code"Session expired"
# Sessions auto-expire after 24 hours
await claude.cleanup_sessions()import logging
logging.basicConfig(level=logging.DEBUG)
# Enable detailed logging
claude = ClaudeAuthManager()from flask import Flask, request, jsonify
from claude_cli_auth import ClaudeAuthManager
app = Flask(__name__)
claude = ClaudeAuthManager()
@app.route('/ask', methods=['POST'])
async def ask_claude():
data = request.json
try:
response = await claude.query(
prompt=data['question'],
session_id=data.get('session_id')
)
return jsonify({
'response': response.content,
'session_id': response.session_id,
'cost': response.cost
})
except Exception as e:
return jsonify({'error': str(e)}), 500import asyncio
from telegram import Update
from telegram.ext import Application, MessageHandler, filters
from claude_cli_auth import ClaudeAuthManager
claude = ClaudeAuthManager()
async def handle_message(update: Update, context):
user_id = update.effective_user.id
response = await claude.query(
prompt=update.message.text,
session_id=f"telegram_{user_id}"
)
await update.message.reply_text(response.content)from claude_cli_auth import ClaudeAuthManager
import asyncio
# Initialize in notebook
claude = ClaudeAuthManager()
# Use in any cell
async def ask_claude(question):
response = await claude.query(question)
return response.content
# Example usage
result = await ask_claude("Explain machine learning in simple terms")
print(result)- No API Keys Stored - Uses secure Claude CLI authentication
- Local Session Storage - Sessions stored in
~/.claude/directory - No Data Sent to Third Parties - Direct communication with Claude
- Audit Logging - Comprehensive operation tracking available
This module is designed to be a stable, focused authentication layer. Contributions welcome for:
- Bug fixes and reliability improvements
- Additional authentication methods
- Enhanced error handling
- Performance optimizations
MIT License - see LICENSE for details.
Pure Claude Authentication - Simple, reliable, no API keys required! π