/* SwiftLLM docs — full old-doc content ported from src-legacy/components/SwiftLLMDocs.tsx.
   Body is English-only per the legacy site's precedent; only the page chrome is translated. */

const GITHUB_URL = 'https://github.com/Elyeden0/swiftllm';

const SECTIONS = [
  { id: 'getting-started',  label: 'Getting Started' },
  { id: 'providers',        label: 'Providers' },
  { id: 'tool-calling',     label: 'Tool Calling' },
  { id: 'async-python',     label: 'Async Python' },
  { id: 'gateway-mode',     label: 'Gateway Mode' },
  { id: 'configuration',    label: 'Configuration' },
  { id: 'cost-tracking',    label: 'Cost Tracking' },
  { id: 'smart-routing',    label: 'Smart Routing' },
  { id: 'consensus',        label: 'Multi-Model Consensus' },
  { id: 'embeddings',       label: 'Embeddings' },
  { id: 'observability',    label: 'Observability' },
  { id: 'docker',           label: 'Docker' },
  { id: 'mcp-server',       label: 'MCP Server' },
  { id: 'language-bindings', label: 'Language Bindings' },
  { id: 'api-reference',    label: 'API Reference' },
];

const PROVIDERS = [
  { name: 'OpenAI',       models: 'gpt-4o, gpt-4.1, o3, o1-mini',                setup: 'llm.add_provider("openai", api_key="sk-...")' },
  { name: 'Anthropic',    models: 'claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5', setup: 'llm.add_provider("anthropic", api_key="sk-ant-...")' },
  { name: 'Google Gemini', models: 'gemini-2.0-flash, gemini-2.0-pro',             setup: 'llm.add_provider("gemini", api_key="AIza...")' },
  { name: 'Mistral',      models: 'mistral-large, codestral, pixtral',             setup: 'llm.add_provider("mistral", api_key="...")' },
  { name: 'Ollama',       models: 'Any local model (llama2, mistral, neural-chat...)', setup: 'llm.add_provider("ollama", base_url="http://localhost:11434")' },
  { name: 'Groq',         models: 'llama-3.3-70b, mixtral-8x7b (LPU inference)',   setup: 'llm.add_provider("groq", api_key="gsk_...")' },
  { name: 'Together AI',  models: 'Open-source models (Llama, Mistral, Code Llama)', setup: 'llm.add_provider("together", api_key="...")' },
  { name: 'AWS Bedrock',  models: 'Claude, Llama, Titan models',                   setup: 'llm.add_provider("bedrock")  # Uses AWS env vars' },
];

const ENV_VARS = [
  ['OPENAI_API_KEY',     'sk-...'],
  ['ANTHROPIC_API_KEY',  'sk-ant-...'],
  ['GEMINI_API_KEY',     'AIza...'],
  ['MISTRAL_API_KEY',    '...'],
  ['GROQ_API_KEY',       'gsk_...'],
  ['TOGETHER_API_KEY',   '...'],
  ['AWS_REGION',         'us-east-1'],
  ['OLLAMA_BASE_URL',    'http://localhost:11434'],
];

const MCP_TOOLS = [
  ['chat_completion',  'Send messages to any LLM provider'],
  ['list_models',      'List available models for all providers'],
  ['list_providers',   'List configured providers'],
  ['smart_route',      'Route requests using smart routing strategies'],
  ['consensus_query',  'Get consensus from multiple models'],
  ['get_stats',        'Get usage and cost statistics'],
  ['compare_models',   'Compare responses from multiple models'],
];

