Skip to content

feat(generate): fall back to Ollama automatically when no API key configured#17

Merged
derek-palmer merged 1 commit into
mainfrom
feat/ollama-local-fallback
May 24, 2026
Merged

feat(generate): fall back to Ollama automatically when no API key configured#17
derek-palmer merged 1 commit into
mainfrom
feat/ollama-local-fallback

Conversation

@derek-palmer
Copy link
Copy Markdown
Owner

@derek-palmer derek-palmer commented May 24, 2026

Summary

  • OllamaProvider.is_available() — lightweight GET /api/tags probe (2s timeout) to detect a running Ollama instance
  • forerunner generate auto-switches to Ollama when no provider is explicitly configured and no API key is present; prints info: no API key; falling back to Ollama (local mode) to stderr. An explicit --provider flag or provider: in config suppresses the fallback.
  • When Ollama is not running either, the error message gains a hint: start Ollama for keyless local generation line
  • forerunner doctor surfaces the effective mode: [ok] local mode when Ollama is configured or auto-detected; Ollama hint when no config and no key are present

Test plan

  • pytest tests/ — 187 passed, 1 skipped
  • test_ollama_is_available_* (4 tests) — probe logic, env override, explicit host, package export
  • test_generate_falls_back_to_ollama_* (5 tests) — fallback fires, explicit provider blocks fallback, config provider blocks fallback, Ollama hint in error, model flag preserved through fallback
  • test_provider_api_key_local_mode_* / test_provider_api_key_hint_* (3 tests) — doctor local-mode message paths

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added automatic fallback to local Ollama generation when API keys are unavailable and no specific provider is requested.
    • Improved error messages to guide users toward starting Ollama for keyless local generation.
    • System now detects Ollama availability for seamless local-mode operation.

Review Change Stack

…configured

When no provider is explicitly set (via --provider or config) and no API
key is found, probe Ollama at localhost:11434. If reachable, switch to
local mode and print an info line to stderr. If not reachable, include
an Ollama hint in the error message.

forerunner doctor surfaces the effective mode: "local mode" when Ollama
is the active or auto-detected provider; hint about Ollama when no
config and no API key are present.

Tests: +13 (187 total, 1 skipped). Covers is_available(), CLI fallback
paths, explicit-provider/config-provider non-fallback, model preservation,
and all three doctor local-mode scenarios.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 24, 2026

📝 Walkthrough

Walkthrough

This PR implements automatic fallback to local Ollama generation when API keys are unavailable. It adds an Ollama availability probe, updates CLI and diagnostic checks to conditionally use local mode, and includes comprehensive test coverage for fallback scenarios.

Changes

Ollama local-mode fallback

Layer / File(s) Summary
Ollama availability detection and export
src/codeforerunner/providers/ollama.py, src/codeforerunner/providers/__init__.py, tests/test_providers.py
New is_available() function probes Ollama server reachability via /api/tags endpoint; resolves host from argument, OLLAMA_HOST env var, or default; exported as ollama_available from providers module and fully tested.
CLI generate fallback to Ollama
src/codeforerunner/cli.py, tests/test_cli.py
cmd_generate now distinguishes explicit provider requests from defaults, enabling fallback to Ollama when API key is missing and no explicit provider was set; falls back only if Ollama is available; emits info message on fallback or Ollama-related error hints on failure; model flag is preserved during fallback; tested across five scenarios including success, no fallback when explicit, and missing key with/without Ollama available.
Doctor provider-api-key check with local-mode detection
src/codeforerunner/doctor.py, tests/test_doctor.py
_check_provider_api_key now detects Ollama availability when no config file exists, reporting success with local-mode messaging for Ollama or prompting to set API key/start Ollama otherwise; Ollama provider message updated to explicitly state "running in local mode (Ollama; no API key needed)"; tested across three scenarios for config/availability combinations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit hops through provider chains with glee,
When keys go missing, Ollama runs free!
Local generation, no API to see,
Falls back so gracefully, a fallback spree! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(generate): fall back to Ollama automatically when no API key configured' accurately and specifically describes the main feature added: automatic fallback to Ollama when no API key is present.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/ollama-local-fallback
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch feat/ollama-local-fallback

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/codeforerunner/cli.py`:
- Around line 114-116: The current logic treats cfg.provider as an explicit user
choice even when the config file contains defaults; fix explicit_provider by
checking whether the provider key was actually present in the loaded config
(e.g., use a presence check on the config object or its raw dict rather than
truthiness of cfg.provider) and only treat it as explicit if the key exists;
apply the same presence-based check to the other provider-selection spots noted
around lines 136-147 (where provider/model are derived), and add a regression
test that writes a config file without a provider key, ensures no API key is
set, sets ollama_available=True, runs the CLI selection path, and asserts the
selected provider is "ollama".
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3d604a85-c799-4cb8-b729-170b1f4ff24c

📥 Commits

Reviewing files that changed from the base of the PR and between d5cd12c and 7dc1947.

📒 Files selected for processing (7)
  • src/codeforerunner/cli.py
  • src/codeforerunner/doctor.py
  • src/codeforerunner/providers/__init__.py
  • src/codeforerunner/providers/ollama.py
  • tests/test_cli.py
  • tests/test_doctor.py
  • tests/test_providers.py

Comment thread src/codeforerunner/cli.py
Comment on lines +114 to 116
explicit_provider = args.provider or (cfg.provider if cfg else None)
provider_name = explicit_provider or "anthropic"
model = args.model or (cfg.model if cfg else None)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

explicit_provider incorrectly treats default config as user-explicit provider.

Line 114 currently marks cfg.provider as explicit even when it comes from defaults, so fallback is skipped whenever forerunner.config.yaml exists without a provider: key. That breaks the intended “no explicit provider → auto-fallback to Ollama” flow.

💡 Proposed fix
-    from codeforerunner.config import load_from_repo
+    from codeforerunner.config import CONFIG_FILENAME, load_from_repo
@@
-    explicit_provider = args.provider or (cfg.provider if cfg else None)
-    provider_name = explicit_provider or "anthropic"
+    cfg_path = repo_root / CONFIG_FILENAME
+    config_provider_is_explicit = False
+    if cfg_path.is_file():
+        config_provider_is_explicit = any(
+            line.split("#", 1)[0].strip().startswith("provider:")
+            for line in cfg_path.read_text(encoding="utf-8").splitlines()
+        )
+
+    explicit_provider = args.provider or (
+        cfg.provider if (cfg and config_provider_is_explicit) else None
+    )
+    provider_name = args.provider or (cfg.provider if cfg else "anthropic")

Also add a regression test for: config file exists without provider:, no API key, ollama_available=True ⇒ fallback occurs.

Also applies to: 136-147

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/codeforerunner/cli.py` around lines 114 - 116, The current logic treats
cfg.provider as an explicit user choice even when the config file contains
defaults; fix explicit_provider by checking whether the provider key was
actually present in the loaded config (e.g., use a presence check on the config
object or its raw dict rather than truthiness of cfg.provider) and only treat it
as explicit if the key exists; apply the same presence-based check to the other
provider-selection spots noted around lines 136-147 (where provider/model are
derived), and add a regression test that writes a config file without a provider
key, ensures no API key is set, sets ollama_available=True, runs the CLI
selection path, and asserts the selected provider is "ollama".

@derek-palmer derek-palmer merged commit 8f28c38 into main May 24, 2026
3 checks passed
@derek-palmer derek-palmer deleted the feat/ollama-local-fallback branch May 24, 2026 21:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant