keepcalculator

06 Numbers and Powers

Wired Ollama Into a Recipe Collection: Setup Guide

Card No. 06·26240 · Updated · Standard formula, shown below

If you want to connect Ollama to a recipe collection, the practical approach is to let a small local app send recipe text to an Ollama model and save the results in a searchable database. This guide walks through a simple Python setup that imports recipe files, asks Ollama to suggest tags, and keeps the original recipes intact.

What You’ll Need

Ollama runs language models on your computer and exposes a local HTTP API. The example below uses Python, SQLite, and plain-text Markdown files, so it does not require a hosted database or a web framework. You can adapt the same pattern to a larger collection or a different storage system.

  • Ollama installed and running on the computer that will process recipes
  • A downloaded Ollama model, such as llama3.2 (use a model name available on your machine)
  • Python 3.10 or later
  • A folder containing recipe files in Markdown or plain text
  • About 15 minutes for the initial setup

Instructions

  1. Start Ollama and confirm the model. Open a terminal and run ollama list. If your chosen model is not listed, download one with ollama pull llama3.2. Start a quick test with ollama run llama3.2, enter a short prompt, then exit the interactive session. Keep the model name consistent in the commands and code below.
  2. Arrange your recipes. Create a project folder with a subfolder named recipes. Save each recipe as a separate .md or .txt file. Use descriptive filenames, for example lemon-lentil-soup.md. The importer treats the file contents as source material; it does not need a special recipe template.
  3. Create a Python environment and install the HTTP client. From the project folder, run python -m venv .venv, then activate it. On macOS or Linux, use source .venv/bin/activate; on Windows PowerShell, use .venv\Scripts\Activate.ps1. Install the dependency with python -m pip install requests.
  4. Save the importer as import_recipes.py. It creates a local SQLite database, sends each recipe to Ollama for a short tag list, and stores the original text alongside those tags. The API call uses Ollama’s local endpoint at http://localhost:11434.
from pathlib import Path
import json
import sqlite3
import requests

MODEL = "llama3.2"
RECIPE_DIR = Path("recipes")
DB_PATH = "recipes.db"
OLLAMA_URL = "http://localhost:11434/api/generate"


def suggest_tags(text):
    prompt = (
        "Suggest 3 to 6 concise search tags for this recipe. "
        "Return only a JSON array of strings. Do not rewrite the recipe.\n\n"
        + text[:12000]
    )
    response = requests.post(
        OLLAMA_URL,
        json={"model": MODEL, "prompt": prompt, "stream": False},
        timeout=180,
    )
    response.raise_for_status()
    answer = response.json()["response"].strip()
    try:
        tags = json.loads(answer)
        return [str(tag).strip() for tag in tags if str(tag).strip()]
    except (json.JSONDecodeError, TypeError):
        return ["tag review needed"]


with sqlite3.connect(DB_PATH) as db:
    db.execute("""CREATE TABLE IF NOT EXISTS recipes (
        id INTEGER PRIMARY KEY,
        filename TEXT UNIQUE NOT NULL,
        title TEXT NOT NULL,
        body TEXT NOT NULL,
        tags TEXT NOT NULL
    )""")

    for path in sorted(RECIPE_DIR.glob("*")):
        if path.suffix.lower() not in {".md", ".txt"}:
            continue
        body = path.read_text(encoding="utf-8").strip()
        if not body:
            continue
        tags = suggest_tags(body)
        title = path.stem.replace("-", " ").replace("_", " ").title()
        db.execute(
            "INSERT INTO recipes (filename, title, body, tags) "
            "VALUES (?, ?, ?, ?) ON CONFLICT(filename) DO UPDATE SET "
            "title=excluded.title, body=excluded.body, tags=excluded.tags",
            (path.name, title, body, json.dumps(tags)),
        )
        print(f"Imported {path.name}: {', '.join(tags)}")
  1. Run the import. Check that Ollama is running, then execute python import_recipes.py. The first request can take longer while the model loads. A successful import prints each filename and its suggested tags, and creates recipes.db in the project folder.
  2. Check the saved collection. Run this small query in a Python shell or save it as a separate script to inspect titles and tags:
import sqlite3

with sqlite3.connect("recipes.db") as db:
    for title, tags in db.execute("SELECT title, tags FROM recipes ORDER BY title"):
        print(title, tags)

For a quick search, you can query the database with SQLite’s built-in text matching: SELECT title FROM recipes WHERE body LIKE '%lentil%';. This is suitable for a personal collection; larger collections can use a full-text index or a dedicated search service.

Tips

  • Keep the original recipe as the source of truth. Model-generated tags are suggestions and can be wrong, especially for allergens, dietary labels, or ingredients mentioned only as substitutions.
  • Use utf-8 text files and consistent filenames. Avoid changing a filename after importing unless you want it stored as a separate record.
  • If the model returns extra commentary instead of a JSON array, the example marks the recipe “tag review needed.” Review or adjust the prompt rather than trusting malformed output.
  • Do not send private or sensitive notes to a model unless you are comfortable processing them locally. Ollama’s local endpoint is intended for local use; avoid exposing its port to an untrusted network.

Serving Suggestions

Once recipes are in SQLite, a basic command-line search can help you find dishes by ingredient, title, or tag. For a friendly interface, connect the database to a small local app with a search box and recipe detail view. Keep the recipe text readable and show tags as filters, not as replacements for ingredients or cooking instructions.

Variations

You can ask Ollama for additional structured fields, such as cuisine or meal type, but validate the response before saving it. For more reliable metadata, require a defined JSON object and validate its keys and value types in Python. If your recipes are already in a spreadsheet, export them to CSV and import rows into SQLite instead of converting every entry to a separate file. For semantic search, create embeddings with an embedding model and store them in a vector index; that is a separate feature from the simple keyword search shown here.

Storage and Reheating

In this setup, “storage” means keeping the recipe collection and its database safe: back up both the recipes folder and recipes.db regularly, and close the script before copying the database. SQLite is a single-file database, but edits made after an older backup will not be included in that copy. Re-run the importer after changing recipe files; it updates records with matching filenames. This workflow does not cook or refrigerate food, so follow each recipe’s food-safety instructions for actual dishes.

Frequently Asked Questions

Does Ollama need an internet connection?
After Ollama and the model are installed, generation can run locally without an internet connection. Downloading models and installing Python packages do require network access.

Why does the script say it cannot connect?
Ollama may not be running, or its local service may not be listening at the expected address. Start Ollama, confirm its API is available at localhost:11434, and try again.

Can I use a different model?
Yes. Set MODEL to a model name shown by ollama list. Models vary in speed and output quality, so check the generated tags before relying on them.

Will rerunning the importer create duplicates?
No, not for the same filename. The database uses the filename as a unique key and updates that record. Renaming a file creates a new key, so remove the old record if you no longer want it.

Can the model extract ingredients and cooking times too?
It can attempt to, but extraction may omit or misread details. Store those fields only after validating them against the original recipe, particularly quantities, temperatures, and timing.

Where is the recipe data stored?
The original files remain in recipes, while titles, text, and tags are stored in recipes.db in the project directory. Back up both locations to preserve the collection.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →