Your First Komilion API Call in 60 Seconds

Your First Komilion API Call in 60 Seconds

By Hossein Shahrokni | March 2026

If you just signed up for Komilion and are staring at a blank dashboard: here’s exactly what to do. This takes 60 seconds.

What you need

  • Your Komilion API key (starts with ck_ — visible in your dashboard)
  • Python 3.7+ or Node.js 16+, OR curl

That’s it. No new SDK. Komilion is OpenAI-compatible — if you’ve used the OpenAI API before, the interface is identical.

Option 1: Python (60 seconds)

Install the OpenAI SDK if you haven’t already:

pip install openai

Then run this:

from openai import OpenAI

client = OpenAI(
    base_url="https://www.komilion.com/api/v1",
    api_key="ck_your_key"  # paste your actual key here
)

response = client.chat.completions.create(
    model="neo-mode/balanced",
    messages=[{"role": "user", "content": "What is the fastest way to find a duplicate in a Python list?"}]
)

print(response.choices[0].message.content)

# See what model handled it and what it cost:
print("Model:", response.model_extra["komilion"]["brainModel"])
print("Tier:", response.model_extra["komilion"]["tier"])
print("Cost:", response.model_extra["komilion"]["cost"])

When you see output — you’re in. The brainModel field shows which model handled your request. The tier will say "balanced". The cost is what that call cost in USD.

Option 2: curl (30 seconds)

curl https://www.komilion.com/api/v1/chat/completions 
  -H "Authorization: Bearer ck_your_key" 
  -H "Content-Type: application/json" 
  -d '{
    "model": "neo-mode/balanced",
    "messages": [{"role": "user", "content": "What is the fastest way to find a duplicate in a Python list?"}]
  }'

You’ll get a standard OpenAI-format JSON response plus a komilion object in the response body with routing metadata.

Option 3: Existing OpenAI code (20 seconds)

If you already have code using the OpenAI SDK, change two lines:

# Before
client = OpenAI(api_key="sk-...")

# After
client = OpenAI(
    base_url="https://www.komilion.com/api/v1",
    api_key="ck_your_key"
)

Change the model string to neo-mode/balanced. Every other parameter — messages, temperature, stream, max_tokens — stays the same.

What the three model strings do

Once you have the first call working, here’s how to use all three tiers:

# Commit messages, summaries, format conversion — ~$0.006/call
response = client.chat.completions.create(
    model="neo-mode/frugal",
    messages=[{"role": "user", "content": "Write a git commit message for this diff: ..."}]
)

# Bug fixes, code review, new functions — ~$0.08/call (default)
response = client.chat.completions.create(
    model="neo-mode/balanced",
    messages=[{"role": "user", "content": "Review this function for edge cases: ..."}]
)

# System design, architecture, security review — council mode, ~90s response
response = client.chat.completions.create(
    model="neo-mode/premium",
    messages=[{"role": "user", "content": "Design the database schema for a multi-tenant SaaS: ..."}]
)

The routing metadata in every response tells you what tier was used and what it cost.

If something goes wrong

401 Unauthorized — API key is wrong or missing. Make sure you’re using your ck_ key, not an OpenAI key.

400 Bad Request on the model string — The model string must be exactly neo-mode/frugal, neo-mode/balanced, or neo-mode/premium. Do not use anthropic/claude-opus-4-6 or any other model string — those will return 400.

402 Insufficient Balance — Your wallet balance is $0. Top up at komilion.com/dashboard.

Empty komilion metadata — Upgrade to openai>=1.0.0. The model_extra field requires the newer SDK.

Slow response on Premium — Expected. The council runs multiple specialists, which can take up to 90 seconds. Use Balanced for interactive requests.

What’s next

Once your first call works:

  • Use neo-mode/balanced as the default everywhere in your codebase
  • Override to neo-mode/frugal for formatting, summarization, and commit messages
  • Override to neo-mode/premium only when the output is going to production without review

The Phase 4 benchmark (30 calls, 10 developer tasks, all outputs published) is at komilion.com/compare-v2 — worth reading before you commit to a tier strategy.

Questions: [email protected]

🚀 Sick of Paying a Fortune for SMS & WhatsApp Notifications?

Hook:
We’ve all been there: You build an amazing application (E-commerce, CRM, or SaaS). But when it’s time to integrate SMS or WhatsApp confirmations, the invoice hits you. 💸 Between Twilio’s API fees and Meta’s per-message costs, your budget is blown before your first customer even signs up.

The Problem:
“Official” solutions are great for multinationals. But for independent developers, startups, or local businesses, they are often a massive barrier:

High cost per message.

Endless business verification processes.

Reliance on international payment gateways.

The Solution: The “Self-Hosted” Approach 🛠️
Today, robust Open Source alternatives exist that allow you to keep total control and reduce your notification costs to zero.

  1. WhatsApp via Evolution API:
    Instead of paying per message, you use a full REST API that connects directly to your standard WhatsApp account (via the WhatsApp Web protocol). It’s stable, fast, and free.

Tool: Evolution API (the most powerful engine right now).

  1. SMS via Your Own Mobile Plan:
    Why pay an SMS gateway when you have unlimited SMS on your SIM card? By using an Android gateway application, your smartphone becomes your own SMS server.

Tool: SMS Gate (open source).

Why Choose Self-Hosted?
✅ Savings: €0/0$ in service fees.
✅ Freedom: You own your infrastructure.
✅ Flexibility: Easy integration into any project (Node.js, PHP/Laravel, Python).

Conclusion:
The era where sending notifications was a luxury is over. With the right Open Source tools, you can build professional communication systems without spending a cent on API fees.

What solution are you using for your notifications? Team Twilio or Team Open Source? 👇

HotSwap: Routing LLM Subtasks by Cache Economics

Abstract

Model routing and prompt caching are well-established, separate techniques for reducing LLM API costs. Routing directs simple tasks to cheaper models (40-85% savings). Anthropic’s prompt caching cuts input token costs by up to 90% on repeated prefixes. Every existing tool treats these as independent optimizations.

This post proposes HotSwap, a pattern that keeps a persistent cached Claude session as the stateful backbone while offloading read-only exploration turns to a cheaper provider. The motivation is cache economics: cached turns on Anthropic are cheap, so you want to keep complex work there while routing lightweight exploration elsewhere. The mechanism is simpler than you’d expect — task-type classification (exploration vs. action), not real-time cost calculation. And a self-tuning model selector adapts which cheap model handles exploration based on observed success rates in your specific workload.

To be clear about what’s novel and what isn’t: multi-model routing exists (LiteLLM, OpenRouter). Prompt caching is well-documented. The contributions here are: (1) using cache economics as the motivating insight for a hybrid architecture that keeps the primary session warm, (2) a guardrail mechanism that lets cheap models explore freely but prevents them from taking irreversible actions, (3) a self-tuning model selector that promotes or demotes the exploration model based on observed outcomes — no pre-trained classifier, no static rules, and (4) a cross-provider message format translation layer that makes the primary model see a seamless conversation history regardless of which provider handled which turn.

Status: HotSwap is implemented and under active benchmarking. Early data is directional, not definitive. This post describes the architecture and methodology; formal benchmark results will follow.

A note on terminology

“Cache-aware routing” is an existing term in infrastructure, but it refers to something completely different. Projects like llm-d (IBM/Google/Red Hat) use KV cache-aware routing to direct requests to GPU pods that already hold relevant context in memory — that’s routing requests to the right server. HotSwap operates at the application layer for API consumers, routing turns to the right provider based on task type, with cache economics as the motivating reason. Different layer, different audience, different problem.

The problem: two optimizations that don’t talk to each other

Today, if you want to reduce your LLM API spend, you have two main levers:

  1. Prompt caching. Anthropic lets you cache prompt prefixes and read them back at 10% of the input token cost. For long system prompts or multi-turn conversations, this is transformative — but you’re still paying full output token price on every call, even for turns that are just reading files and exploring code.

  2. Model routing. Tools like LiteLLM, OpenRouter, and Bifrost let you send simple requests to cheaper models. This works well, but each call is independent — there’s no concept of a persistent session, and no awareness of what’s already cached.

The gap: exploration turns (reading files, searching code, summarizing) don’t need a frontier model, but existing routers don’t know which turns are exploration and which are action. And caching tools don’t influence routing at all.

