CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-chatgptpy

TLS-based ChatGPT API with auto token regeneration, conversation tracking, proxy support and more.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

authentication.mddocs/

Authentication Management

Token management utilities for handling OpenAI authentication, including automatic login flow, token validation, manual token operations, and session management.

Capabilities

Token Status Functions

Utilities for checking and retrieving stored authentication tokens.

def token_expired() -> bool:
    """
    Check if the stored access token has expired.
    
    Returns:
        bool: True if token is expired or missing, False if valid
        
    Note:
        Checks token stored in classes/auth.json file. Returns True if
        file doesn't exist, token is malformed, or expiry time has passed.
    """
def get_access_token() -> Tuple[str or None, str or None]:
    """
    Retrieve stored access token and expiry time.
    
    Returns:
        Tuple[str or None, str or None]: (access_token, expires_at) or (None, None) if not found
        
    Note:
        Reads from classes/auth.json file. Returns None values if file
        doesn't exist or is malformed.
    """

Usage Example

from pychatgpt import OpenAI

# Check token status
if OpenAI.token_expired():
    print("Token is expired or missing")
else:
    token, expiry = OpenAI.get_access_token()  
    print(f"Token: {token[:20]}...")
    print(f"Expires at: {expiry}")

Auth Class

Handles the complete OpenAI authentication flow including login, captcha solving, and token creation.

class Auth:
    """
    Manages OpenAI authentication through TLS-based login flow.
    
    Args:
        email_address (str): OpenAI account email address
        password (str): OpenAI account password  
        proxy (str, optional): Proxy URL for network requests
    """
    def __init__(
        self, 
        email_address: str, 
        password: str, 
        proxy: str = None
    ): ...

Token Creation

Perform the complete authentication flow to create a new access token.

def create_token(self):
    """
    Execute the full authentication flow to create and save an access token.
    
    This method handles the complex multi-step OpenAI login process including:
    - Initial login page request
    - CSRF token retrieval  
    - Auth0 authentication flow
    - State token management
    - Captcha handling (if required)
    - Access token extraction and storage
    
    Raises:
        PyChatGPTException: If email/password not provided
        Auth0Exception: If authentication steps fail
        IPAddressRateLimitException: If IP is rate limited
        
    Note:
        If captcha is detected, saves captcha.png and prompts user for input.
        Token is automatically saved to classes/auth.json on success.
    """

Usage Example

from pychatgpt import OpenAI

# Create authentication handler
auth = OpenAI.Auth(
    email_address="user@example.com",
    password="your-password"
)

# Optional: use with proxy
auth = OpenAI.Auth(
    email_address="user@example.com", 
    password="your-password",
    proxy="http://proxy.example.com:8080"
)

try:
    # Perform authentication flow
    auth.create_token()
    print("Authentication successful!")
    
    # Token is now available
    token, expiry = OpenAI.get_access_token()
    print(f"Token created: {token[:20]}...")
    
except OpenAI.PyChatGPTException as e:
    print(f"Authentication failed: {e.message}")

Manual Token Management

Save access tokens manually for advanced use cases.

@staticmethod
def save_access_token(access_token: str, expiry: int or None = None):
    """
    Manually save an access token with expiry time.
    
    Args:
        access_token (str): The access token to save
        expiry (int, optional): Token expiry timestamp. Defaults to 1 hour from now.
        
    Raises:
        Exception: If file operations fail
        
    Note:
        Saves token to classes/auth.json file. If expiry is not provided,
        sets expiry to current time + 3600 seconds (1 hour).
    """

Usage Example

import time
from pychatgpt import OpenAI

# Save a token manually (advanced usage)
OpenAI.Auth.save_access_token(
    access_token="your-token-here",
    expiry=int(time.time()) + 3600  # Expires in 1 hour
)

# Verify it was saved
if not OpenAI.token_expired():
    print("Token saved successfully")

Authentication Flow Details

The authentication process involves these steps:

  1. Initial Request: GET to https://chat.openai.com/auth/login
  2. CSRF Token: GET to https://chat.openai.com/api/auth/csrf
  3. Auth0 Signin: POST to signin endpoint with CSRF token
  4. Login Page: GET to Auth0 login page with state parameter
  5. Captcha Check: Parse page for captcha requirements
  6. Email Submit: POST email address with optional captcha solution
  7. Password Submit: POST password to complete login
  8. Token Extract: Extract access token from response
  9. Token Save: Store token and expiry to auth.json file

Captcha Handling

When a captcha is detected:

  1. SVG captcha is extracted and converted to PNG
  2. File saved as captcha.png in current directory
  3. User prompted to solve captcha via console input
  4. Solution submitted with login credentials

Proxy Support

All authentication requests support proxy configuration:

from pychatgpt import OpenAI

# String proxy
auth = OpenAI.Auth(
    email_address="user@example.com",
    password="password", 
    proxy="http://proxy.example.com:8080"
)

# Or as dictionary in Options when using Chat class
from pychatgpt import Chat, Options

options = Options()
options.proxies = {
    "http": "http://proxy.example.com:8080",
    "https": "https://secure-proxy.example.com:8443"
}

chat = Chat(email="user@example.com", password="password", options=options)

Error Handling

Authentication can raise several exception types:

from pychatgpt import OpenAI

try:
    auth = OpenAI.Auth("user@example.com", "password")
    auth.create_token()
    
except OpenAI.PyChatGPTException as e:
    print(f"General error: {e.message}")
    
except OpenAI.Auth0Exception as e:
    print(f"Authentication error: {e.message}")
    
except OpenAI.IPAddressRateLimitException as e:
    print(f"Rate limited: {e.message}")
    print("Try again in a few minutes or use a proxy")

Token Storage

Tokens are stored in classes/auth.json with this format:

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_at": 1683847200
}

The file is automatically created and managed by the authentication system.

Install with Tessl CLI

npx tessl i tessl/pypi-chatgptpy

docs

authentication.md

chat-interface.md

configuration.md

index.md

tile.json