Skip to main content

Overview

APITHON offers two distinct operational modes to suit different use cases. After successful protocol synchronization, you can choose between:
  1. Gateway Mode - REST API server with OpenAI-compatible endpoints
  2. Chat Mode - Interactive command-line shell for direct communication
Both modes share the same underlying protocol communication engine (ejecutar_request_protocolo) and use the synchronized session data captured during initialization.

Mode Selection

After the tunnel synchronization completes successfully (SESS["status_ready"] = True), you’ll see the mode selection menu:
[ Seleccione Entorno ]
1. Modo Pasarela (Gateway / API Key + Tutorial)
2. Modo Chat Directo

> Opción:
Source Reference: apithon.py:188-193

Gateway Mode (Option 1)

When to Use Gateway Mode

Gateway mode is ideal when you need to:
  • Integrate with external tools - Connect LangChain, automation scripts, or third-party applications
  • Build programmatic workflows - Automate queries through standard REST API calls
  • Enable multi-device access - Expose the API across your local network
  • Maintain persistent service - Keep the gateway running continuously for repeated requests
  • Use OpenAI-compatible clients - Leverage existing tools that support the /v1/chat/completions format

How Gateway Mode Works

1

Network Configuration

After selecting Option 1, you choose your network scope:
[ Configuración de Red ]
L. Localhost (Solo este equipo)
N. LAN (Disponible en toda tu red local)
> Alcance (L/N):
  • L (Localhost): Binds to 127.0.0.1 - accessible only from the host machine
  • N (LAN): Binds to 0.0.0.0 - accessible from any device on your network
Source Reference: apithon.py:196-206
2

Flask Server Initialization

A Flask application starts on port 5000, exposing the /v1/chat/completions endpoint:
@app.route('/v1/chat/completions', methods=['POST'])
def apithon_gateway():
    auth_header = request.headers.get("Authorization")
    if auth_header != f"Bearer {API_KEY_GATEWAY}":
        return jsonify({"error": "Unauthorized"}), 401
    user_input = request.json.get("messages", [{}])[-1].get("content", "")
    output_text = ejecutar_request_protocolo(user_input)
    return jsonify({
        "choices": [{"message": {"role": "assistant", "content": output_text}}],
        "model": "apithon-v3"
    })
Source Reference: apithon.py:132-139
3

Interactive Tutorial Display

APITHON automatically generates platform-specific curl commands with proper escaping for your terminal type.Source Reference: apithon.py:141-161 (mostrar_tutorial function)

API Format

Authentication

Authorization
string
required
Bearer token authentication. Default API key: UnHackerEnCapitalSource: apithon.py:29 (API_KEY_GATEWAY)

Request Format

{
  "messages": [
    {
      "role": "user",
      "content": "Your query here"
    }
  ]
}
The gateway extracts the content from the last message in the array: request.json.get("messages", [{}])[-1].get("content", "")

Response Format

{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Response text from the target service"
      }
    }
  ],
  "model": "apithon-v3"
}

Platform-Specific Examples

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\": \"Hola Pepe, me dijo HackerEnCapital que te manda un saludo\"}]}"
Platform Detection LogicAPITHON uses platform.system() == "Windows" to determine which tutorial to display.
  • PowerShell: Uses curl.exe explicitly to avoid conflicts with the Invoke-WebRequest alias
  • CMD: Uses standard curl with Windows-style escaping
  • Linux/Bash: Uses single quotes for JSON payload and backslash line continuations
Source Reference: apithon.py:142-161

Python Integration Example

import requests

