Skip to main content

Bot-Maker Baker - A smart yet simple chatbot framework for Python

Project description

Baker

Bot-Maker Baker — a chatbot framework with actual ML. Uses TF-IDF vectorization, character n-gram similarity, intent classification, smart response selection, template rendering, and optional sentence-transformers for semantic matching. No hardcoded rules, no massive synonym dictionaries — the ML learns from your data.

Installation

pip install baker-python

Or from source:

pip install -e .

For the semantic backend (better understanding, heavier dependency):

pip install sentence-transformers

Quick Start

from baker import Chatbot

bot = Chatbot("MyBot", "data.json", memory=True)

# Define intents (optional — checked before fuzzy matching)
bot.add_intent("greeting", ["Hello", "Hi", "Howdy"], ["Hey there!", "Hi {name}!"])

bot.respond("Hello")            # "Hey there!" (via intent)
bot.respond("helloo")           # understands typos via char n-gram TF-IDF
bot.respond("how are you doing?")   # matches via word TF-IDF
bot.respond("whats your name")      # "whats" → "what is" via contraction expansion
bot.respond("My name is Alice")     # "Hi Alice!" (template + entity extraction)

How the ML Works

Baker uses a two-vector approach for matching:

  1. Word-level TF-IDF: Learns term importance from your data. Common words get lower weight, distinctive words get higher weight. Queries are compared to known keys via cosine similarity.

  2. Character n-gram TF-IDF (2-4 grams): Captures spelling variations, typos, and morphological similarity. "helloo" → shares character n-grams with "Hello".

Combined score: 0.6 × word_sim + 0.4 × char_sim

Data File Format

Create a JSON, YAML, or XML file:

JSON (data.json):

{
    "Hello": ["Hi!", "Hello!", "Hey there!"],
    "How are you": ["I'm doing great!", "Pretty good, thanks!"],
    "What is your name": ["My name is Baker!"]
}

YAML (data.yaml):

Hello:
- Hi!
- Hello!
How are you:
- I'm good, thanks!

XML (data.xml):

<responses>
  <Hello>
    <response>Hi!</response>
    <response>Hello!</response>
  </Hello>
</responses>

Usage

Backend Selection

Backend Dependency Quality Use Case
'tfidf' (default) none Good Lightweight, fast, no installs
'semantic' sentence-transformers Best Deep semantic understanding
# Default TF-IDF (lightweight ML, no extra deps)
bot = Chatbot("MyBot", "data.json", backend='tfidf')

# Semantic (requires: pip install sentence-transformers)
bot = Chatbot("MyBot", "data.json", backend='semantic')

Intents

Define named intents with example phrases and responses. Baker classifies user input via TF-IDF against your examples.

bot.add_intent(
    "greeting",
    ["Hello", "Hi", "Hey", "Howdy", "Good morning"],
    ["Hey there!", "Hi {name}!", "Hello! How are you?"]
)

bot.add_intent(
    "farewell",
    ["Bye", "Goodbye", "See you later"],
    ["Goodbye!", "See you later!", "Take care {name}!"]
)

bot.list_intents()  # ["greeting", "farewell"]
bot.remove_intent("farewell")

Intents are checked before fuzzy TF-IDF key matching, so they override ambiguous matches.

Template Responses

Responses can use {variable} placeholders filled from entities and conversation memory:

bot.respond("My name is Alice")  # "Hi Alice!" (from greeting intent + entity)

Available variables: {name}, {age}, {email}, {last_topic}, {sentiment}, {intent}. Unknown variables render as empty string.

Smart Response Selection

Instead of random choice, Baker scores each response candidate:

  • +1.0 base score
  • −0.3 per recent use (last 5 responses)
  • +0.15 per matched entity in the text
  • +0.05 for templates (encourages personalized responses)

This naturally avoids repetition and prefers responses that reference extracted entities.

Training

