Skip to content

Pure Claude CLI authentication module - no API keys required, works with Claude subscription

License

Notifications You must be signed in to change notification settings

milhy545/claude-cli-authentication

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Claude CLI Authentication Module

Python License PyPI

A production-ready Python module for Claude AI integration without API keys. Uses Claude CLI authentication to work seamlessly with Claude subscriptions.

🎯 Key Features

  • πŸ”‘ No API Keys Required - Uses claude auth login authentication
  • πŸ’³ 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

πŸš€ Quick Start

Installation

# 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 login

Basic Usage

from 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}")

With Session Management

# 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)

πŸ“š Complete Documentation

Configuration

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)

Error Handling

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

Advanced Features

# 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}")

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           Your Application          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚        ClaudeAuthManager            β”‚
β”‚         (Main Interface)            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Primary: Python SDK + CLI Auth    β”‚
β”‚  Fallback: Direct CLI Subprocess   β”‚
β”‚  Emergency: Error Recovery          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚        Claude CLI (~/.claude/)     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ”§ Core Components

  • AuthManager - Session and credential management
  • CLIInterface - Direct CLI subprocess wrapper
  • SDKInterface - Python SDK with CLI authentication (optional)
  • ClaudeAuthManager - Unified API with intelligent fallbacks

βš™οΈ Requirements

  • Python 3.8+
  • Claude CLI - Install with npm install -g @anthropic-ai/claude-code
  • Claude Authentication - Run claude auth login (one-time setup)

🚨 Troubleshooting

Common Issues

"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()

Debug Mode

import logging
logging.basicConfig(level=logging.DEBUG)

# Enable detailed logging
claude = ClaudeAuthManager()

πŸ“– Integration Examples

Flask/FastAPI Integration

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)}), 500

Telegram Bot Integration

import 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)

Jupyter Notebook Integration

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)

πŸ”’ Security & Privacy

  • 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

🀝 Contributing

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

πŸ“„ License

MIT License - see LICENSE for details.


Pure Claude Authentication - Simple, reliable, no API keys required! πŸ”

About

Pure Claude CLI authentication module - no API keys required, works with Claude subscription

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages