SPB Git

Repository Public

APIDocumentation.swift 9.2 KB 140 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Local Chat9// File             : Services/LocalAPIServer/Sources/APIDocumentation.swift10// Description      : Self-contained HTML documentation of the Local API (served11//                    at / and /docs), with curl examples for the actual port.12// Module           : Services13// Repository       : https://git.spboucher.ai/local-chat14// Created          : 2026-11-2015// Last Modified    : 2026-11-2016//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091enum APIDocumentation {92    static func html(port: UInt16, configuration: ServerConfiguration) -> String {93        let base = "http://127.0.0.1:\(port)"94        let auth = configuration.authenticationRequired95        let header = auth ? " \\\n  -H \"Authorization: Bearer $LOCAL_CHAT_KEY\"" : ""96        let rate = configuration.rateLimitPerMinute > 0 ? "\(configuration.rateLimitPerMinute) requests per minute per key (or per client address)" : "disabled"97        let origins = configuration.allowedOrigins.isEmpty ? "none (requests carrying a foreign <code>Origin</code> header are refused)" : configuration.allowedOrigins.map { "<code>\(escape($0))</code>" }.joined(separator: ", ")98        func endpoint(_ method: String, _ path: String, _ summary: String, _ example: String) -> String {99            "<section><h2><span class=\"m \(method.lowercased())\">\(method)</span> <code>\(path)</code></h2><p>\(summary)</p><pre>\(escape(example))</pre></section>"100        }101        return """102        <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">103        <title>Local Chat API</title><style>104        :root{color-scheme:light dark;--bg:#fafafa;--fg:#1c1c1e;--mut:#6e6e73;--card:#fff;--line:#e3e3e8;--acc:#4f46e5}105        @media (prefers-color-scheme:dark){:root{--bg:#141416;--fg:#f2f2f7;--mut:#9a9aa2;--card:#1d1d21;--line:#2e2e34;--acc:#8b85ff}}106        body{font:15px/1.55 -apple-system,BlinkMacSystemFont,"SF Pro Text",system-ui,sans-serif;background:var(--bg);color:var(--fg);margin:0}107        main{max-width:820px;margin:0 auto;padding:48px 24px 80px}h1{font-size:30px;letter-spacing:-.02em;margin:0 0 6px}108        h2{font-size:17px;margin:0 0 6px}p{margin:6px 0 12px}.lead{color:var(--mut);margin-bottom:28px}109        section,.box{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:18px 20px;margin:14px 0}110        pre{background:rgba(127,127,140,.12);border-radius:10px;padding:12px 14px;overflow:auto;font:12.5px/1.5 ui-monospace,"SF Mono",Menlo,monospace;margin:0}111        code{font:13px ui-monospace,"SF Mono",Menlo,monospace}.m{font:600 11px ui-monospace,monospace;padding:3px 7px;border-radius:6px;color:#fff;vertical-align:2px}112        .get{background:#1f9d55}.post{background:var(--acc)}dl{display:grid;grid-template-columns:max-content 1fr;gap:6px 18px;margin:0}dt{color:var(--mut)}dd{margin:0}113        </style></head><body><main>114        <h1>Local Chat API</h1>115        <p class="lead">OpenAI-compatible inference served by Local Chat on this Mac. Everything runs on this machine; nothing is sent elsewhere.</p>116        <div class="box"><dl>117        <dt>Base URL</dt><dd><code>\(base)/v1</code></dd>118        <dt>Network</dt><dd>\(configuration.exposeOnLAN ? "Reachable from your local network (explicitly enabled)" : "This Mac only (bound to 127.0.0.1)")</dd>119        <dt>Authentication</dt><dd>\(auth ? "Required — <code>Authorization: Bearer &lt;key&gt;</code>. Create keys in Local Chat → Settings → Local API." : "Not required on loopback (can be enabled in Local Chat → Settings → Local API)")</dd>120        <dt>Rate limit</dt><dd>\(rate)</dd>121        <dt>Browser origins</dt><dd>\(origins)</dd>122        </dl></div>123        \(endpoint("GET", "/v1/models", "Lists the models this node can serve. Each entry carries a <code>local_chat</code> object (backend, quantization, context length, capabilities).",124                   "curl \(base)/v1/models\(header)"))125        \(endpoint("POST", "/v1/chat/completions", "Chat completion. Supports <code>stream</code> (Server-Sent Events), <code>tools</code>, <code>stop</code>, <code>seed</code>, <code>temperature</code>, <code>top_p</code>, <code>top_k</code>, <code>max_tokens</code>, <code>stream_options.include_usage</code>, base64 <code>image_url</code> parts for vision models, and <code>reasoning_content</code> for thinking models. The final chunk carries measured timings in <code>local_chat</code>.",126                   "curl \(base)/v1/chat/completions\(header) \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"<id from /v1/models>\",\n    \"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}],\n    \"stream\": true\n  }'"))127        \(endpoint("POST", "/v1/embeddings", "Embeddings from an embedding model. <code>input</code> is a string or an array of strings.",128                   "curl \(base)/v1/embeddings\(header) \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"model\": \"<embedding model id>\", \"input\": [\"first text\", \"second text\"]}'"))129        \(endpoint("GET", "/health", "Liveness probe. Needs no key and returns no information about models or usage.", "curl \(base)/health"))130        <section><h2>Using an OpenAI SDK</h2><p>Point any OpenAI-compatible client at the base URL.</p><pre>\(escape("from openai import OpenAI\nclient = OpenAI(base_url=\"\(base)/v1\", api_key=\"\(auth ? "<your key>" : "not-needed")\")\nprint(client.chat.completions.create(model=\"<id>\", messages=[{\"role\": \"user\", \"content\": \"Hello\"}]).choices[0].message.content)"))</pre></section>131        <section><h2>Errors</h2><p>Errors use the OpenAI envelope <code>{"error": {"message", "type"}}</code>: 400 invalid request, 401 missing or invalid key, 403 origin not allowed, 404 unknown model or route, 413 body too large, 429 rate limited (with <code>Retry-After</code>), 503 model cannot be loaded.</p></section>132        </main></body></html>133        """134    }135136    static func escape(_ text: String) -> String {137        text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;").replacingOccurrences(of: ">", with: "&gt;")138    }139}140
Files main
Menu

Theme