The economic insight that motivates HotSwap: even with Anthropic’s 90% cache discount, a cached Sonnet exploration turn costs ~$0.0045. An uncached gpt-4.1-nano turn costs ~$0.001. The hybrid isn’t just preserving the cache — it’s cheaper even when the cache is working perfectly.

A recent paper (Khraishi et al., 2026, arXiv:2603.03111) studied what happens when you switch models mid-conversation, finding that handoffs can swing outcomes by -8 to +13 percentage points depending on direction. However, that paper studied per-conversation-turn switching (swapping the model that continues a dialogue), not per-agentic-turn switching (routing discrete tool-calling turns within a single execution). HotSwap addresses the drift risk with a guardrail mechanism (see below).

The HotSwap architecture

HotSwap separates your LLM usage into two channels based on task type, with cache economics as the motivating reason for the split.

The cached backbone (Claude)

A single Claude session acts as the persistent source of truth. The system prompt, tool definitions, and growing conversation history are cached using Anthropic’s cache_control parameter. Every subsequent call to this session reads from the cache at 10% of the base input price. This session handles all turns that involve action: writing code, editing files, rebuilding, planning, and synthesis.

The cheap sidecar (OpenAI)

Exploration turns are offloaded to a cheaper model. The sidecar receives the full message history, translated to OpenAI’s native format — not a summarized version. The sidecar needs full context to make good exploration decisions (“which file should I read next?” depends on what’s already been read). Sending a self-contained prompt would require summarizing the conversation, adding complexity and token cost. The savings come from cheaper per-token pricing, not smaller inputs.

OpenAI has automatic prompt caching, but it doesn’t penalize switching between models — each exploration call is independent, so there’s no warm cache to lose on the sidecar side.

The routing logic

The routing decision is task-type-based, not real-time cost calculation:

  • First turn always goes to the primary model — this creates the cache.
  • After each turn, check: were all tools in the previous turn read-only? If yes, the next turn routes to the cheap model. If no, it stays on the primary.
  • If the cheap model requests action tools (edit_code, write_file, rebuild), the response is discarded and the turn is re-routed to the primary model. The cache is still warm.
  • If the cheap model call fails entirely (auth error, timeout, bad model name), the system falls back to the primary model gracefully. No hang, no crash.

The cache economics are the motivation — cached turns are cheap, so you want the expensive model handling the work that matters. The mechanism is straightforward task classification. Real-time cache-economics-driven routing (factoring in TTL, marginal cost comparisons) is a direction for future work.

How it actually works

def handle_turn(messages, tools, primary_model):
    # First turn always goes to primary (creates cache)
    if turn == 1:
        return primary_model.call(messages, tools)

    # Check: was the PREVIOUS turn exploration-only?
    last_tools = get_tools_called(messages[-1])
    all_exploration = all(t in EXPLORATION_TOOLS for t in last_tools)

    if not all_exploration or not openai_client:
        return primary_model.call(messages, tools)  # cache hit

    # Route to cheap model for exploration
    cheap_model = get_best_exploration_model(stats)  # self-tuning
    try:
        response = cheap_model.call(
            translate_to_openai(messages),  # full history, translated
            translate_tools(tools)
        )
    except Exception:
        # OpenAI failed -- fall back to primary, cache still warm
        return primary_model.call(messages, tools)

    # GUARDRAIL: if cheap model requests action tools, discard and re-route
    if any(tool in ACTION_TOOLS for tool in response.tool_calls):
        log("Guardrail: re-routing to primary")
        return primary_model.call(messages, tools)  # cache still warm

    # Translate response back to primary format and inject into history
    return translate_to_anthropic(response)
    # Primary's cache stays warm -- next primary call gets cache hit

The guardrail: explore freely, never act

This is how HotSwap addresses the context drift problem from arXiv:2603.03111.

The cheap model can call any read-only tool: read files, search code, summarize, list directories. But when the cheap model’s response includes a call to an action tool (edit_code, write_file, rebuild), the entire response is discarded and the turn is re-routed to the primary model. The primary’s cache is still warm — Anthropic’s cache TTL is 5 minutes, and exploration turns take seconds.

This means the cheap model can explore freely but cannot take irreversible actions. The worst case is a wasted sidecar call (~$0.001 on nano) — not a bad edit.

The guardrail itself is zero-cost on success: a string comparison against a set of tool names. No LLM call, no API round-trip. The only cost is when it triggers.

Guardrail triggers are not counted in exploration stats, which prevents pollution of the success rate data used for self-tuning.

Self-tuning exploration model selection

Existing model routers like RouteLLM train classifiers on fixed preference datasets, and FrugalGPT learns LLM cascades from labeled examples — both require upfront training data and don’t adapt at runtime. HotSwap’s routing adapts based on observed outcomes within your specific workload, with zero training data.

How it works:

  • Starts with the cheapest model — gpt-4.1-nano ($0.10/1M input tokens at time of writing; verify current pricing).
  • Tracks success rate: did this exploration turn lead to a successful edit on the next primary turn?
  • If success rate drops below 60% after 5+ exploration turns, promotes to the next cheapest model (e.g., gpt-4o-mini, then gpt-4.1-mini, then gpt-4o).
  • Stats persist across sessions in a local JSON file.
  • Zero LLM cost for the routing decision itself — pure bookkeeping.

Known limitation: the success metric is conservative. Only the last exploration turn before a successful edit gets credit. If three exploration turns preceded the edit, only the third is marked successful. This deflates the success rate, meaning the system is more cautious about staying on cheap models than the data may warrant. We chose conservative over optimistic — it’s safer to promote to a better model too early than to stay on a bad one too long.

This means HotSwap gets smarter over time for your specific workload. A codebase where nano handles exploration fine stays on nano. A codebase where nano’s exploration leads to bad edits gets automatically promoted to a better model. No manual tuning required.

Message format translation

A less glamorous but essential piece: the translation layer that makes cross-provider routing seamless.

Anthropic uses tool_use/tool_result blocks. OpenAI uses function_call/function response format. HotSwap translates the full Anthropic message history into OpenAI’s format before sending to the sidecar, and translates the OpenAI response back into Anthropic ContentBlocks before injecting it into the conversation history.

The primary model sees a seamless history — it doesn’t know some turns were handled by a different provider. This is what makes the cache reinjection work without invalidating the cached prefix.

What already exists vs. what HotSwap adds

The building blocks are mature. The combination is new.

Capability Existing tools HotSwap
Multi-model routing LiteLLM, OpenRouter, Bifrost Uses existing
Prompt caching Anthropic API Uses existing
Orchestrator / worker split Various Uses existing
Task-type routing motivated by cache economics None Novel
Guardrail: explore freely, never act None Novel
Self-tuning model selector based on observed outcomes None Novel
Cross-provider message format translation with cache reinjection None Novel
Graceful fallback on sidecar failure None Novel

Known risks and mitigations

  • Context drift. arXiv:2603.03111 found that switching models mid-conversation can swing outcomes by -8 to +13 percentage points. HotSwap mitigates this with the guardrail: the cheap model can explore but cannot act. If it tries to act, the turn is discarded and re-routed. Additionally, the arXiv paper studied conversational handoffs (one model continuing another’s dialogue); HotSwap’s exploration turns produce factual tool results (file contents, search matches), which carry less drift risk than open-ended reasoning.

  • Cache invalidation. Reinjected sidecar results append to the end of the message history but do not modify the cached prefix (system prompt, tools, early history). The prefix stays immutable. Risk: if the message history grows large enough to push past cache boundaries, hits may degrade.

  • Latency overhead. The sidecar call adds a network round-trip, plus translation time. For latency-sensitive applications, this may not be worth it. Mitigation: measure P50/P95 latency per path and adjust routing thresholds.

  • Translation fidelity. The format translation between Anthropic and OpenAI is not lossless — edge cases in tool call formatting, multi-block responses, or provider-specific features could cause subtle issues. Mitigation: test translation on your specific tool set before deploying.

  • Sidecar availability. If the OpenAI API is down or the model name is invalid, the sidecar call fails. Mitigation: HotSwap catches all sidecar errors and falls back to the primary model. This was added after discovering a real hang caused by a sidecar failure during development.

Early data (benchmarking in progress)

From actual sessions — directional, not definitive:

Configuration Cost Turns Outcome Notes
Sonnet with caching $0.38 9 Completed One measured session
Sonnet with caching $0.70 17 Completed One measured session (more complex task)
Opus with caching $0.88 9 Completed One measured session
Cache discount (Sonnet) 22% — — One measured session vs. uncached baseline