const LANGUAGES = [
  {
    name: 'Python',
    install: 'pip install swiftllm',
    code: `from swiftllm import SwiftLLM

llm = SwiftLLM()
llm.add_provider("openai", api_key="sk-...")
response = llm.completion("gpt-4o", messages)`,
  },
  {
    name: 'Node.js/TypeScript',
    install: 'npm install swiftllm',
    code: `import { SwiftLLM } from 'swiftllm';

const llm = new SwiftLLM();
llm.addProvider('openai', { apiKey: 'sk-...' });
const response = await llm.completion('gpt-4o', messages);`,
    frameworks: [
      { name: 'Express', code: `import { SwiftLLM } from 'swiftllm';
const express = require('express');
const app = express();
const llm = new SwiftLLM();

app.post('/chat', async (req, res) => {
  const response = await llm.completion('gpt-4o', req.body.messages);
  res.json(response);
});` },
      { name: 'Fastify', code: `import { SwiftLLM } from 'swiftllm';
import fastify from 'fastify';
const app = fastify();
const llm = new SwiftLLM();

app.post('/chat', async (req, res) => {
  const response = await llm.completion('gpt-4o', req.body.messages);
  return response;
});` },
      { name: 'Hono', code: `import { SwiftLLM } from 'swiftllm';
import { Hono } from 'hono';
const app = new Hono();
const llm = new SwiftLLM();

app.post('/chat', async (c) => {
  const body = await c.req.json();
  const response = await llm.completion('gpt-4o', body.messages);
  return c.json(response);
});` },
      { name: 'Next.js', code: `import { SwiftLLM } from 'swiftllm';

const llm = new SwiftLLM();

export async function POST(req: Request) {
  const body = await req.json();
  const response = await llm.completion('gpt-4o', body.messages);
  return Response.json(response);
}` },
      { name: 'Nuxt', code: `import { SwiftLLM } from 'swiftllm';

const llm = new SwiftLLM();

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const response = await llm.completion('gpt-4o', body.messages);
  return response;
});` },
      { name: 'SvelteKit', code: `import { SwiftLLM } from 'swiftllm';
import type { RequestHandler } from '@sveltejs/kit';

const llm = new SwiftLLM();

export const POST: RequestHandler = async ({ request }) => {
  const body = await request.json();
  const response = await llm.completion('gpt-4o', body.messages);
  return new Response(JSON.stringify(response));
};` },
      { name: 'Remix', code: `import { json } from '@remix-run/node';
import { SwiftLLM } from 'swiftllm';

const llm = new SwiftLLM();

export async function action({ request }: any) {
  const body = await request.json();
  const response = await llm.completion('gpt-4o', body.messages);
  return json(response);
}` },
      { name: 'Deno', code: `import { SwiftLLM } from 'npm:swiftllm';

const llm = new SwiftLLM();

Deno.serve(async (req) => {
  if (req.method === 'POST') {
    const body = await req.json();
    const response = await llm.completion('gpt-4o', body.messages);
    return new Response(JSON.stringify(response));
  }
});` },
      { name: 'Bun', code: `import { SwiftLLM } from 'swiftllm';

const llm = new SwiftLLM();

const server = Bun.serve({
  port: 3000,
  async fetch(req) {
    const body = await req.json();
    const response = await llm.completion('gpt-4o', body.messages);
    return new Response(JSON.stringify(response));
  },
});` },
      { name: 'Koa', code: `import { SwiftLLM } from 'swiftllm';
import Koa from 'koa';
const app = new Koa();
const llm = new SwiftLLM();

app.use(async (ctx) => {
  const body = await ctx.request.json();
  const response = await llm.completion('gpt-4o', body.messages);
  ctx.body = response;
});` },
      { name: 'NestJS', code: `import { SwiftLLM } from 'swiftllm';
import { Controller, Post, Body } from '@nestjs/common';

@Controller('chat')
export class ChatController {
  private llm = new SwiftLLM();

  @Post()
  async chat(@Body() body: any) {
    return await this.llm.completion('gpt-4o', body.messages);
  }
}` },
      { name: 'Elysia', code: `import { SwiftLLM } from 'swiftllm';
import { Elysia } from 'elysia';

const llm = new SwiftLLM();

const app = new Elysia().post('/chat', async (body) => {
  const response = await llm.completion('gpt-4o', body.messages);
  return response;
});` },
      { name: 'AdonisJS', code: `import { SwiftLLM } from 'swiftllm';
import { HttpContextContract } from '@adonisjs/core/build/standalone';

const llm = new SwiftLLM();

export default class ChatController {
  async chat({ request, response }: HttpContextContract) {
    const body = request.all();
    const result = await llm.completion('gpt-4o', body.messages);
    return response.json(result);
  }
}` },
      { name: 'tRPC', code: `import { SwiftLLM } from 'swiftllm';
import { initTRPC } from '@trpc/server';

const t = initTRPC.create();
const llm = new SwiftLLM();

export const router = t.router({
  chat: t.procedure.input(z.object({ messages: z.array(z.any()) })).query(async ({ input }) => {
    return await llm.completion('gpt-4o', input.messages);
  }),
});` },
    ],
  },
  { name: 'C',    install: 'gcc -lswiftllm program.c', code: `#include <swiftllm.h>

SwiftLLM *llm = swiftllm_new();
swiftllm_add_provider(llm, "openai", "sk-...");
CompletionResponse *response = swiftllm_completion(llm, "gpt-4o", messages);` },
  { name: 'C++',  install: 'g++ -lswiftllm program.cpp', code: `#include <swiftllm.hpp>

SwiftLLM llm;
llm.addProvider("openai", "sk-...");
auto response = llm.completion("gpt-4o", messages);` },
  { name: 'Go',   install: 'go get github.com/elyeden0/swiftllm-go', code: `package main

import "github.com/elyeden0/swiftllm-go"

llm := swiftllm.New()
llm.AddProvider("openai", "sk-...")
response, err := llm.Completion("gpt-4o", messages)` },
  { name: 'Java', install: 'gradle add swiftllm', code: `import com.elyeden0.swiftllm.SwiftLLM;

SwiftLLM llm = new SwiftLLM();
llm.addProvider("openai", "sk-...");
CompletionResponse response = llm.completion("gpt-4o", messages);` },
  { name: 'C#',   install: 'dotnet add package SwiftLLM', code: `using SwiftLLM;

var llm = new SwiftLLM();
llm.AddProvider("openai", "sk-...");
var response = await llm.Completion("gpt-4o", messages);` },
  { name: 'Ruby', install: 'gem install swiftllm', code: `require 'swiftllm'

llm = SwiftLLM.new
llm.add_provider('openai', api_key: 'sk-...')
response = llm.completion('gpt-4o', messages)` },
  { name: 'PHP',  install: 'composer require elyeden0/swiftllm', code: `use SwiftLLM\\SwiftLLM;

$llm = new SwiftLLM();
$llm->addProvider('openai', ['api_key' => 'sk-...']);
$response = $llm->completion('gpt-4o', $messages);` },
  { name: 'Elixir', install: 'mix add swiftllm', code: `alias SwiftLLM

llm = SwiftLLM.new()
SwiftLLM.add_provider(llm, :openai, "sk-...")
{:ok, response} = SwiftLLM.completion(llm, "gpt-4o", messages)` },
  { name: 'Swift', install: '// Add to Package.swift', code: `import SwiftLLM

let llm = SwiftLLM()
llm.addProvider("openai", apiKey: "sk-...")
let response = try await llm.completion("gpt-4o", messages)` },
  { name: 'Kotlin', install: '// Add to build.gradle.kts', code: `import com.elyeden0.swiftllm.SwiftLLM

val llm = SwiftLLM()
llm.addProvider("openai", "sk-...")
val response = llm.completion("gpt-4o", messages)` },
  { name: 'Zig', install: 'zig build', code: `const swiftllm = @cImport({
    @cInclude("swiftllm.h");
});

const llm = swiftllm.swiftllm_new();
swiftllm.swiftllm_add_provider(llm, "openai", "sk-...");` },
  { name: 'Rust', install: 'cargo add swiftllm', code: `use swiftllm::SwiftLLM;

let mut llm = SwiftLLM::new();
llm.add_provider("openai", "sk-...")?;
let response = llm.completion("gpt-4o", messages).await?;` },
  { name: 'Scala', install: '// Add to build.sbt', code: `import com.elyeden0.swiftllm.SwiftLLM

val llm = new SwiftLLM()
llm.addProvider("openai", "sk-...")
val response = llm.completion("gpt-4o", messages)` },
  { name: 'Haskell', install: 'cabal add swiftllm', code: `{-# LANGUAGE ForeignFunctionInterface #-}
import SwiftLLM

llm <- newSwiftLLM
addProvider llm "openai" "sk-..."
response <- completion llm "gpt-4o" messages` },
  { name: 'OCaml', install: 'opam install swiftllm', code: `open Swiftllm

let llm = create ()
let () = add_provider llm "openai" "sk-..."
let response = completion llm "gpt-4o" messages` },
  { name: 'Lua',  install: 'luarocks install swiftllm', code: `local swiftllm = require("swiftllm")

local llm = swiftllm.new()
llm:add_provider("openai", "sk-...")
local response = llm:completion("gpt-4o", messages)` },
  { name: 'Perl', install: 'cpanm SwiftLLM', code: `use SwiftLLM;

my $llm = SwiftLLM->new();
$llm->add_provider('openai', 'sk-...');
my $response = $llm->completion('gpt-4o', \\@messages);` },
  { name: 'D', install: 'dub add swiftllm', code: `extern(C) {
    void* swiftllm_new();
    void swiftllm_add_provider(void* llm, const char* name, const char* key);
}

auto llm = swiftllm_new();
swiftllm_add_provider(llm, "openai", "sk-...");` },
  { name: 'Nim', install: 'nimble install swiftllm', code: `import swiftllm

let llm = newSwiftLLM()
llm.addProvider("openai", "sk-...")
let response = llm.completion("gpt-4o", messages)` },
  { name: 'Dart', install: 'dart pub add swiftllm', code: `import 'package:swiftllm/swiftllm.dart';

final llm = SwiftLLM();
llm.addProvider('openai', 'sk-...');
final response = await llm.completion('gpt-4o', messages);` },
  { name: 'Erlang', install: 'rebar3 add swiftllm', code: `-module(llm).

llm_init() ->
    Llm = swiftllm_nif:new(),
    swiftllm_nif:add_provider(Llm, "openai", "sk-..."),
    Llm.` },
];

