Build AI Apps with Python: Full-Featured CLI Agent — Tools Guardrails History | Episode 23
Video: Build AI Apps with Python: Full-Featured CLI Agent — Tools Guardrails History | Episode 23 by Taught by Celeste AI - AI Coding Coach
Watch full page →Build AI Apps with Python: Full-Featured CLI Agent — Tools, Guardrails, History
This example demonstrates how to build a command-line AI assistant in Python that integrates multiple tools, enforces input guardrails, and maintains conversation history. The agent supports math calculations, word definitions, and weather queries, while preventing unsafe requests from reaching the AI model.
Code
import sys
# Tool functions
def calculate(expression):
# Simple eval for math expressions (use cautiously in real apps)
try:
return str(eval(expression, {"__builtins__": {}}))
except Exception as e:
return f"Error calculating expression: {e}"
def define_word(word):
# Dummy dictionary lookup
definitions = {
"python": "A high-level programming language.",
"ai": "Artificial intelligence, the simulation of human intelligence by machines."
}
return definitions.get(word.lower(), "Definition not found.")
def get_weather(location):
# Placeholder weather info
return f"The weather in {location} is sunny and 75°F."
# Guardrail to block dangerous inputs
def guardrails(user_input):
blocked_keywords = ["rm -rf", "shutdown", "delete", "format", "drop table"]
for keyword in blocked_keywords:
if keyword in user_input.lower():
return False, f"Request blocked due to unsafe keyword: '{keyword}'"
return True, ""
# Conversation history storage
history = []
def main():
print("Welcome to the AI CLI Agent. Type 'quit' to exit.")
while True:
user_input = input("You: ").strip()
if user_input.lower() == "quit":
print("Goodbye!")
break
allowed, message = guardrails(user_input)
if not allowed:
print(f"Guardrails: {message}")
continue
# Check for tool usage commands
if user_input.startswith("calculate "):
expr = user_input[len("calculate "):]
response = calculate(expr)
elif user_input.startswith("define_word "):
word = user_input[len("define_word "):]
response = define_word(word)
elif user_input.startswith("get_weather "):
location = user_input[len("get_weather "):]
response = get_weather(location)
else:
# Default AI response placeholder
response = f"AI response to: {user_input}"
# Save to history
history.append({"user": user_input, "agent": response})
print(f"Agent: {response}")
if __name__ == "__main__":
main()
Key Points
- The agent uses separate tool functions to handle math, definitions, and weather queries.
- Input guardrails scan user input for dangerous commands and block them before processing.
- Conversation history is stored in a list to maintain context across turns.
- An interactive CLI loop lets users chat, call tools, and quit gracefully.
- This pattern combines multiple AI agent features into a cohesive terminal assistant.