Skip to main content

Overview

This guide covers common issues you may encounter when installing, configuring, or running APITHON, along with their solutions. Issues are organized by category for easy navigation.
Before You StartMost issues can be diagnosed by checking:
  1. The terminal output for error messages
  2. The state of SESS["status_ready"] (should be True before mode selection)
  3. Your network configuration and firewall rules
  4. Browser automation completion (manual validation if needed)

Installation Issues

Playwright Installation Fails

Symptoms:
Error: Failed to download Chromium
Causes:
  • Network connectivity issues
  • Insufficient disk space
  • Proxy/firewall blocking downloads
  • Missing system dependencies
Solutions:
1

Verify pip installation succeeded

pip show playwright
# Should show version info
2

Install with environment variable

# Set custom browser download location
export PLAYWRIGHT_BROWSERS_PATH=$HOME/playwright-browsers
playwright install chromium
3

Install system dependencies (Linux)

# Ubuntu/Debian
sudo apt-get install libgbm1 libgtk-3-0 libnotify4 libnss3 \
     libxss1 libasound2 libxtst6 xauth xvfb

# Then retry
playwright install chromium
4

Check disk space

df -h $HOME
# Chromium requires ~300MB
Cause: Playwright not installed or wrong Python environmentSolution:
# Verify which Python you're using
which python
python --version

# Install in the correct environment
pip install playwright

# If using virtual environment
python -m venv venv
source venv/bin/activate  # Linux/Mac
.\venv\Scripts\activate   # Windows
pip install playwright
playwright install chromium
Symptoms:
ModuleNotFoundError: No module named 'curl_cffi'
Solution:
pip install curl_cffi

# If that fails, try upgrading pip first
pip install --upgrade pip
pip install curl_cffi
Note: curl_cffi is essential for Chrome impersonation (impersonate="chrome120" at apithon.py:123)
Symptoms:
ModuleNotFoundError: No module named 'flask'
Solution:
pip install flask

# Or install all dependencies at once
pip install flask playwright curl_cffi

Browser Automation Issues

Headless Mode Problems

Symptoms:
[*] Estableciendo túnel en: https://app.example.com
[*] Iniciando validación automatizada...
[Hangs here indefinitely]
Cause: Playwright can’t launch browser in headless modeSolution:The code already uses headless=False (apithon.py:63):
browser = await p.chromium.launch(headless=False)
If still hanging:
  1. Check system dependencies (see Playwright installation section)
  2. Verify display server (Linux)
    echo $DISPLAY
    # Should show something like :0 or :1
    
    # If empty, you're in a headless environment
    # Use Xvfb (virtual framebuffer)
    sudo apt-get install xvfb
    xvfb-run python apithon.py
    
  3. Try with slow_mo (debugging)
    # Edit apithon.py:63
    browser = await p.chromium.launch(headless=False, slow_mo=100)
    
Symptoms:
[!] Advertencia: No se pudo automatizar el envío. Hágalo manualmente.
Cause: Input field selector not found within 15 seconds (apithon.py:89)Why this happens:
  • Target site has a different UI structure
  • Page loaded slowly
  • Captcha or additional verification required
Solution:This is not a critical error. The code already handles it gracefully:
try:
    input_selector = "div[contenteditable='true'], textarea, input"
    await page.wait_for_selector(input_selector, timeout=15000)
    print("[+] Interfaz detectada. Enviando validación ('.')")
    await page.fill(input_selector, ".")
    await page.keyboard.press("Enter")
except Exception:
    print("[!] Advertencia: No se pudo automatizar el envío. Hágalo manualmente.")
Source Reference: apithon.py:88-94Action required:
  1. Wait for the browser window to fully load
  2. Manually type a message (anything, even ”.”) and press Enter
  3. The protocol sniffer will capture the request
  4. Once captured, the message ”[+] PROTOCOLO CAPTURADO” will appear
Cause: Script progressed past the synchronization phase prematurelyCheck:
# The script waits here until protocol is captured
while not SESS["status_ready"]:
    await asyncio.sleep(0.5)
Source Reference: apithon.py:96-97Debug: Add logging before line 96:
print(f"[DEBUG] Status: {SESS['status_ready']}")
print(f"[DEBUG] Context: {SESS['internal_context']}")
print(f"[DEBUG] Session ID: {SESS['session_id']}")
If status_ready is True but you didn’t send a message, the protocol sniffer pattern might have false-positive matched. Review the regex patterns at apithon.py:72-79.
Symptoms:
  • Browser opens successfully
  • You manually send a message
  • Terminal never shows ”[+] PROTOCOLO CAPTURADO”
  • Hangs at while not SESS["status_ready"]
Cause: The protocol sniffer isn’t detecting StreamGenerate requestsDiagnosis:Add debug logging to the sniffer (apithon.py:67):
async def protocol_sniffer(request):
    print(f"[DEBUG] Request: {request.url}")  # Add this line
    if "StreamGenerate" in request.url:
        # ...
Common reasons:
  1. Wrong target URL: The service doesn’t use the expected protocol
  2. Changed API endpoint: Service updated their backend structure
  3. Request method mismatch: Service uses GET instead of POST
Solution:
  1. Open browser DevTools (F12) manually on the target site
  2. Go to Network tab
  3. Send a message
  4. Look for the actual API endpoint being called
  5. Update the pattern in apithon.py:68:
    if "YourActualEndpoint" in request.url:
    
Symptoms:
  • Protocol appears captured
  • Later API requests fail with 401 Unauthorized
  • SESS["auth_cookie"] is empty or incomplete
Diagnosis:
# Add after line 81 in apithon.py
print(f"[DEBUG] Captured cookies: {SESS['auth_cookie']}")
Possible causes:
  1. Cookies set after protocol capture: Login happened after the request was sniffed
  2. HttpOnly cookies: Some cookies can’t be read by JavaScript/Playwright
  3. Domain mismatch: Cookies are set for a different domain
Solution:
  • Ensure you’re logged in before sending the first message
  • If the site requires 2FA, complete it before triggering APITHON
  • Try capturing cookies at a later stage (after the first successful response)

API Request Errors

401 Unauthorized

When accessing the gateway itself:Symptoms:
curl http://127.0.0.1:5000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{"messages": [{"role": "user", "content": "test"}]}'

{"error": "Unauthorized"}
Cause: Missing or incorrect Authorization headerSolution:
# Add the Authorization header with correct API key
curl http://127.0.0.1:5000/v1/chat/completions \
  -H 'Authorization: Bearer UnHackerEnCapital' \
  -H 'Content-Type: application/json' \
  -d '{"messages": [{"role": "user", "content": "test"}]}'
Source Reference: apithon.py:134-136
auth_header = request.headers.get("Authorization")
if auth_header != f"Bearer {API_KEY_GATEWAY}":
    return jsonify({"error": "Unauthorized"}), 401
When the underlying target service rejects the request:Symptoms:
  • Gateway accepts your request (authentication passes)
  • But response is: "Error en el túnel: 401 Unauthorized"
Cause: Captured session expired or cookies invalidSolutions:
1

Verify session data

Add debug output after line 81:
print(f"[DEBUG] Session ID: {SESS['session_id']}")
print(f"[DEBUG] Build ID: {SESS['build_id']}")
print(f"[DEBUG] Cookie length: {len(SESS['auth_cookie'])}")
2

Re-synchronize the tunnel

  1. Stop APITHON (Ctrl+C)
  2. Run python apithon.py again
  3. Go through the authentication flow on the target site
  4. Ensure you’re fully logged in before sending the test message
3

Check cookie expiration

Sessions expire after a certain time. If you’ve been running APITHON for hours:
  • Restart and re-authenticate
  • The captured cookies have likely expired

Empty or Invalid Responses

Symptoms:
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "Aviso: Flujo de datos vacío."
    }
  }],
  "model": "apithon-v3"
}
Cause: The regex pattern didn’t match any response textSource Reference: apithon.py:124-127
patterns = re.findall(r'rc_[a-z0-9]+.*?\[\\"(.*?)\\"\]', r.text)
if patterns:
    return patterns[-1].replace('\\\\n', '\n').replace('\\n', '\n').replace('\\"', '"')
return "Aviso: Flujo de datos vacío."
Diagnosis:
  1. Add debug logging to see the raw response:
    print(f"[DEBUG] Raw response: {r.text[:500]}")
    print(f"[DEBUG] Status code: {r.status_code}")
    
  2. Check if the response format changed
  3. Inspect the actual response structure from the target service