/* ----- Building blocks ----- */

function CopyBtn({ text }) {
  const t = window.t;
  const [copied, setCopied] = React.useState(false);
  const onCopy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1400);
    } catch (_) {}
  };
  return (
    <button type="button" className="code-copy" onClick={onCopy} aria-label={t('swiftllm.copy')}>
      {copied ? (
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8l4 4 6-8" /></svg>
      ) : (
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="5" width="9" height="9" rx="1.5"/><path d="M3 11V3h8"/></svg>
      )}
      <span>{copied ? t('swiftllm.copied') : t('swiftllm.copy')}</span>
    </button>
  );
}

function CodeBlock({ code, lang }) {
  return (
    <div className="code-block">
      <div className="code-block-head">
        <span className="code-block-lang">{lang || 'python'}</span>
        <CopyBtn text={code} />
      </div>
      <pre className="code-block-body"><code>{code}</code></pre>
    </div>
  );
}

function BulletList({ items }) {
  return (
    <ul className="sw-bullets">
      {items.map((it, i) => (
        <li key={i}>
          <span className="sw-bullet-dot">•</span>
          <span>{it}</span>
        </li>
      ))}
    </ul>
  );
}

function DocSection({ id, title, children }) {
  return (
    <section className="sw-doc-section reveal" id={id}>
      <h2 className="sw-doc-title">
        <span className="sw-doc-bracket">&lt;</span>
        <span className="sw-doc-title-text">{title}</span>
        <span className="sw-doc-bracket">{'/>'}</span>
      </h2>
      <div className="sw-doc-body">{children}</div>
    </section>
  );
}