# Single
bot.train("Hello", "Hey there!")

# Bulk
bot.train_many([
    ("What is your name", "I'm Baker!"),
    ("How old are you", "I was just born!"),
])

# From a JSON corpus file
trainer = Trainer("data.json")
trainer.train_from_json("corpus.json")
trainer.train_from_csv("corpus.csv")

Response Details

details = bot.respond_detailed("Hello")
print(details['response'])     # "Hi!"
print(details['confidence'])   # 1.0
print(details['matched_key'])  # "Hello"
print(details['sentiment'])    # "neutral"
print(details['entities'])     # {}

Conversation Memory

bot = Chatbot("MyBot", "data.json", memory=True)
bot.respond("My name is Alice")
bot.get_context()['entities']['name']  # "Alice"

Adjusting Match Sensitivity

# Lower threshold = more fuzzy matches (default 0.3)
bot = Chatbot("MyBot", "data.json", threshold=0.2)

# Higher threshold = stricter matching
bot = Chatbot("MyBot", "data.json", threshold=0.6)

Data Management

from baker import Parser

parser = Parser("data.json")
parser.list_key_questions()
parser.count_responses("Hello")
parser.remove_response("Hello", "Hi")
parser.reset_responses("Hello")
parser.export_responses("data.yaml")

Interactive Session

bot = Chatbot("MyBot", "data.json")
bot.session()

Type teach to train the bot mid-session.

API

Class Purpose
Chatbot(name, data_file, backend, threshold, memory) Main chatbot interface
Parser(file, backend, threshold) Data layer with ML matching
Trainer(file, backend, threshold) Extends Parser with bulk training
Matcher(threshold) TF-IDF + char n-gram similarity search
SemanticMatcher(model, threshold) Sentence-transformers similarity
TfidfVectorizer() Pure-Python TF-IDF implementation
IntentClassifier(threshold) TF-IDF intent classification from examples
ResponseSelector(recency_penalty, diversity_window) Smart non-random response selection
TemplateEngine() {variable} placeholder rendering in responses
EntityExtractor() Regex entity extraction (name, age, email)
SentimentAnalyzer() Token-based sentiment detection
ConversationMemory() Conversation history and entity tracking

Why Baker?

  • Real ML: TF-IDF vectorization + cosine similarity. No hardcoded rules.
  • Lightweight default: Zero external ML dependencies (only PyYAML for file formats).
  • Optional semantic power: Plug in sentence-transformers for deep understanding.
  • Simple: One-liner instantiation, one method to chat.
  • Flexible: JSON, YAML, XML. Train on the fly or from files.

License

GNU General Public License v3.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

baker_python-3.0.0.tar.gz (56.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

baker_python-3.0.0-py3-none-any.whl (40.1 kB view details)

Uploaded Python 3

File details

Details for the file baker_python-3.0.0.tar.gz.

File metadata

  • Download URL: baker_python-3.0.0.tar.gz
  • Upload date:
  • Size: 56.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for baker_python-3.0.0.tar.gz
Algorithm Hash digest
SHA256 127f8c343c867edf00337f4768dec1fd3d8c52edbf92954efa4ee09030f42d66
MD5 054f0f96ab2dd2234e8f92218ba96b0b
BLAKE2b-256 ad7fda77122289475083c412b0e6d33eea156a3c7fbde25b7e8d427e30a6099b

See more details on using hashes here.

File details

Details for the file baker_python-3.0.0-py3-none-any.whl.

File metadata

  • Download URL: baker_python-3.0.0-py3-none-any.whl
  • Upload date:
  • Size: 40.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for baker_python-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e3c7e1fb5dc8f9f3e9fd7f95efd7cfec1b50828ac12afc8d2900f61de1827efa
MD5 56037eb025622efd86304286d52e212e
BLAKE2b-256 7d872ca0c47a258877b426a15f0152543110a3bba28ce3633d92ddd142431082

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page