Hybrid routing data (OpenAI exploration turns) is being collected. Formal benchmarks across the scenarios below are actively in progress.

Benchmark methodology

To validate HotSwap, metrics are being collected across three configurations: (A) pure Claude without caching, (B) pure Claude with caching, and (C) the HotSwap hybrid approach.

Primary metrics

Metric What to measure Why it matters
Cost per task Total API spend across all providers for one complete task The headline number
Cost per turn by type Break down by exploration vs. action turns Shows where offloading saves money
Cache hit rate Percentage of primary model calls that hit the cache Validates the architecture’s core assumption
End-to-end duration Wall-clock time per task Reveals whether sidecar round-trips add unacceptable delay
Task completion rate Did the task succeed across configurations? Proves offloading exploration doesn’t degrade results

Secondary metrics

Metric What to measure Why it matters
Guardrail trigger rate How often the cheap model tries to act and gets re-routed High rate means exploration model is too aggressive
Self-tuning promotions How often the system promotes to a more expensive exploration model Indicates when the cheapest model isn’t good enough
Sidecar fallback rate How often sidecar calls fail, requiring a primary model retry Measures reliability of the cross-provider bridge
Exploration success rate Did the exploration turn lead to a successful action on the next turn? The metric that drives self-tuning

Test scenarios (in progress)

  1. Simple UI change. Change one CSS property. Minimal exploration, one edit. Tests baseline cost across models.

  2. Find and fix. Locate a specific UI element and modify it. Moderate exploration (search + read), one edit. Tests exploration routing.

  3. Add a feature. Add a new UI element with behavior. Heavy exploration (multiple files), multiple edits. Tests the full exploration-to-action cycle.

  4. Investigation only. Answer a question about the codebase. All exploration, no edits. Tests whether HotSwap saves on pure-exploration tasks.

  5. Multi-file refactor. Extract duplicated code into a shared utility. Heavy exploration + heavy action. Tests the architecture under sustained load.

What comes next

HotSwap is a hypothesis under active testing, not a proven solution. The architecture is working, but the key question — does the added complexity pay for itself, and under what conditions? — is still open.

Directions being explored:

  • Real-time cache-economics-driven routing — using TTL remaining and marginal cost comparisons to make routing decisions dynamically, instead of pure task-type classification. This is the aspirational version of the pattern.
  • More granular tool classification — the current exploration/action split is binary. Some tools are borderline (e.g., running tests is read-only but computationally meaningful). Smarter classification could improve routing accuracy.
  • Broader provider support — the translation layer currently handles Anthropic <> OpenAI. Adding Google Vertex or local models as sidecar options would test provider-agnosticism.

Larry Kang – March 2026

The Habit MACD: How to Detect Momentum Shifts Before You Burn Out or Quit

If you’ve ever felt a habit “losing energy” before you could articulate why — MACD explains it.

In technical analysis, the MACD (Moving Average Convergence Divergence) is the go-to indicator for catching momentum shifts before they become trend reversals.

I’ve been tracking my habits like stocks for several months now. After experimenting with Sharpe Ratios, RSI, Bollinger Bands, and moving averages applied to daily behavior — MACD is the indicator I check most.

Here’s why.

What MACD Tells You That Streaks Never Could

A streak tells you one thing: did you show up or not.

MACD tells you something far more useful: is your momentum building or fading?

The classic MACD uses two exponential moving averages — typically 12-day and 26-day — and plots their difference as a “MACD line.” A second “signal line” (9-day EMA of the MACD line) creates the crossover signal.

When MACD crosses above the signal line: bullish momentum is building.
When MACD crosses below: bearish divergence — momentum is fading, even if the habit is still happening.

For habits, I adapted this:

function habitMACD(scores, short = 7, long = 21, signal = 5) {
  const ema = (data, period) => {
    const k = 2 / (period + 1);
    return data.reduce((acc, val, i) => {
      if (i === 0) return [val];
      return [...acc, val * k + acc[acc.length - 1] * (1 - k)];
    }, []);
  };

  const shortEMA = ema(scores, short);
  const longEMA = ema(scores, long);
  const macdLine = shortEMA.map((v, i) => v - longEMA[i]);
  const signalLine = ema(macdLine.slice(long - 1), signal);

  return {
    macdLine: macdLine.slice(long - 1),
    signalLine,
    histogram: macdLine.slice(long - 1).map((v, i) => v - (signalLine[i] || 0))
  };
}