function SubHeading({ children }) {
  return <h3 className="sw-sub">{children}</h3>;
}

function Para({ children }) {
  return <p className="sw-para">{children}</p>;
}

function LanguageCard({ lang, isOpen, onToggle, expandedFrameworks, toggleFramework }) {
  return (
    <div className={`sw-lang-card ${isOpen ? 'open' : ''}`}>
      <button type="button" className="sw-lang-header" onClick={onToggle}>
        <span className="sw-lang-name">{lang.name}</span>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" className="sw-lang-chev"><path d="M3 5L7 9L11 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      {isOpen && (
        <div className="sw-lang-body">
          <div className="sw-lang-subheading">Install</div>
          <CodeBlock code={lang.install} lang="bash" />

          {lang.frameworks && (
            <>
              <div className="sw-lang-subheading">Frameworks</div>
              <div className="sw-frameworks">
                {lang.frameworks.map(fw => {
                  const key = `${lang.name}-${fw.name}`;
                  const fwOpen = expandedFrameworks.includes(key);
                  return (
                    <div key={key} className={`sw-fw-card ${fwOpen ? 'open' : ''}`}>
                      <button type="button" className="sw-fw-header" onClick={() => toggleFramework(key)}>
                        <span>{fw.name}</span>
                        <svg width="12" height="12" viewBox="0 0 14 14" fill="none" className="sw-fw-chev"><path d="M3 5L7 9L11 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                      </button>
                      {fwOpen && (
                        <div className="sw-fw-body">
                          <CodeBlock code={fw.code} lang="typescript" />
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </>
          )}

          <div className="sw-lang-subheading">Basic Usage</div>
          <CodeBlock code={lang.code} lang="python" />
        </div>
      )}
    </div>
  );
}

function Sidebar({ activeId }) {
  const t = window.t;
  const onClick = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };
  return (
    <aside className="sw-sidebar">
      <div className="sw-sidebar-inner">
        <h3 className="sw-sidebar-heading">{t('swiftllm.sidebarHeading')}</h3>
        <nav className="sw-sidebar-nav">
          {SECTIONS.map(s => (
            <a
              key={s.id}
              href={`#${s.id}`}
              className={`sw-sidebar-item ${activeId === s.id ? 'active' : ''}`}
              onClick={(e) => onClick(e, s.id)}
            >
              <svg width="10" height="10" viewBox="0 0 14 14" fill="none"><path d="M5 3L9 7L5 11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
              <span>{s.label}</span>
            </a>
          ))}
        </nav>
      </div>
    </aside>
  );
}

function SwiftLLM() {
  const t = window.t;
  const [activeId, setActiveId] = React.useState(SECTIONS[0].id);
  const [expandedLanguages, setExpandedLanguages] = React.useState([]);
  const [expandedFrameworks, setExpandedFrameworks] = React.useState([]);

  const toggleLanguage = (name) => {
    setExpandedLanguages(prev => prev.includes(name) ? prev.filter(n => n !== name) : [...prev, name]);
  };
  const toggleFramework = (key) => {
    setExpandedFrameworks(prev => prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]);
  };

  React.useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) setActiveId(entry.target.id);
      });
    }, { rootMargin: '-20% 0px -60% 0px', threshold: 0 });

    SECTIONS.forEach(s => {
      const el = document.getElementById(s.id);
      if (el) io.observe(el);
    });

    return () => io.disconnect();
  }, []);

  return (
    <section className="sw-full-page" id="swiftllm">
      <div className="container">

        <a href="#/docs" className="sw-back">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M9 12L3 7L9 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          <span>{t('swiftllm.back')}</span>
        </a>

        <div className="sw-full-hero reveal">
          <h1 className="sw-full-title">
            <span className="sw-bracket">&lt;</span>
            <span className="sw-title-text">{t('swiftllm.title')}</span>
            <span className="sw-bracket">{'/>'}</span>
          </h1>
          <p className="sw-full-desc">{t('swiftllm.description')}</p>
          <div className="sw-free-pill">
            <span className="sw-free-text">{t('swiftllm.freeBadge')}</span>
            <span className="sw-free-sep">|</span>
            <span className="sw-free-mit">{t('swiftllm.mitBadge')}</span>
            <span className="sw-free-sep">|</span>
            <a href={GITHUB_URL} target="_blank" rel="noopener noreferrer" className="sw-free-gh">{t('swiftllm.githubLink')}</a>
          </div>
        </div>

        <div className="sw-doc-grid">
          <Sidebar activeId={activeId} />

          <div className="sw-doc-content">

            <DocSection id="getting-started" title="Getting Started">
              <div className="sw-free-callout">
                <h4 className="sw-free-callout-title">SwiftLLM is completely free</h4>
                <p className="sw-free-callout-body">
                  SwiftLLM is open-source under the MIT license. No API fees, no usage limits, no hidden costs.
                  You only pay for the LLM provider API calls you make (OpenAI, Anthropic, etc.). SwiftLLM itself is free forever.
                </p>
              </div>

              <SubHeading>Prerequisites</SubHeading>
              <Para>
                SwiftLLM requires <strong>Python 3.10+</strong> (up to 3.14). No Rust toolchain needed for Python users — the package ships pre-built native wheels for Linux, macOS, and Windows.
              </Para>

              <SubHeading>Step 1 — Install SwiftLLM</SubHeading>
              <CodeBlock code={`pip install swiftllm-py`} lang="bash" />

              <SubHeading>Step 2 — Get an API key from any provider</SubHeading>
              <Para>
                You need an API key from at least one LLM provider. SwiftLLM supports 8 providers — pick whichever you prefer.
                Many offer free tiers (Groq, Google Gemini, Ollama is fully local and free).
              </Para>

              <SubHeading>Step 3 — Set your API key</SubHeading>
              <Para>Export your key as an environment variable, or pass it directly in code:</Para>
              <CodeBlock lang="bash" code={`# Option A: environment variable (recommended)
export OPENAI_API_KEY="sk-..."

# Option B: .env file
echo 'OPENAI_API_KEY=sk-...' >> .env`} />

              <SubHeading>Step 4 — Run your first completion</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import completion

# One-liner — SwiftLLM auto-detects the provider from the model name
response = completion(
    "gpt-4o-mini",
    "What is machine learning?",
    api_key="sk-..."   # or omit if OPENAI_API_KEY is set
)
print(response.text)`} />

              <SubHeading>Step 5 (optional) — Use the full client for multi-provider setups</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import SwiftLLM

llm = SwiftLLM()
llm.add_provider("openai", api_key="sk-...")
llm.add_provider("anthropic", api_key="sk-ant-...")
llm.add_provider("groq", api_key="gsk-...")

# Switch between providers by model name
response = llm.completion("gpt-4o", [{"role": "user", "content": "Hello!"}])
response = llm.completion("claude-sonnet-4-6", [{"role": "user", "content": "Hello!"}])
response = llm.completion("llama-3.3-70b", [{"role": "user", "content": "Hello!"}])

print(response.text)`} />

              <SubHeading>For Rust Users</SubHeading>
              <CodeBlock code={`cargo add swiftllm`} lang="toml" />
            </DocSection>

            <DocSection id="providers" title="Providers">
              <Para>SwiftLLM supports 8 major LLM providers. Configure them with your API keys:</Para>
              <div className="sw-provider-cards">
                {PROVIDERS.map(p => (
                  <div className="sw-provider-card" key={p.name}>
                    <h4 className="sw-provider-name">{p.name}</h4>
                    <p className="sw-provider-models">
                      <span className="sw-provider-k">Models:</span> {p.models}
                    </p>
                    <CodeBlock code={p.setup} lang="python" />
                  </div>
                ))}
              </div>

              <SubHeading>Using Different Providers</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import SwiftLLM

