Loading repository dataβ¦
Loading repository dataβ¦
zyanshykh / repository
π AI-Native Development (Python) AI-Native Development demonstrates how modern software is built with AI as the core compute layer. This repository focuses on building AI agents, tool-calling workflows, and memory-driven systems using Python, inspired by Sir Zia Khanβs AI-Native vision.
Format for each chapter
YOUR_API_KEY)Concept summary: AI is the new compute layer β give instructions and AI executes.
Learning objectives
Python Practical β Basic chat + calculator
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role":"system","content":"You are a helpful math engine."},
{"role":"user","content":"Calculate 143 * 27 and show steps in one line."}
]
)
print(resp.choices[0].message["content"])
Mini project: CLI "Task Executor" that accepts 3 user instructions and prints results.
Tests & success criteria: All tasks return plausible, correct outputs (e.g., math matches local calc).
Concept summary: Treat LLMs as a callable service (IaaS). Focus on delegation design.
Learning objectives
Python Practical β Planner -> Executor -> Verifier
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")
# Planner
planner = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role":"system","content":"You are a planner."},
{"role":"user","content":"Create a 3-step study plan for 7 days for AI-Native book."}]
)
plan = planner.choices[0].message["content"]
# Executor
exec_resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role":"system","content":"You are an executor."},
{"role":"user","content": f"Execute step 1 from this plan:\n{plan}"}]
)
print("PLAN:\n", plan)
print("EXECUTION:\n", exec_resp.choices[0].message["content"])
Mini project: Build a planner.py that accepts a task and returns a 3-step plan and executes step 1.
Tests: The planner must produce ordered actionable steps; executor must output a concrete result for step 1.
Concept summary: Design agents (goal + tools + memory + planner). Create role-based agents.
Learning objectives
Python Practical β Function calling
from openai import OpenAI
import json
client = OpenAI(api_key="YOUR_API_KEY")
def greet(name):
return f"Hello {name}, welcome to AI-native development!"
functions = [{
"name":"greet",
"description":"Greet the user by name",
"parameters":{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}
}]
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role":"system","content":"You call functions when asked."},
{"role":"user","content":"Say hello to Zyan."}],
functions=functions,
function_call="auto"
)
msg = resp.choices[0].message
if msg.get("function_call"):
fn_name = msg["function_call"]["name"]
args = json.loads(msg["function_call"]["arguments"])
if fn_name == "greet":
print(greet(**args))
Mini project: Create a small tools.py (todo add/list, calc) and let the agent pick which tool to call.
Tests: The agent should correctly parse and call local tools based on the user request.
Concept summary: Prompts are architecture β system + user + example flows.
Learning objectives
Python Practical β Prompt template utility
PROMPT_TEMPLATE = '''System: You are a concise assistant.
Constraints: Answer in <=50 words.
Example Q: How to learn fast?\nA: Build projects daily.\n
User: {question}
'''
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")
q = "Give a 2-step plan to revise the AI-Native book in 7 days."
resp = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role":"user","content":PROMPT_TEMPLATE.format(question=q)}])
print(resp.choices[0].message["content"])
Mini project: Build a prompt_builder.py that takes role, constraints, examples and returns the final prompt.
Tests: Different constraints change output length/style predictably.
Concept summary: Use embeddings + vector DB for recall; RAG grounds LLMs.
Learning objectives
Python Practical β Simple in-memory embeddings + retrieval
import numpy as np
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")
def embed(text):
r = client.embeddings.create(model="text-embedding-3-small", input=text)
return np.array(r.data[0].embedding)
memory = []
def store(text):
memory.append({"text":text, "emb": embed(text)})
def retrieve(query, k=3):
qv = embed(query)
sims = []
for i,item in enumerate(memory):
sim = float(np.dot(qv, item['emb'])/(np.linalg.norm(qv)*np.linalg.norm(item['emb'])))
sims.append((sim, item['text']))
sims.sort(reverse=True)
return [t for _,t in sims[:k]]
# usage
store("Zyan prepares for December hackathon.")
store("Zyan likes Python and Next.js.")
print(retrieve("What does Zyan like?"))
Mini project: Persist embeddings to disk (JSON+binary) and query them.
Tests: Retrieval returns semantically relevant docs for test queries.
Concept summary: Tools allow LLMs to act on the world (APIs, FS, DB, shell).
Learning objectives
Python Practical β Safe tool wrapper (mock)
import json
def safe_call_tool(name, args):
# Example safety: block destructive commands
destructive = ['delete_all_files', 'format_disk']
if name in destructive:
return "TOOL BLOCKED: destructive"
# Mock tool execution
return f"Executed {name} with {json.dumps(args)}"
print(safe_call_tool('todo_add', {'task':'Finish Chapter 2'}))
Mini project: Build tools.py with 4 tools (calc, todo add/list, read_file, mock_http_get) and integrate with function-calling.
Tests: Tools must enforce safety checks and produce logs (JSONL).
Concept summary: Break concerns across specialized agents to scale complexity.
Learning objectives
Python Practical β Very small orchestrator
# Pseudocode style simplified orchestrator
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")
def search_agent(query):
return f"Search results for {query} (mock)"
def exec_agent(instruction):
return f"Executed: {instruction}"
# Orchestrator
query = "Find AI-native hackathon project ideas"
results = search_agent(query)
final = exec_agent("Pick top idea and make 3-step plan.")
print(results)
print(final)
Mini project: Implement 3 agents (plan, search, execute) with a simple JSON-based message bus (file or in-memory queue).
Tests: Orchestrator must show message logs and final aggregated result.
Concept summary: Always verify claims; add human-in-loop for critical tasks.
Learning objectives
Python Practical β Verifier pattern
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")
answer = "The capital of France is Paris."
verification_prompt = f"Verify: '{answer}' Give sources or say 'I don't know'."
ver = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role":"user","content":verification_prompt}])
print(ver.choices[0].message['content'])
Mini project: Add a verification layer that marks answers as CONFIRMED / SUSPECT and posts SUSPECT items for human review.
Tests: Known factual QAs should return CONFIRMED; made-up facts should return SUSPECT or 'I don't know.'
Concept summary: Deploy agents as cloud functions or serverless workflows.
Learning objectives
requirements.txt.Python Practical β Dockerfile snippet & run
# Dockerfile (example)
# FROM python:3.11-slim
# WORKDIR /app
# COPY . /app
# RUN pip install -r requirements.txt
# ENV OPENAI_API_KEY=""
# CMD ["python","agent.py"]
Mini project: Dockerize your agent.py and run locally; measure latency and memory.
Tests: Container starts and agent responds to a sample request.
Concept summary: Logs, traces, and metrics are critical to debug and improve agents.
Learning objectives
Python Practical β JSONL logger
import time, json
def log_event(path, record):
record['ts'] = time.time()
with open(path, 'a') as f:
f.write(json.dumps(record)+"\n")
log_event('logs.jsonl', {'event':'plan','plan':'step1...','tokens':120})
Mini project: Integrate logging into your agent and produce a short dashboard (CLI summary) of last 10 events.
Tests: Logs contain consistent records for each request and tool call.
Concept summary: Design interactions where user confirmations are required for sensitive steps.
Learning objectives
Python Practical β Confirmation wrapper
def confirm_and_execute(action_desc, fn, *args, confirm=True):
print("Action:", action_desc)
if confirm:
ok = input("Type YES to proceed: ")
if ok.strip().upper() != 'YES':
return 'CANCELLED'
return fn(*args)
# example
print(confirm_and_execute('Delete account', lambda: 'deleted', confirm=False))
Mini project: Add confirmation flow to any destructive tool (e.g., delete todo).
Tests: Actions with confirm=True must stop until user types YES.
Concept summary: Handle PII with care; design redaction & minimization.
Learning objectives
Python Practical β Simple redaction
import re
def redact(text):
text = re.sub(r"\b\d{10,}\b", "[REDACTED]", text) # naive phone
text = re.sub(r"\b\S+@\S+\b", "[REDACTED]", text) # naive email
return text
print(redact("Call me at 03123456789 or email z@x.com"))
Mini project: Implement a middleware that redacts PII before logging or sending to LLM.
Tests: PII is replaced in logs and outgoing prompts.
Concept summary: Balance quality vs token cost & latency; caching and chunking strategies.
Learning objectives
Python Practical β Simple cache for embeddings
import hashlib, json
def cache_key(text):
return hashlib.sha256(text