The Four MACD States for Habits

1. Bullish Crossover (MACD crosses above signal)
Your short-term momentum is outpacing your long-term average. This is the entry signal — the habit is accelerating. You’re building the behavior faster than historical pace.

2. Bearish Crossover (MACD crosses below signal)
This is the warning sign. Your habit hasn’t broken yet. The streak might still be intact. But momentum is fading. In my data, a bearish crossover predicts a miss within the next 9 days with ~67% accuracy.

3. Histogram Expansion (bars growing)
Momentum is strengthening. If bullish: accelerating growth. If bearish: accelerating decline. The rate of change of change.

4. Histogram Compression (bars shrinking)
A reversal is approaching. If in a bearish trend, compression often precedes recovery. The bottom is forming.

The Pattern That Surprised Me Most

When I ran MACD analysis on 90+ days of habit data across several behaviors, I found something I didn’t expect:

The bearish crossover almost always happened on a “good” week.

Not after a miss. Not after a stressful period. After a string of 95%+ scores.

This is the MACD version of what I call the Overbought Trap (which overlaps with the RSI signal I’ve written about). Intensity without variance builds emotional fragility. The MACD detects the unsustainable acceleration — the “too fast” momentum — that streaks completely miss.

Practical Application

I now use MACD for a single decision: do I need to coast or push?

  • Bullish crossover + expanding histogram → push this week, momentum is real
  • Bearish crossover + expanding histogram → coast, reduce friction, ride it out
  • Histogram compression → prepare for a momentum flip either direction
  • Below zero but compressing → recovery forming, don’t abandon now

The key insight: coasting on bearish MACD is not failure. It’s risk management.

A trader who holds through every bearish signal gets wiped. A trader who cuts position size during low-momentum periods protects capital for the next rally.

Same logic applies to habits. The goal isn’t 100% effort every day. The goal is sustained participation over years.

What This Changed For Me

I used to push hardest exactly when I should have coasted — during bearish divergence, when momentum was already fading. The willpower expenditure accelerated the decline rather than preventing it.

Now when I see a bearish MACD crossover, I deliberately reduce the “dose” of the habit. Not skip it. Just: do less. 15 minutes instead of 45. Show up at 50% instead of 100%.

The habit price dips slightly. But the MACD recovers. And the next bullish crossover comes from a more stable base.

The result: fewer dramatic crashes. Slower accumulation. Better long-term charts.

I built HabitStock to make this kind of analysis accessible without a spreadsheet. Free, no account required: habitstock.limed.tech

Have you ever felt a habit losing energy before the actual miss? That’s MACD in action.

Tags: productivity, javascript, webdev, indiehackers

AWS S3 Introduces Account-Regional Namespaces, Ending 18 Years of Global Bucket Name Collisions

AWS introduced account-regional namespaces for S3, fixing global bucket name collisions that broke IaC automation for 18 years. New format: {prefix}-{account-id}-{region}-an. CloudFormation gets the BucketNamePrefix property, and IAM gets the s3:x-amz-bucket-namespace condition key. Prevents confused-deputy attacks by making names unpredictable when there is no account ID.

By Steef-Jan Wiggers

Presentation: Open Source, Community, and Consequence: The Story of MongoDB

Andrew Davidson and Akshat Vig discuss the journey of disrupting the transactional database market. They explain why the document model became the “Buckminster Fuller” moment for modern apps and share lessons on scaling from “web-scale” memes to mission-critical workloads. Leaders will learn about operational excellence, monetizing convenience over control, and navigating the open-source race.

By Akshat Vig, Andrew Davidson

İYTE, EBSO Ödül Töreninde 3 Ödüle Layık Görüldü

İzmir Yüksek Teknoloji Enstitüsü, EBSO tarafından düzenlenen törende üniversite-sanayi iş birliği alanındaki başarıları nedeniyle 3 ödül kazandı. Rektör Prof. Dr. Yusuf Baran, bu ödüllerin Türkiye’nin yerli ve milli teknoloji hamlesine katkının bir göstergesi olduğunu belirtti.