llm = SwiftLLM()
llm.add_provider("openai", api_key="sk-...")
llm.add_provider("anthropic", api_key="sk-ant-...")
llm.add_provider("groq", api_key="gsk_...")

# Use OpenAI
response = llm.completion("gpt-4o", messages)

# Switch to Anthropic
response = llm.completion("claude-opus-4-6", messages)

# Use Groq for fast inference
response = llm.completion("llama-3.3-70b", messages)`} />
            </DocSection>

            <DocSection id="tool-calling" title="Tool Calling">
              <Para>Pass tools/functions to enable the LLM to call functions:</Para>
              <CodeBlock lang="python" code={`from swiftllm import SwiftLLM

llm = SwiftLLM()
llm.add_provider("openai", api_key="sk-...")

# Define tools
tools = [
  {
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Get weather for a location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "City name"
          },
          "unit": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"],
            "description": "Temperature unit"
          }
        },
        "required": ["location"]
      }
    }
  }
]

messages = [
  {"role": "user", "content": "What's the weather in Paris?"}
]

response = llm.completion(
    "gpt-4o",
    messages,
    tools=tools
)

# Check if model wants to call a tool
if response.tool_calls:
    for call in response.tool_calls:
        print(f"Call {call.name} with {call.arguments}")
else:
    print(response.text)`} />

              <SubHeading>Tool Calling with Multiple Tools</SubHeading>
              <CodeBlock lang="python" code={`tools = [
  {
    "type": "function",
    "function": {
      "name": "search",
      "description": "Search the web",
      "parameters": {
        "type": "object",
        "properties": {
          "query": {"type": "string"}
        },
        "required": ["query"]
      }
    }
  },
  {
    "type": "function",
    "function": {
      "name": "calculator",
      "description": "Perform math calculations",
      "parameters": {
        "type": "object",
        "properties": {
          "expression": {"type": "string"}
        },
        "required": ["expression"]
      }
    }
  }
]

response = llm.completion("gpt-4o", messages, tools=tools)`} />
            </DocSection>

            <DocSection id="async-python" title="Async Python">
              <Para>Use async_completion for non-blocking LLM calls in async contexts:</Para>
              <CodeBlock lang="python" code={`import asyncio
from swiftllm import async_completion

async def main():
    # One-liner async
    response = await async_completion(
        "gpt-4o-mini",
        "Hello!",
        api_key="sk-..."
    )
    print(response.text)

asyncio.run(main())`} />

              <SubHeading>FastAPI Example</SubHeading>
              <CodeBlock lang="python" code={`from fastapi import FastAPI
from swiftllm import async_completion

app = FastAPI()

@app.post("/chat")
async def chat(message: str):
    response = await async_completion(
        "gpt-4o",
        message,
        api_key="sk-..."
    )
    return {"reply": response.text}

@app.post("/batch")
async def batch_queries(queries: list[str]):
    # Run multiple requests concurrently
    tasks = [
        async_completion("gpt-4o", q, api_key="sk-...")
        for q in queries
    ]
    responses = await asyncio.gather(*tasks)
    return {"results": [r.text for r in responses]}`} />

              <SubHeading>With Client</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import SwiftLLM

llm = SwiftLLM()
llm.add_provider("openai", api_key="sk-...")

async def stream_completion():
    response = await llm.async_completion(
        "gpt-4o",
        [{"role": "user", "content": "Write a poem"}]
    )
    print(response.text)`} />
            </DocSection>

            <DocSection id="gateway-mode" title="Gateway Mode">
              <Para>Run SwiftLLM as an HTTP server with caching, rate limiting, and failover:</Para>

              <SubHeading>Start Gateway Server</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import SwiftLLM

llm = SwiftLLM(
    cache=True,
    rate_limit=100,  # 100 requests per minute
    failover=True
)
llm.add_provider("openai", api_key="sk-...")
llm.add_provider("anthropic", api_key="sk-ant-...")

# Start HTTP server
llm.serve(port=8080)`} />

              <SubHeading>Make Requests</SubHeading>
              <CodeBlock lang="bash" code={`# Using curl
curl -X POST http://localhost:8080/v1/chat/completions \\
  -H "Content-Type: application/json" \\
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "Hello!"}
    ]
  }'

# Using Python
import httpx

