Notion2API

repository·main·Indexed 42 days ago

https://github.com/galiais/notion2api

A Go-based bridge service that provides an OpenAI-compatible API for Notion AI. It features a WebUI for management, multi-account pooling, streaming responses, and local SQLite persistence. Supports various proxy modes including Resin sticky proxy for account isolation and is deployable via Docker Compose.

Tokens
9K
Snippets
24
Records
39
Agent score
47%

What's inside Notion2API

  1. Configure Proxy Modes and Resin Sticky Proxy

    main

    The proxy_mode setting determines how outbound requests are routed. Supported modes include:

    • off: No proxy used.
    • env: Reads from environment variables (prioritizing N2A_* prefixes).
    • http: Uses a fixed HTTP proxy.
    • https: Splits HTTP and HTTPS proxies separately.
    • socks5: Uses SOCKS5 or SOCKS5H proxy.
    • resin_forward: Enables Resin sticky proxy forwarding.

    Resin Sticky Proxy (Account Isolation)

    When resin_forward is enabled, you can isolate identities per account using accounts[].sticky_proxy_account. If not explicitly set, it falls back to a value derived from the email.

    Authentication Details for Resin:

    • Username format: <resin_platform>.<sticky_proxy_account>
    • Password: Use the token from the resin_url.
    • Header: Requests will include the X-Resin-Account header.
  2. Quickstart Notion2API

    main

    Notion2API is a Go-based bridge service that provides an OpenAI-compatible interface for Notion AI. It supports multi-account pools, streaming responses, and local SQLite persistence.

    Local Execution

    To run the service locally using a configuration file:

    go run ./cmd/notion2api --config ./config.example.json

    Local Build

    To build the binary:

    go build ./cmd/notion2api

    Docker Deployment

    1. Modify config.docker.json according to your environment.
    2. Start the service using Docker Compose:

    Standard deployment:

    docker compose up -d --build

    Production deployment:

    docker compose -f docker-compose.prod.yml up -d --build

    Note: Local development requires Go 1.25.0+.

    go run ./cmd/notion2api --config ./config.example.json
  3. How the Responses streaming works

    main

    The server provides a specialized streaming mechanism for the /v1/responses endpoint using a sequence of SSE events. This is more granular than the standard OpenAI chat completions stream.

    Event Lifecycle:

    • response.created: The response object is initialized.
    • response.in_progress: Indicates the model is currently generating.
    • response.output_item.added: An output item (like a message) is added to the response.
    • response.content_part.added: A new content part is being processed.
    • response.reasoning.delta: Incremental chunks of reasoning text.
    • response.output_text.delta: Incremental chunks of visible text.
    • response.reasoning.done: The reasoning phase has finished.
    • response.output_text.done: The visible text generation is complete.
    • response.output_item.done: The specific output item is finalized.
    • response.completed: The entire response process is finished.
  4. Configuration Reference

    main

    The following keys are the primary configuration options for Notion2API. Refer to config.example.json or config.docker.json for full schemas.

    KeyDescription
    api_keySecret key for the OpenAI-compatible interface
    admin.passwordPassword for the WebUI admin panel
    upstream_base_url / upstream_originUpstream service URLs
    proxy_modeProxying strategy (off, env, http, https, socks5, resin_forward)
    proxy_url / proxy_http_url / proxy_https_urlProxy connection strings
    resin_enabledEnable/disable Resin sticky proxy
    resin_urlResin proxy URL
    resin_platformResin platform identifier
    resin_modeResin proxy mode
    accounts[*].sticky_proxy_accountExplicit sticky account name for an account entry
    accountsList of account configurations
    active_accountThe currently selected account
    storage.sqlite_pathPath to the SQLite database file
  5. Understand the ServerState structure

    main

    The ServerState is the central authority for the application's runtime data. It manages:

    • Configuration: Config (AppConfig)
    • Session: Session (SessionInfo)
    • Models: ModelRegistry for available AI models.
    • Persistence: Store (SQLiteStore) for accounts and responses, and Conversations (ConversationStore) for chat history.
    • Concurrency: slots for managing per-account request limits.
    • Caches: Atomic pointers for high-performance access to static JSON payloads (health checks, model lists).
  6. How the Chat Completions streaming works

    main

    The server implements an OpenAI-compatible Server-Sent Events (SSE) stream for chat completions. When a request is made to /v1/chat/completions:

    1. Initialization: The server generates a completionID and prepares OpenAI-compatible SSE headers.
    2. Streaming: As the inference engine produces data, the server emits chunks containing content (visible text) and reasoning (internal model thought process).
    3. Reasoning Support: If request.StreamReasoningWarmup is enabled, a reasoning heartbeat (\u200b) is sent to initialize the reasoning stream.
    4. Error Handling: If the upstream inference fails, the server attempts to send any partially generated text before sending an error payload with type: "api_error" and code: "upstream_error".
    5. Completion: The stream concludes with a finish_reason: "stop" chunk and a [DONE] signal.
  7. Manage AI prompt behavior via PromptConfig

    main

    The PromptConfig interface allows fine-tuning of how the AI interacts with users and handles errors. You can define custom prefixes for different scenarios to guide the model's reasoning or retry logic.

    Available configuration keys:

    • profile: The default prompt profile to use.
    • custom_prefix: A string to prepend to prompts.
    • fallback_profiles: A list of profiles to use if the primary fails.
    • max_escalation_steps: Limit for how many times the system attempts to resolve an issue.
    • max_refusal_retries: Limit for retrying when the model refuses a prompt.
    • cognitive_reframing_prefix: Prefix used for cognitive reframing tasks.
    • toolbox_capability_expansion_prefix: Prefix for expanding tool capabilities.
    • coding_retry_prefixes: Array of prefixes used specifically for coding retries.
    • general_retry_prefixes: Array of prefixes for general retries.
    • direct_answer_retry_prefixes: Array of prefixes for retries when a direct answer is expected.
  8. Configure Notion2API via Docker Compose

    main

    You can deploy Notion2API using Docker Compose. The configuration is highly parameterized using environment variables, allowing you to customize the image name, container name, port mapping, volume mounts, and proxy settings without modifying the docker-compose.yml file directly.

    Port Mapping

    By default, the service listens on port 8787. You can change the host port using the N2A_PORT environment variable.

    Volume Mounts

    • Configuration: The application expects a configuration file at /app/config/config.json. You can map your local config file using N2A_CONFIG_FILE (defaults to ./config.docker.json). This is mounted as read-only (ro).
    • Data Directory: Persistent data is stored in /app/data. You can map a local directory using N2A_DATA_DIR (defaults to ./data).

    Proxy and Resin Settings

    The service supports various proxy modes and Resin sticky proxy configurations via environment variables such as N2A_PROXY_MODE, N2A_PROXY_URL, and N2A_RESIN_ENABLED.

    services:
      notion2api:
        image: ${N2A_IMAGE:-notion2api:latest}
        container_name: ${N2A_CONTAINER_NAME:-notion2api}
        ports:
          - "${N2A_PORT:-8787}:8787"
        volumes:
          - ${N2A_CONFIG_FILE:-./config.docker.json}:/app/config/config.json:ro
          - ${N2A_DATA_DIR:-./data}:/app/data
        environment:
          N2A_PROXY_MODE: ${N2A_PROXY_MODE:-}
          N2A_PROXY_URL: ${N2A_PROXY_URL:-}
          N2A_RESIN_ENABLED: ${N2A_RESIN_ENABLED:-}
          # ... other env vars
  9. Configure the Notion2API application settings

    main

    The AppConfigShape interface defines the core configuration for the Notion2API instance. This includes network settings, upstream proxy configurations, model management, and storage persistence.

    Key configuration groups include:

    • Network/Upstream: host, port, upstream_base_url, upstream_origin, and upstream_host_header.
    • Models: default_model, model_id, and model_aliases (a mapping of aliases to actual model IDs).
    • Storage: Configures SQLite usage and persistence for conversations, conversation_snapshots, responses, continuation_sessions, and sillytavern_bindings.
    • Admin: Security settings including password and token_ttl_hours.
    • Features: Toggles for web search, read-only mode, image generation, and CSV support.
    • Prompt: Customization of AI behavior via PromptConfig (profiles, prefixes, and retry logic).
    // Example of the AppConfigShape structure
    const config: AppConfigShape = {
      host: 'localhost',
      port: 3000,
      default_model: 'gpt-4',
      storage: {
        sqlite_path: './data.db',
        persist_conversations: true
      },
      features: {
        use_web_search: true,
        enable_generate_image: false
      }
    };
  10. Configure the backend base URL

    main

    The API client determines the target backend URL using the NEXT_PUBLIC_BACKEND_BASE_URL environment variable. Ensure this variable is set in your environment to point to the Notion2API service. The client automatically strips trailing slashes from this URL.

    NEXT_PUBLIC_BACKEND_BASE_URL=https://api.your-notion2api-instance.com
  11. Default API and WebUI Endpoints

    main

    Once the service is running, it exposes the following default endpoints:

    • OpenAI Compatible API: http://127.0.0.1:8787/v1/* (includes /v1/models, /v1/chat/completions, and /v1/responses)
    • Health Check: http://127.0.0.1:8787/healthz
    • WebUI Admin Panel: http://127.0.0.1:8787/admin
  12. Configure Proxy Environment Variables

    main

    When proxy_mode is set to env, the service follows a specific priority order for HTTPS and HTTP requests.

    HTTPS Request Priority

    1. N2A_PROXY_HTTPS_URL
    2. N2A_UPSTREAM_PROXY_HTTPS_URL
    3. N2A_PROXY_URL
    4. N2A_UPSTREAM_PROXY_URL
    5. HTTPS_PROXY / https_proxy
    6. ALL_PROXY / all_proxy

    HTTP Request Priority

    1. N2A_PROXY_HTTP_URL
    2. N2A_UPSTREAM_PROXY_HTTP_URL
    3. N2A_PROXY_URL
    4. N2A_UPSTREAM_PROXY_URL
    5. HTTP_PROXY / http_proxy
    6. ALL_PROXY / all_proxy

    Configuration Overrides

    You can also override configuration file fields directly using these environment variables:

    • N2A_PROXY_MODE
    • N2A_PROXY_URL
    • N2A_PROXY_HTTP_URL
    • N2A_PROXY_HTTPS_URL
    • N2A_RESIN_ENABLED
    • N2A_RESIN_URL
    • N2A_RESIN_PLATFORM
    • N2A_RESIN_MODE