Simple AI Scientist Bot (Python)

A minimal clone of scientific‑agent‑skills for beginners

Welcome to another official UVF IT build guide! In the next 45 minutes you’ll spin up a tiny AI Scientist Bot that can answer basic scientific queries using a local LLM and a tiny SQLite knowledge store, inspired by the K‑Dense scientific‑agent‑skills project.

We’ll use plain Python, the free‑tier openai API (or any compatible local model), and SQLite – all running on your laptop. No paid services, no Docker, just a few commands and a bit of code.

Before you start…

Minimal AI Scientist Bot Architecture
LOCAL RUNTIME store/query ask Python Bot SQLite DB OpenAI API (free tier)
1

Phase 1: Scaffold the project

Create a fresh folder for the bot and spin up an isolated Python virtual environment. This keeps our dependencies tidy and avoids polluting your global Python install.

Install the tiny libraries we need – the OpenAI client for API calls and nothing else because SQLite is built into Python’s standard library.

mkdir ai_scientist_bot && cd ai_scientist_bot
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install openai
2

Phase 2: Define the data model (SQLite)

We’ll create a single SQLite database file named facts.db with a table facts that stores an id, a topic, and the content of each scientific fact. This tiny store will act as the knowledge base the bot can query.

The script also pre‑populates the table with a couple of example facts so you can test the bot immediately after the next phase.

init_db.py

import sqlite3

DB_PATH = 'facts.db'

def init_db():
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()
    # Create table
    cur.execute('''
        CREATE TABLE IF NOT EXISTS facts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            topic TEXT NOT NULL,
            content TEXT NOT NULL
        )
    ''')
    # Insert example facts
    examples = [
        ('gravity', 'Gravity is the force that attracts two bodies toward each other.'),
        ('photosynthesis', 'Photosynthesis converts light energy into chemical energy in plants.')
    ]
    cur.executemany('INSERT INTO facts (topic, content) VALUES (?, ?)', examples)
    conn.commit()
    conn.close()

if __name__ == '__main__':
    init_db()
    print('Database initialized with example facts.')
3

Phase 3: Core bot logic – query DB & call LLM

The bot first looks for a matching fact in the SQLite knowledge base; this keeps responses fast and deterministic for known queries. If the database returns nothing, we fall back to an OpenAI LLM call so the bot can still answer novel scientific questions. The script combines both paths into a single answer_question function, making the flow easy to extend later.

bot.py

import os
import sqlite3
import openai

# Load OpenAI key from environment for safety
openai.api_key = os.getenv("OPENAI_API_KEY")

DB_PATH = "facts.db"

def init_db():
    """Create a tiny facts table if it doesn't exist."""
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()
    cur.execute("""
        CREATE TABLE IF NOT EXISTS facts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            question TEXT UNIQUE,
            answer TEXT
        )
    """)
    conn.commit()
    conn.close()

def query_fact(question: str) -> str:
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()
    cur.execute("SELECT answer FROM facts WHERE question = ?", (question,))
    row = cur.fetchone()
    conn.close()
    return row[0] if row else None

def ask_llm(prompt: str) -> str:
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=150,
        temperature=0.7,
    )
    return response.choices[0].message.content.strip()

def answer_question(question: str) -> str:
    # 1. Try the local DB first
    fact = query_fact(question)
    if fact:
        return fact
    # 2. If not found, ask the LLM
    return ask_llm(question)

if __name__ == "__main__":
    init_db()
    print("Simple AI Scientist Bot – type 'exit' to quit.")
    while True:
        user_q = input("You: ").strip()
        if user_q.lower() in ("exit", "quit"):
            break
        print("Bot:", answer_question(user_q))
4

Phase 4: Run locally

Initialize the SQLite database once with a couple of example facts, then launch the interactive loop. The first run will create facts.db and seed it if you wish, but the script already ensures the table exists, so you can simply start the bot and begin asking questions.

# Ensure you have the OpenAI key exported
export OPENAI_API_KEY=your_key_here

# Run the bot – it will create the DB on first start
python bot.py
5

Phase 5: Verify & extend

Test the bot with a known fact (e.g., "What is gravity?") to see the database lookup in action. Then ask something the DB doesn't know, like "Explain dark matter," and watch the LLM generate a response. Finally, add your own fact directly into SQLite and confirm the bot now returns it without hitting the LLM.

# 1. Add a new fact to the DB (example: gravity)
sqlite3 facts.db "INSERT OR IGNORE INTO facts (question, answer) VALUES ('What is gravity?', 'Gravity is the force that attracts two bodies toward each other.');"

# 2. Run the bot and test both paths
python bot.py <<EOF
What is gravity?
Explain dark matter
exit
EOF

# 3. Add another custom fact
sqlite3 facts.db "INSERT OR REPLACE INTO facts (question, answer) VALUES ('What is photosynthesis?', 'Photosynthesis is the process plants use to convert sunlight into chemical energy.');"

# 4. Verify the new fact is returned
python bot.py <<EOF
What is photosynthesis?
exit
EOF"}]]

Verifying the Stack

CheckCommand / Why it matters
Database created with two example factssqlite3 facts.db "SELECT COUNT(*) FROM facts;" should output 2
Bot returns a stored factRun python bot.py and ask "What is gravity?" – answer should match the DB entry
Bot falls back to LLMAsk an unknown topic like "Explain dark matter" – answer should be generated by OpenAI

You did it!

Your minimal AI Scientist Bot is up and running. Feel free to enrich the SQLite knowledge base, swap the OpenAI model for a local LLM, or wrap the script in a tiny FastAPI server for a web UI. Happy experimenting!