Solutions:
  • Update regex pattern: The service might have changed response format
  • Check for errors in response: Look for error messages in r.text
  • Verify request payload: The inner_structure format might be incorrect for this service
Symptoms:
TypeError: 'NoneType' object is not subscriptable
Cause: One of the session variables is NoneDiagnosis:
# Add at the start of ejecutar_request_protocolo (line 103)
print(f"[DEBUG] Session ready: {SESS['status_ready']}")
print(f"[DEBUG] Build ID: {SESS['build_id']}")
print(f"[DEBUG] Session ID: {SESS['session_id']}")
print(f"[DEBUG] Context: {SESS['internal_context'][:50] if SESS['internal_context'] else None}")
Solution: If any of these are None, the protocol wasn’t captured correctly:
  1. Restart APITHON
  2. Ensure you send a message in the browser that triggers a StreamGenerate request
  3. Wait for the ”[+] PROTOCOLO CAPTURADO” message before proceeding
Symptoms:
Error en el túnel: Connection refused
Error en el túnel: Read timed out
Causes:
  1. Target service is down
  2. Network connectivity issues
  3. Firewall blocking outbound connections
  4. VPN/proxy interference
Solutions:
# Test connectivity to target service
curl -I https://app.targetservice.com

# Check DNS resolution
nslookup app.targetservice.com

# Test with different impersonation
# Edit apithon.py:123
r = requests.post(backend_endpoint, headers=headers, data=payload, 
                  impersonate="chrome110")  # Try different version

Platform-Specific Issues

Windows

Symptoms:
Invoke-WebRequest: Cannot bind parameter 'Headers'
Cause: PowerShell aliases curl to Invoke-WebRequest, which has different syntaxSolution: Use curl.exe explicitly (as shown in the APITHON tutorial):
curl.exe http://127.0.0.1:5000/v1/chat/completions `
  -H "Content-Type: application/json" `
  -H "Authorization: Bearer UnHackerEnCapital" `
  -d "{\"messages\": [{\"role\": \"user\", \"content\": \"test\"}]}"
Note: APITHON’s tutorial already handles this (apithon.py:149-151)
Symptoms:
JSON parse error: Unexpected character
Cause: Windows CMD has tricky quote escaping rulesSolution: Copy the exact command from APITHON’s tutorial, which already handles Windows escaping:
curl http://127.0.0.1:5000/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer UnHackerEnCapital" -d "{\"messages\": [{\"role\": \"user\", \"content\": \"Test message \"}]}"
Source Reference: apithon.py:153-154
Cause: Using Linux command on WindowsExpected behavior: APITHON already handles this with platform detection:
def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')
Source Reference: apithon.py:40-41If you still see this error, your Python environment is misdetecting the OS. This is cosmetic and won’t affect functionality.

Linux

Symptoms:
PermissionError: [Errno 13] Permission denied
Cause: Ports below 1024 require root (but APITHON uses 5000, which shouldn’t need root)Likely cause: SELinux or AppArmor policySolution:
# Check SELinux status
getenforce

# If enforcing, allow binding to port 5000
sudo semanage port -a -t http_port_t -p tcp 5000

# Or run with different port (edit apithon.py:167)
app.run(host=host, port=8080, debug=False, use_reloader=False)
Symptoms:
Error: Could not connect to display :0
Cause: Running on a server without a display (headless environment)Solution:
# Install and use Xvfb (virtual framebuffer)
sudo apt-get install xvfb
xvfb-run -a python apithon.py

# Or use a headless browser (requires code modification)
# Edit apithon.py:63
browser = await p.chromium.launch(headless=True)
If using headless=True, some sites may detect automation and block requests. The captcha/verification might also not be completable.

macOS

Symptoms:
Protocol error (Browser.getVersion): Browser closed
Cause: macOS permissions/security blocking ChromiumSolution:
  1. Allow in System Preferences:
    • System Preferences → Security & Privacy
    • Look for message about blocked Chromium
    • Click “Open Anyway”
  2. Grant accessibility permissions:
    • System Preferences → Security & Privacy → Privacy → Accessibility
    • Add Terminal or your Python IDE to the list
  3. Disable Gatekeeper temporarily (not recommended):
    sudo spctl --master-disable
    # Run APITHON
    sudo spctl --master-enable  # Re-enable after
    

Connection and Network Errors

Symptoms:
curl: (7) Failed to connect to 127.0.0.1 port 5000: Connection refused
Diagnosis:
  1. Check if Flask is running:
    netstat -tuln | grep 5000
    # Should show: tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN
    
  2. Verify you selected Gateway Mode:
    • Did you choose Option 1 (Gateway) or Option 2 (Chat)?
    • Gateway mode prints: “[MANTENIENDO PASARELA… Ctrl+C para cerrar]”
    • Chat mode shows: ”[+] MODO CHAT LLM ACTIVADO”
Solution:
  • If in Chat mode, restart and select Option 1
  • If gateway appears to be running but port isn’t listening, check for error messages in the terminal
Symptoms:
OSError: [Errno 98] Address already in use
Cause: Another process is using port 5000Solution:
# Find the process
# Linux/macOS
sudo lsof -i :5000
# Example output: python 12345 user ...

# Kill it
kill 12345

# Or on Windows
netstat -ano | findstr :5000
# Note the PID, then:
taskkill /PID <pid> /F

# Alternatively, change APITHON's port
# Edit apithon.py:167
app.run(host=host, port=8080, debug=False, use_reloader=False)
Comprehensive checklist:
1

Verify LAN mode is active

When you started the gateway, did you select N (LAN)?Check the tutorial output - it should show your LAN IP (e.g., 192.168.1.45), not 127.0.0.1.
2

Confirm binding to 0.0.0.0

netstat -tuln | grep 5000
# Should show: tcp 0 0 0.0.0.0:5000 0.0.0.0:* LISTEN
# NOT: tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN
3

Test from host machine first

# Use the LAN IP, not 127.0.0.1
curl http://192.168.1.45:5000/v1/chat/completions \
  -H 'Authorization: Bearer UnHackerEnCapital' \
  -H 'Content-Type: application/json' \
  -d '{"messages": [{"role": "user", "content": "test"}]}'
If this fails on the host, it’s a firewall issue. If this succeeds, but fails from other devices, it’s a network routing issue.
4

Check firewall rules

See the Network Configuration guide for platform-specific firewall setup.
5

Verify network connectivity

# From the client device, ping the host
ping 192.168.1.45

# If ping fails, you have a network routing problem
# Check if both devices are on the same subnet

Protocol and Session Issues

Symptoms:
  • SESS["internal_context"] is None
  • Protocol appears captured but requests fail
Cause: Regex pattern didn’t match the context tokenSource Reference: apithon.py:72-73
ctx_match = re.search(r'(![a-zA-Z0-9_\-]{100,})', decoded)
Diagnosis:
  1. Add debug logging to protocol_sniffer:
    async def protocol_sniffer(request):
        if "StreamGenerate" in request.url:
            post_data = request.post_data
            if post_data:
                decoded = urllib.parse.unquote(post_data)
                print(f"[DEBUG] Decoded POST data: {decoded[:500]}")  # Add this
                # ... rest of function
    
  2. Look for the context token pattern in the output
  3. Adjust the regex if the format changed
Symptoms:
  • SESS["build_id"] or SESS["session_id"] is None
  • Requests fail with malformed URLs
Cause: URL parameters changed or pattern doesn’t matchSource Reference: apithon.py:73-79
sid_match = re.search(r'f.sid=([^&]+)', request.url)
bl_match = re.search(r'bl=([^&]+)', request.url)
Diagnosis:
# Add to protocol_sniffer
if "StreamGenerate" in request.url:
    print(f"[DEBUG] Full URL: {request.url}")  # Add this
Check if the URL structure changed (e.g., different parameter names).
Symptoms:
  • Works initially
  • After some time (minutes/hours), all requests return 401 or empty responses
Cause: Authentication cookies expiredSolution:
  1. Short-term: Restart APITHON and re-authenticate
  2. Long-term: Implement cookie refresh logic
    # Add to ejecutar_request_protocolo (after line 128)
    if "Unauthorized" in r.text or r.status_code == 401:
        return "Session expired. Please restart APITHON and re-authenticate."
    

Performance and Stability

Symptoms:
  • Requests take 10+ seconds to complete
  • Gateway becomes unresponsive
Causes:
  1. Target service is slow
  2. Network latency
  3. curl_cffi overhead
  4. Flask debug mode (already disabled in APITHON)
Diagnosis:
# Add timing to ejecutar_request_protocolo
import time
start_time = time.time()
r = requests.post(backend_endpoint, headers=headers, data=payload, impersonate="chrome120")
print(f"[DEBUG] Request took {time.time() - start_time:.2f} seconds")
Solutions:
  • Use Chat mode for faster direct responses (no HTTP overhead)
  • Check network connectivity between host and target service
  • Consider implementing request timeout:
    r = requests.post(backend_endpoint, headers=headers, data=payload, 
                      impersonate="chrome120", timeout=30)
    
Symptoms:
  • APITHON consumes increasing memory
  • System becomes sluggish after running for hours
Cause: Flask development server not designed for long-running production useSolution:
# Use a production WSGI server
pip install gunicorn

# Create wsgi.py file:
# from apithon import app
# if __name__ == "__main__":
#     app.run()

# Run with gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 apithon:app
Using gunicorn requires restructuring the code to separate Flask initialization from main().
Symptoms:
  • Multiple simultaneous requests cause delays
  • Some requests timeout
Cause: Flask development server handles requests sequentiallySource Reference: apithon.py:167 - No threading enabled by defaultSolutions:
  1. Enable Flask threading:
    # Edit line 167
    app.run(host=host, port=5000, debug=False, use_reloader=False, threaded=True)
    
  2. Use production server:
    gunicorn -w 4 -b 0.0.0.0:5000 apithon:app
    # 4 workers = 4 concurrent requests
    

Debug Mode and Logging

Enable Comprehensive Debugging

1

Add session state logging

After line 38 in apithon.py, add:
def log_session_state():
    print("\n[DEBUG SESSION STATE]")
    print(f"  Status Ready: {SESS['status_ready']}")
    print(f"  Target URL: {SESS['target_url']}")
    print(f"  Build ID: {SESS['build_id']}")
    print(f"  Session ID: {SESS['session_id']}")
    print(f"  Context: {SESS['internal_context'][:50] if SESS['internal_context'] else None}...")
    print(f"  Cookie length: {len(SESS['auth_cookie']) if SESS['auth_cookie'] else 0}")
    print("\n")
2

Add request/response logging

In ejecutar_request_protocolo (after line 102), add:
def ejecutar_request_protocolo(user_query):
    print(f"\n[DEBUG] User query: {user_query}")
    # ... existing code ...
    
    print(f"[DEBUG] Request URL: {backend_endpoint}")
    print(f"[DEBUG] Payload: {payload}")
    
    try:
        r = requests.post(backend_endpoint, headers=headers, data=payload, impersonate="chrome120")
        print(f"[DEBUG] Status code: {r.status_code}")
        print(f"[DEBUG] Response length: {len(r.text)}")
        print(f"[DEBUG] Response preview: {r.text[:200]}")
        # ... rest of function
3

Enable Flask logging

# Add at top of file
import logging
logging.basicConfig(level=logging.DEBUG)

# Or keep Flask's default logging
# It already logs all requests to stdout
4

Call logging functions

# After successful sync (line 186)
if SESS["status_ready"]:
    log_session_state()  # Add this
    while True:
        # ... mode selection

Getting Help

Check Logs

Review all terminal output for error messages and stack traces

Verify Dependencies

pip list | grep -E "flask|playwright|curl_cffi"

Test Connectivity

Verify you can access the target service manually in a browser

Simplify Configuration

Start with Localhost mode and Chat mode to isolate issues
Still Having Issues?If you’ve tried all troubleshooting steps:
  1. Document your error:
    • Exact error message
    • Platform (OS, Python version)
    • Steps to reproduce
    • Terminal output (sanitize any sensitive data)
  2. Verify source code:
    • Check if you’ve modified apithon.py
    • Compare against the original version
    • Look for syntax errors or indentation issues
  3. Test with minimal setup:
    • Fresh Python virtual environment
    • Clean install of dependencies
    • Default configuration (no modifications)
Common Fixes Checklist
  • All dependencies installed (flask, playwright, curl_cffi)
  • Chromium browser installed (playwright install chromium)
  • Target URL is accessible in a regular browser
  • You’re logged into the target service before running APITHON
  • Firewall allows connections on port 5000 (LAN mode)
  • API key matches in both client and server (UnHackerEnCapital)
  • Session was successfully synchronized (saw ”[+] PROTOCOLO CAPTURADO”)
  • Using correct network configuration (L for local, N for LAN)

Build docs developers (and LLMs) love