async with httpx.AsyncClient() as client:
    response = await client.post(
        "http://localhost:8080/v1/chat/completions",
        json={
            "model": "gpt-4o",
            "messages": [{"role": "user", "content": "Hello!"}]
        }
    )
    print(response.json())`} />

              <SubHeading>Features</SubHeading>
              <BulletList items={[
                <><strong>Request Caching:</strong> Cache repeated requests to reduce API costs</>,
                <><strong>Rate Limiting:</strong> Built-in rate limiting per API key</>,
                <><strong>Failover:</strong> Automatic failover to alternative providers</>,
                <><strong>OpenAI Compatible:</strong> Drop-in replacement for OpenAI API</>,
              ]} />
            </DocSection>

            <DocSection id="configuration" title="Configuration">
              <Para>Configure SwiftLLM using environment variables:</Para>

              <div className="sw-env-box">
                {ENV_VARS.map(([key, val]) => (
                  <div className="sw-env-row" key={key}>
                    <span className="sw-env-key">{key}</span>
                    <span className="sw-env-eq">=</span>
                    <span className="sw-env-val">{val}</span>
                  </div>
                ))}
              </div>

              <SubHeading>Load from .env File</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import SwiftLLM
from dotenv import load_dotenv
import os

load_dotenv()

llm = SwiftLLM()
llm.add_provider("openai", api_key=os.getenv("OPENAI_API_KEY"))
llm.add_provider("anthropic", api_key=os.getenv("ANTHROPIC_API_KEY"))`} />
            </DocSection>

            <DocSection id="cost-tracking" title="Cost Tracking & Dashboard">
              <Para>Track API costs and view analytics through the SwiftLLM dashboard:</Para>

              <CodeBlock lang="python" code={`from swiftllm import SwiftLLM

llm = SwiftLLM(track_costs=True)
llm.add_provider("openai", api_key="sk-...")
llm.add_provider("anthropic", api_key="sk-ant-...")

# Make requests...
response = llm.completion("gpt-4o", messages)
response = llm.completion("claude-opus-4-6", messages)

# View costs
costs = llm.get_cost_report()
print(f"Total cost: \${costs['total']}")
print(f"OpenAI: \${costs['openai']}")
print(f"Anthropic: \${costs['anthropic']}")

# Start dashboard at http://localhost:9090
llm.start_dashboard(port=9090)`} />

              <SubHeading>Dashboard Features</SubHeading>
              <BulletList items={[
                'Real-time cost tracking across all providers',
                'Request logs and latency metrics',
                'Model usage statistics',
                'Error tracking and failover events',
                'Export reports (CSV, JSON)',
              ]} />
            </DocSection>

            <DocSection id="smart-routing" title="Smart Routing">
              <Para>Automatically route requests to the best provider based on your strategy:</Para>

              <SubHeading>Routing Strategies</SubHeading>
              <BulletList items={[
                <><strong>cost_optimized:</strong> Choose the cheapest provider that meets quality requirements</>,
                <><strong>latency_optimized:</strong> Choose the fastest provider</>,
                <><strong>balanced:</strong> Balance between cost and latency</>,
              ]} />

              <SubHeading>Quality Tiers</SubHeading>
              <Para>low, medium, high</Para>

              <CodeBlock lang="json" code={`{
  "model": "gpt-4o",
  "messages": [{"role": "user", "content": "Hello"}],
  "routing": {
    "strategy": "cost_optimized",
    "quality": "high"
  }
}`} />
            </DocSection>

            <DocSection id="consensus" title="Multi-Model Consensus">
              <Para>Get responses from multiple models and combine them using consensus strategies:</Para>

              <SubHeading>Consensus Strategies</SubHeading>
              <BulletList items={[
                <><strong>best_of:</strong> A judge model picks the best response</>,
                <><strong>majority:</strong> Choose the response that appears most frequently</>,
                <><strong>merge:</strong> Synthesize all responses into one comprehensive answer</>,
              ]} />

              <CodeBlock lang="json" code={`{
  "model": "gpt-4o",
  "messages": [{"role": "user", "content": "Explain quantum computing"}],
  "consensus": {
    "models": ["gpt-4o", "claude-sonnet-4-6", "gemini-2.0-flash"],
    "strategy": "best_of",
    "judge": "claude-sonnet-4-6"
  }
}`} />
            </DocSection>

            <DocSection id="embeddings" title="Embeddings">
              <Para>Generate embeddings for text using various models:</Para>

              <SubHeading>POST /v1/embeddings</SubHeading>
              <CodeBlock lang="json" code={`{
  "model": "text-embedding-3-large",
  "input": "The quick brown fox jumps over the lazy dog"
}`} />

              <SubHeading>Response</SubHeading>
              <CodeBlock lang="json" code={`{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.0023064255, -0.009327292, ...]
    }
  ],
  "model": "text-embedding-3-large",
  "usage": {
    "prompt_tokens": 8,
    "total_tokens": 8
  }
}`} />
            </DocSection>

            <DocSection id="observability" title="Observability">
              <Para>Built-in OpenTelemetry support with GenAI semantic conventions for production monitoring:</Para>

              <SubHeading>Span Attributes</SubHeading>
              <BulletList items={[
                <><strong>gen_ai.system:</strong> The LLM provider (openai, anthropic, gemini, etc.)</>,
                <><strong>gen_ai.request.model:</strong> The model name used</>,
                <><strong>gen_ai.usage.input_tokens:</strong> Input token count</>,
                <><strong>gen_ai.usage.output_tokens:</strong> Output token count</>,
                <><strong>gen_ai.usage.cost:</strong> Total cost in USD</>,
              ]} />

              <SubHeading>Configuration</SubHeading>
              <CodeBlock lang="bash" code={`export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4317"
export OTEL_SERVICE_NAME="swiftllm"
export OTEL_SDK_DISABLED="false"`} />
            </DocSection>

            <DocSection id="docker" title="Docker">
              <Para>Run SwiftLLM as a containerized service:</Para>

              <SubHeading>Docker Run</SubHeading>
              <CodeBlock lang="bash" code={`docker run -p 8080:8080 \\
  -e OPENAI_API_KEY=sk-... \\
  -e ANTHROPIC_API_KEY=sk-ant-... \\
  elyeden0/swiftllm:latest`} />

              <SubHeading>Docker Compose</SubHeading>
              <CodeBlock lang="yaml" code={`version: '3.8'

services:
  swiftllm:
    image: elyeden0/swiftllm:latest
    ports:
      - "8080:8080"
    environment:
      - OPENAI_API_KEY=sk-...
      - ANTHROPIC_API_KEY=sk-ant-...
      - GEMINI_API_KEY=AIza...
      - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel:4317
      - OTEL_SERVICE_NAME=swiftllm
    depends_on:
      - otel

  otel:
    image: otel/opentelemetry-collector:latest
    ports:
      - "4317:4317"`} />
            </DocSection>

            <DocSection id="mcp-server" title="MCP Server">
              <Para>SwiftLLM exposes 7 tools via the Model Context Protocol (MCP) for Claude Desktop integration:</Para>

              <SubHeading>Run MCP Server</SubHeading>
              <CodeBlock lang="bash" code={`./swiftllm-mcp`} />

              <SubHeading>Available Tools</SubHeading>
              <BulletList items={MCP_TOOLS.map(([name, desc]) => (
                <><strong>{name}:</strong> {desc}</>
              ))} />

              <SubHeading>Claude Desktop Configuration</SubHeading>
              <CodeBlock lang="json" code={`{
  "mcpServers": {
    "swiftllm": {
      "command": "/usr/local/bin/swiftllm-mcp",
      "env": {
        "OPENAI_API_KEY": "sk-...",
        "ANTHROPIC_API_KEY": "sk-ant-...",
        "GEMINI_API_KEY": "AIza..."
      }
    }
  }
}`} />
            </DocSection>

            <DocSection id="language-bindings" title="Language Bindings">
              <Para>SwiftLLM is available across 22 programming languages. Click each language to see install and usage instructions:</Para>
              <div className="sw-languages">
                {LANGUAGES.map(lang => (
                  <LanguageCard
                    key={lang.name}
                    lang={lang}
                    isOpen={expandedLanguages.includes(lang.name)}
                    onToggle={() => toggleLanguage(lang.name)}
                    expandedFrameworks={expandedFrameworks}
                    toggleFramework={toggleFramework}
                  />
                ))}
              </div>
            </DocSection>

            <DocSection id="api-reference" title="API Reference">
              <SubHeading>SwiftLLM Class</SubHeading>
              <CodeBlock lang="python" code={`class SwiftLLM:
  def __init__(
    self,
    cache: bool = False,
    rate_limit: int = None,
    failover: bool = False,
    track_costs: bool = False,
    timeout: int = 30
  )

  def add_provider(
    self,
    name: str,
    api_key: str = None,
    base_url: str = None,
    **kwargs
  ) -> None

  def completion(
    self,
    model: str,
    messages: list[dict],
    temperature: float = 0.7,
    max_tokens: int = None,
    tools: list[dict] = None,
    tool_choice: str = None,
    **kwargs
  ) -> CompletionResponse

  async def async_completion(
    self,
    model: str,
    messages: list[dict],
    **kwargs
  ) -> CompletionResponse

  def serve(
    self,
    port: int = 8080,
    host: str = "0.0.0.0"
  ) -> None

  def get_cost_report(self) -> dict

  def start_dashboard(self, port: int = 9090) -> None`} />

              <SubHeading>completion() Function</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import completion

response = completion(
    model: str,           # Model name
    prompt: str,          # User prompt
    api_key: str = None,  # Optional API key
    temperature: float = 0.7,
    max_tokens: int = None,
    system: str = None,
    **kwargs
) -> CompletionResponse`} />

              <SubHeading>Response Object</SubHeading>
              <CodeBlock lang="python" code={`class CompletionResponse:
  text: str                    # Generated text
  model: str                   # Model used
  usage: TokenUsage           # Token counts
  tool_calls: list[ToolCall]  # Function calls (if any)
  finish_reason: str          # "stop", "length", "tool_calls"

class TokenUsage:
  input_tokens: int
  output_tokens: int
  total_tokens: int

class ToolCall:
  name: str           # Function name
  arguments: dict     # Function arguments
  call_id: str        # Unique call ID`} />

              <SubHeading>Example — Complete Response</SubHeading>
              <CodeBlock lang="python" code={`from swiftllm import completion

response = completion(
    "gpt-4o",
    "What's 2+2?",
    api_key="sk-..."
)

print(response.text)                    # "4"
print(response.model)                   # "gpt-4o"
print(response.usage.total_tokens)      # 15
print(response.finish_reason)           # "stop"`} />
            </DocSection>

          </div>
        </div>
      </div>
    </section>
  );
}

window.SwiftLLM = SwiftLLM;