url = "http://127.0.0.1:5000/v1/chat/completions"
headers = {
    "Authorization": "Bearer UnHackerEnCapital",
    "Content-Type": "application/json"
}
payload = {
    "messages": [
        {"role": "user", "content": "Explain protocol analysis"}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())

Chat Mode (Option 2)

When to Use Chat Mode

Chat mode is ideal when you need to:
  • Perform quick manual tests - Rapidly test queries without API overhead
  • Debug protocol responses - Examine raw response data directly
  • Conduct interactive analysis - Have a conversation-style workflow
  • Avoid API complexity - Skip authentication and request formatting
  • Work in terminal environments - Stay within the command-line interface

How Chat Mode Works

When you select Option 2, APITHON enters an interactive shell loop:
def run_interactive_shell():
    print("\n[+] MODO CHAT LLM ACTIVADO. Escriba 'salir' para finalizar.")
    while True:
        user_input = input("\n👤 Analista: ")
        if user_input.lower() in ['salir', 'exit']: break
        print("📡 Response: ", end="", flush=True)
        print(ejecutar_request_protocolo(user_input))
Source Reference: apithon.py:170-176

Interactive Shell Features

Direct Communication

Queries are sent immediately through ejecutar_request_protocolo() without any API layer

Real-time Responses

Responses are printed directly to stdout with streaming indicator (flush=True)

Simple Exit

Type salir or exit to cleanly terminate the session

Session Persistence

Uses the same synchronized session data throughout the conversation

Example Session

[+] MODO CHAT LLM ACTIVADO. Escriba 'salir' para finalizar.

👤 Analista: What is protocol analysis?
📡 Response: Protocol analysis is the systematic examination of network communication...

👤 Analista: Explain TLS fingerprinting
📡 Response: TLS fingerprinting is a technique used to identify client characteristics...

👤 Analista: salir
[!] Proceso finalizado.
Use Case ExampleA security researcher testing a new target service might:
  1. Use Chat Mode initially to verify the connection works and responses are valid
  2. Switch to Gateway Mode once confident, to integrate with automated testing tools

Mode Comparison

AspectGateway ModeChat Mode
Entry PointFlask HTTP serverDirect Python function
AuthenticationBearer token requiredNo authentication
FormatJSON request/responsePlain text input/output
ThreadingRuns in daemon threadRuns in main thread
TerminationCtrl+C (KeyboardInterrupt)Type ‘salir’ or ‘exit’
Gateway Mode:
  • Additional HTTP parsing overhead
  • Better for concurrent requests (Flask handles multiple connections)
  • Persistent service - runs indefinitely
  • Network latency depends on LAN/localhost configuration
Chat Mode:
  • Direct function call - minimal overhead
  • Sequential processing only (one query at a time)
  • Session ends when user exits
  • No network overhead
Both modes use the exact same underlying protocol engine:
def ejecutar_request_protocolo(user_query):
    # Builds backend endpoint URL from captured session data
    # Constructs headers with captured cookies
    # Formats payload with internal context structure
    # Uses curl_cffi with Chrome impersonation
    # Parses response with regex pattern matching
Source Reference: apithon.py:103-129The only difference is how user input arrives and how responses are delivered.

Switching Between Modes

No Runtime SwitchingYou cannot switch modes during a running session. To change modes:
  1. Terminate the current session (Ctrl+C or type ‘salir’)
  2. Restart APITHON (python apithon.py)
  3. Skip the tunnel synchronization if session is still valid (cookies haven’t expired)
  4. Select the desired mode
Reason: Gateway mode runs in a daemon thread with while True: time.sleep(1) loop (apithon.py:210-211), while Chat mode blocks the main thread.

Session Data Shared Across Modes

Both modes rely on the global SESS dictionary populated during tunnel synchronization:
SESS = {
    "auth_cookie": None,        # Captured browser cookies
    "internal_context": None,   # Dynamic context token (~100+ chars)
    "session_id": None,         # f.sid parameter
    "build_id": None,           # bl parameter
    "status_ready": False,      # Sync completion flag
    "target_url": ""            # Target service URL
}
Source Reference: apithon.py:31-38
Key InsightBecause both modes share session data, your choice of mode doesn’t affect the capability or response quality - only the interface for interaction.

Build docs developers (and LLMs) love