A Knowledge-Based Agent is an AI system that uses an explicit Knowledge Base (KB) made up of facts and rules to analyze situations, derive conclusions and answers queries or take appropriate actions. Instead of reacting directly to input, a knowledge-based agent reasons about what it knows, updates beliefs when new information arrives and explains its decisions.
Components of Knowledge-Based Agents
A fully functional knowledge-based agent involves several key subsystems working together:

- Perception: Converts inputs into symbolic facts.
- Knowledge Base: Stores asserted facts & rules (domain knowledge).
- Inference Engine: Performs forward and backward chaining.
- Logical Representation: Propositional logic, first-order logic, semantic networks.
- Planner / Action Selector: Decides which action aligns with goals & derived knowledge.
- Belief Revision Module: Resolves contradictions using priority or truth maintenance.
- Explanation Module: Generates human-readable reasoning traces.
These systems are widely used in expert systems, diagnostics and intelligent assistants.
Knowledge Representation Types
Knowledge-based agents can be built using various representation paradigms:
- Propositional Logic: Represents knowledge using simple true/false statements. It’s fast and suitable for small, rule-based systems but limited in handling complex relationships.
- First-Order Logic (FOL): Extends propositional logic by including quantifiers, predicates and variables, allowing agents to represent relationships between objects. This makes it more expressive and flexible.
- Production Rules (IF–THEN): The most common form used in expert systems. Knowledge is represented as condition-action pairs, making reasoning straightforward through rule-based inference.
- Ontologies (RDF/OWL): Provide a standardized structure for representing knowledge that supports semantic interoperability hence helping different AI systems to share and interpret information consistently.
- Frames & Semantic Networks: Represent concepts as interconnected nodes in a graph-like structure, where relationships capture the meaning between entities. These are useful for visualizing and reasoning about conceptual hierarchies.
To know more about it refer to: Knowledge Representation Types
Inference Mechanisms
Inference is the reasoning process that derives conclusions from the KB.
- Forward Chaining: Starts from known facts and applies rules to derive new facts.
- Backward Chaining: Starts with a goal and tries to prove it using rules and subgoals.
- Resolution: Core inference method used in automated theorem proving.
- Unification: Matches patterns and variables in first-order logic.
- Constraint Propagation: Efficiently solves systems with constraints.
These mechanisms enable the agent to answer queries, generate new knowledge and perform goal-oriented reasoning.
Implementation
Let's build a simple agent to demonstrate how Knowledge based agents work.
Step 1: Define the Knowledge Base
A compact dictionary mapping each illness id to the set of symptom tokens it requires.
- Illness keys use snake_case (e.g., common_cold).
- Symptoms are tokens prefixed with symptom_ for consistent matching.
- Use a set for each illness so membership checks and intersections are fast.
KNOWLEDGE_BASE = {
"common_cold": {
"symptom_runny_nose",
"symptom_sneezing",
"symptom_sore_throat"
},
"influenza_flu": {
"symptom_fever",
"symptom_body_aches",
"symptom_cough",
"symptom_fatigue"
},
"seasonal_allergies": {
"symptom_sneezing",
"symptom_itchy_eyes",
"symptom_runny_nose"
},
"bronchitis": {
"symptom_cough",
"symptom_chest_discomfort",
"symptom_fatigue"
}
}
Step 2: Scoring-based Inference Engine
A function that compares user percepts to each illness’s symptom set and produces a ranked list.
- Intersects percepts with required symptoms to count matches.
- Calculates score as matched / total_required * 100.
- Excludes illnesses with zero matches and sorts results high-to-low.
def inference_engine(percepts, kb):
diagnosis_scores = {}
for illness, required_symptoms in kb.items():
matching_symptoms = required_symptoms.intersection(percepts)
match_count = len(matching_symptoms)
if match_count > 0:
total_symptoms_for_illness = len(required_symptoms)
score = (match_count / total_symptoms_for_illness) * 100
diagnosis_scores[illness] = score
sorted_diagnoses = sorted(diagnosis_scores.items(),
key=lambda item: item[1], reverse=True)
return sorted_diagnoses
Step 3: Agent Initialization
A class that holds the knowledge base and groups perception, inference and action methods.
- self.kb stores the provided KB so methods can access it.
- Class style makes it easy to extend with logging, sessions or APIs.
class SymptomCheckerAgent:
def __init__(self, knowledge_base):
self.kb = knowledge_base
Step 4: Perceive: Convert user input into KB tokens
Interactive prompt that normalizes free text into symptom tokens that match the KB.
- Lowercases, strips spaces and replaces spaces with underscores.
- Prefixes each cleaned token with symptom_.
- Returns a set of percept tokens.
def perceive(self):
print("Please enter your symptoms, separated by commas (e.g., fever, cough):")
user_input = input().lower()
symptoms = [s.strip() for s in user_input.split(',') if s.strip()]
percepts = set(f"symptom_{s.replace(' ', '_')}" for s in symptoms)
print(f"\n[Agent Perceived]: {percepts}")
return percepts
Step 5: Ask: Call the inference engine
Minimal wrapper that sends percepts to the inference engine and returns ranked diagnoses.
- Keeps the reasoning call separate from perception and output formatting.
- Easy place to add logging or telemetry later.
def ask(self, percepts):
print("[Agent Asking KB]: 'What do these symptoms mean?'")
diagnoses = inference_engine(percepts, self.kb)
return diagnoses
Step 6: Act: Present ranked results to the user
Formats and prints the sorted diagnoses with human-friendly labels and a short disclaimer.
- Converts illness ids to title case for readability.
- Shows percentage match rounded to whole numbers.
def act(self, diagnoses):
print("[Agent Acting]:")
if not diagnoses:
print("Based on my knowledge, your symptoms do not match any known illness patterns.")
else:
print("Based on your symptoms, here are the potential matches:")
for illness, score in diagnoses:
print(f"- {illness.replace('_', ' ').title()} ({score:.0f}% match)")
print("\n--- Please remember, this is not real medical advice! ---")
Step 7: Run: Single orchestration flow
One-line flow that runs perceive → ask → act in sequence.
- Simple entry point for interactive use or unit tests.
- Easy to convert into a loop, API handler or chatbot step.
def run(self):
percepts = self.perceive()
diagnoses = self.ask(percepts)
self.act(diagnoses)
Step 8: Start the Agent Workflow
Create the agent with the KB and run the single interaction when the script executes directly. Keeps module import safe for reuse in other code.
if __name__ == "__main__":
agent = SymptomCheckerAgent(KNOWLEDGE_BASE)
agent.run()
Output:
Importance
Knowledge-based agents play a crucial role in domains requiring structured reasoning, transparency and interpretability. They help AI systems “understand” context instead of memorizing patterns.
- Provide explainable and traceable decisions.
- Detect inconsistencies and update beliefs through revision mechanisms.
- Generalize rules to multiple scenarios without retraining.
- Support complex problem-solving such as diagnosis, planning and compliance.
- Enable dynamic query answering with logical inference instead of statistical correlations.
Limitations
- Rule creation is time-consuming and knowledge-intensive.
- Inference can be slow for large KBs.
- Difficult to handle noisy or ambiguous data.
- Advanced belief revision requires complex algorithms.