PHL EDU WITH AI — Agents Code Hub
AI Agents Complete
Code Library
Every working script from our AI Agents series — from beginner setup to a full personal assistant. 100% free, no login required.
مکمل AI Agents سیریز کا کوڈ لائبریری — اردو میں — بالکل مفت، کوئی سائن ان ضروری نہیں
🟢 Parts 1-5 — Development Foundation
Virtual Environment & Dependency Management
Show description ▼
Creates an isolated virtual environment and installs all critical AI and automation dependencies required for the series.
پراجیکٹ کے لیے علیحدہ ماحول (Virtual Environment) بنائیں اور تمام پیکجز انسٹال کریں۔
:: Windows Setup Command Script python -m venv ai_env call ai_env\Scripts\activate :: Core Dependencies Installation pip install --upgrade pip pip install ollama whisper sounddevice numpy requests pip install flask flask-socketio psutil schedule chromadb pip install beautifulsoup4 google-auth google-auth-oauthlib echo Setup Complete! Activate env using: ai_env\Scripts\activate
Ollama API Communication Wrapper
Show description ▼
A programmatic client module to handle direct asynchronous-style requests to local Ollama endpoints with raw JSON decoding.
مقامی اولاما ماڈل (Ollama) کے ساتھ براہ راست پائتھن کمیونیکیشن کوڈ۔
import requests, json def query_local_llm(prompt, model="llama3"): url = "http://localhost:11434/api/generate" payload = {"model": model, "prompt": prompt, "stream": False} try: response = requests.post(url, json=payload) if response.status_code == 200: return response.json().get("response", "") return f"Error: Server returned status {response.status_code}" except Exception as e: return f"Connection Failed: {str(e)}" if __name__ == "__main__": print(query_local_llm("Hello, confirm your model activation."))
Basic System Instruction Chat Loop
Show description ▼
A standalone interactive session framework matching prompt-engineered criteria with automatic terminal escape conditions.
سسٹم ہدایات پر مبنی پہلا کانٹیکسٹ اویئر مقامی چیٹ لوپ۔
import ollama SYSTEM = """You are a helpful AI agent. Respond in the same language the user uses. Be concise and accurate.""" def ask_agent(user_input): response = ollama.chat( model='llama3', messages=[ {'role': 'system', 'content': SYSTEM}, {'role': 'user', 'content': user_input} ] ) return response['message']['content'] print("🤖 Local Agent ready — type 'exit' to quit") while True: q = input("You: ") if q.lower() == 'exit': break print(f"Agent: {ask_agent(q)}\n")
🖥️ Parts 6-7 — Core Infrastructure (Free)
Whisper Voice Transcription Audio Module
Show description ▼
Captures microphone raw waveforms natively via SoundDevice and pipelines data into a local instance of OpenAI Whisper.
لوکل آواز ریکارڈنگ اور مائیکروفون ان پٹ ٹرانسکرپشن انجن۔
import whisper import sounddevice as sd import numpy as np model = whisper.load_model("base") def listen_once(duration=6, sr=16000): print(f"🎤 Listening for {duration}s...") audio = sd.rec( int(duration * sr), samplerate=sr, channels=1, dtype='float32' ) sd.wait() result = model.transcribe( audio.flatten(), language=None ) text = result["text"].strip() print(f"📝 Transcribed: {text}") return text if __name__ == '__main__': listen_once()
OS Process and Shell Subsystems Mapping
Show description ▼
Low-level programmatic system hooks utilizing subprocess layouts to execute browser triggers, diagnostic checks, and task automation.
ونڈوز کمانڈز، براؤزر اور پراسیس کنٹرول کرنے کا پائتھن ماڈیول۔
import os, webbrowser, subprocess, psutil def play_music(query): url = f"https://youtube.com/results?search_query={query.replace(' ','+')}" webbrowser.open(url) def power_action(action, minutes=0): secs = minutes * 60 win = os.name == 'nt' cmds = { "shutdown": f'shutdown /s /t {secs}' if win else f'sudo shutdown -h +{minutes}', "cancel": 'shutdown /a' if win else 'sudo shutdown -c' } if action in cmds: os.system(cmds[action]) def get_system_stats(): return {"cpu": psutil.cpu_percent(interval=1), "ram": psutil.virtual_memory().percent}
Login-Style Front-End UI Block Template
Show description ▼
A lightweight, reusable front-end form block for building your own local dashboards and demo interfaces.
اپنے لوکل ڈیش بورڈ کے لیے خوبصورت، ریسپونسیو لاگ ان فارم بلاک۔
<div style="font-family:Arial;background:#f0f2f5;padding:40px;text-align:center;border-radius:12px;color:#1c1e21"> <h2 style="color:#111;font-size:28px;font-weight:bold;margin-bottom:16px">My Local Agent</h2> <input type="text" placeholder="Username" style="width:100%;max-width:320px;padding:14px;margin-bottom:12px;border:1px solid #ddd;border-radius:6px"/> <br/> <input type="password" placeholder="Password" style="width:100%;max-width:320px;padding:14px;margin-bottom:16px;border:1px solid #ddd;border-radius:6px"/> <br/> <button style="width:100%;max-width:320px;padding:14px;background:#111;color:#fff;border:none;border-radius:6px;font-size:16px;font-weight:bold;cursor:pointer">Enter Dashboard</button> </div>
📚 AI Agents Guide Series — Read All 5 Parts
مکمل رہنمائی پانچ حصوں میں — ہر حصہ پڑھیں اور اپنے AI ایجنٹ خود بنائیں
⚡ Parts 8-10 — Advanced Agent Architecture (Free)
Unified Offline Speech Command Interpreter
Show description ▼
End-to-end local engine binding structural speech analysis data down into actionable operating commands processed strictly without network APIs.
آواز کی مدد سے مکمل کمپیوٹر آٹومیشن اور رن ٹائم ایگزیکیوشن انجن۔
import whisper, sounddevice as sd import numpy as np, ollama, os, webbrowser model = whisper.load_model("base") SYSTEM_RULE = "Analyze voice input. Respond ONLY with executable tokens: PLAY_MUSIC:[item] or SHUTDOWN:[min] or CHAT:[reply]" def voice_runtime_loop(): while True: input("[Press Enter to speak command]") rec = sd.rec(int(5 * 16000), samplerate=16000, channels=1, dtype='float32') sd.wait() raw_text = model.transcribe(rec.flatten())["text"] ctx = ollama.chat(model='llama3', messages=[ {'role':'system','content':SYSTEM_RULE}, {'role':'user','content':raw_text} ])['message']['content'] if "PLAY_MUSIC" in ctx: webbrowser.open(f"https://youtube.com/results?search_query={ctx.split(':')[1]}") elif "SHUTDOWN" in ctx: os.system("shutdown /s /t 60") else: print("Agent Speech Response:", ctx)
Persistent Local Memory Pipeline via ChromaDB
Show description ▼
Implements an ultra-low latency vector database engine locally to manage agent long-term history and prevent chat context loss across application boots.
کروم ڈی بی (ChromaDB) پر مبنی مستقل لانگ ٹرم میموری اسٹوریج انجن۔
import chromadb from chromadb.utils import embedding_functions chroma_client = chromadb.PersistentClient(path="./agent_brain") emb_fn = embedding_functions.DefaultEmbeddingFunction() memory_store = chroma_client.get_or_create_collection(name="knowledge", embedding_function=emb_fn) def remember_fact(fact_id, factual_content): memory_store.add(documents=[factual_content], ids=[fact_id]) def recall_relevant_context(query_text): results = memory_store.query(query_texts=[query_text], n_results=2) return " ".join([doc for sublist in results['documents'] for doc in sublist]) if __name__ == "__main__": remember_fact("usr_prop", "User runs phledu.com based in Pakistan.") print("Recalled Brain Context:", recall_relevant_context("Where is user blog hosted?"))
Targeted RAG Document Extractor
Show description ▼
Executes autonomous document mining and payload filtration via beautifulsoup hooks, piping pure markup strings into Ollama data ingestion frames.
ویب سائٹ ڈیٹا مائننگ اور لوکل ماڈل کانٹیکسٹ فیڈنگ انجن۔
import requests, ollama from bs4 import BeautifulSoup def scrape_and_summarize(target_url): try: headers = {'User-Agent': 'Mozilla/5.0'} html_data = requests.get(target_url, headers=headers, timeout=10).text soup = BeautifulSoup(html_data, 'html.parser') for script in soup(["script", "style"]): script.decompose() clean_text = " ".join(soup.get_text().split())[:4000] digest = ollama.chat(model='llama3', messages=[ {'role':'user', 'content':f"Provide a structured diagnostic technical summary: {clean_text}"} ])['message']['content'] return digest except Exception as e: return f"Scrape Execution Fault: {str(e)}"
Gmail IMAP Safe Automation Framework
Show description ▼
Binds directly to authorized Google OAuth tokens to structurally crawl incoming message pools and generate predictive response payloads locally.
آٹو میٹڈ جی میل اکاؤنٹ کراولنگ اور انٹیلیجنٹ ریپلائی جنریٹر ماڈیول۔
import imaplib, smtplib, ollama from email.mime.text import MIMEText def process_latest_unreads(user_mail, app_pass): mail = imaplib.IMAP4_SSL("imap.gmail.com") mail.login(user_mail, app_pass) mail.select("inbox") _, data = mail.search(None, 'UNSEEN') mail_ids = data[0].split() if not mail_ids: return "No unresolved inbound logs found." for target_id in mail_ids: _, msg_data = mail.fetch(target_id, '(RFC822)') raw_body = msg_data[0][1].decode('utf-8', errors='ignore') reply_draft = ollama.chat(model='llama3', messages=[ {'role':'user', 'content':f"Draft a formal support response payload for: {raw_body}"} ])['message']['content'] print("Generated Response Architecture:\n", reply_draft)
Flask Live Engine Microserver Core Architecture
Show description ▼
The core web engine runtime mapping system resources, operational endpoints, and asynchronous processing configurations inside a clean localized network array.
مرکزی کنٹرول ڈیش بورڈ پائتھن فلاسکر بیک اینڈ سرور کوڈ۔
from flask import Flask, render_template, request, jsonify import ollama, threading, webbrowser, time, psutil app = Flask(__name__) chat_history_state = [] @app.route('/') def index_root(): return "Dashboard Framework Online" @app.route('/api/chat', methods=['POST']) def process_dashboard_chat(): user_payload = request.get_json().get('message', '') chat_history_state.append({'role': 'user', 'content': user_payload}) llm_out = ollama.chat(model='llama3', messages=chat_history_state[-10:])['message']['content'] chat_history_state.append({'role': 'assistant', 'content': llm_out}) return jsonify({'reply': llm_out}) @app.route('/api/telemetry') def get_telemetry(): return jsonify({'cpu': psutil.cpu_percent(), 'ram': psutil.virtual_memory().percent}) if __name__ == '__main__': threading.Thread(target=lambda: (time.sleep(1), webbrowser.open('http://localhost:5000'))).start() app.run(host='0.0.0.0', port=5000)
Dark Theme Responsive Telemetry Dashboard Form
Show description ▼
High performance operational interface with built-in telemetry update pipes, reactive chat cells, and standalone operational layout fields.
براؤزر پر چلنے والے ڈارک تھیم انٹرفیس فرنٹ اینڈ ایچ ٹی ایم ایل کوڈ بلاک۔
<div style="background:#0d1220;color:#fff;padding:24px;font-family:sans-serif;border-radius:12px"> <div style="display:flex;justify-content:between;border-bottom:1px solid #141c2e;padding-bottom:12px"> <h3>🤖 System Agent Control</h3> <div>CPU: <span id="cpu">--</span>% | RAM: <span id="ram">--</span>%</div> </div> <div id="chat_view" style="height:200px;overflow-y:auto;padding:12px 0"></div> <div style="display:flex;gap:8px"> <input id="inp" type="text" placeholder="Issue action payload..." style="flex:1;padding:12px;border-radius:6px;background:#141c2e;color:#fff;border:none"/> <button onclick="dispatch()" style="padding:12px 24px;background:#00e5ff;color:#000;font-weight:bold;border:none;border-radius:6px;cursor:pointer">Send</button> </div> </div>
🆕 Parts 11-12 — Extended Agent Capabilities (Free)
Tool-Calling Agent Router
Show description ▼
A simple router that lets your local model decide which Python function to call (weather, calculator, time) based on the user’s request — the core pattern behind modern tool-using agents.
صارف کی درخواست کی بنیاد پر صحیح فنکشن (ٹول) خود بخود منتخب کرنے والا ایجنٹ راؤٹر۔
import ollama, json def calculator(expr): try: return str(eval(expr, {"__builtins__": {}})) except Exception as e: return f"Calc error: {e}" def get_time(): import datetime return datetime.datetime.now().strftime("%H:%M:%S") TOOLS = {"calculator": calculator, "get_time": get_time} ROUTER_PROMPT = """Choose one tool for this request. Reply ONLY as JSON: {"tool": "calculator"|"get_time"|"none", "arg": "..."}""" def run_agent(user_input): plan = ollama.chat(model='llama3', messages=[ {'role':'system','content':ROUTER_PROMPT}, {'role':'user','content':user_input} ])['message']['content'] try: parsed = json.loads(plan) tool = parsed.get("tool") if tool == "calculator": return calculator(parsed.get("arg","")) if tool == "get_time": return get_time() return "No matching tool — answering normally." except Exception: return plan
Telegram Bot Agent Bridge
Show description ▼
Connects your local Ollama agent to a Telegram bot so you can chat with your assistant from your phone, anywhere.
اپنے لوکل AI ایجنٹ کو Telegram بوٹ کے ذریعے موبائل سے چلانے کا کوڈ۔
import requests, ollama, time BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN" API = f"https://api.telegram.org/bot{BOT_TOKEN}" def get_updates(offset=None): params = {"timeout": 30, "offset": offset} return requests.get(f"{API}/getUpdates", params=params).json() def send_message(chat_id, text): requests.post(f"{API}/sendMessage", json={"chat_id": chat_id, "text": text}) def run_bot(): offset = None print("🤖 Telegram agent bridge running...") while True: updates = get_updates(offset).get("result", []) for u in updates: offset = u["update_id"] + 1 msg = u.get("message", {}) text, chat_id = msg.get("text"), msg.get("chat",{}).get("id") if text and chat_id: reply = ollama.chat(model='llama3', messages=[{'role':'user','content':text}])['message']['content'] send_message(chat_id, reply) time.sleep(1)
Local Vision Agent (Image Understanding)
Show description ▼
Sends a local image to a vision-capable Ollama model (like llava) and returns a description or answer — fully offline image understanding.
لوکل تصویر کو سمجھنے اور بیان کرنے والا AI Vision ایجنٹ (آفلائن)۔
import ollama def describe_image(image_path, question="Describe this image in detail."): response = ollama.chat( model='llava', messages=[{ 'role': 'user', 'content': question, 'images': [image_path] }] ) return response['message']['content'] if __name__ == "__main__": result = describe_image("sample.jpg", "What text or objects are visible?") print("👁️ Vision Agent:", result)
Scheduled Task Agent (Auto-Run on Time)
Show description ▼
Runs your agent automatically on a schedule — daily summaries, reminders, or recurring checks — using the lightweight schedule library.
مقررہ وقت پر ایجنٹ کو خودکار چلانے کے لیے شیڈولنگ کوڈ۔
import schedule, time, ollama def daily_summary_job(): reply = ollama.chat(model='llama3', messages=[ {'role':'user','content':"Give me a short motivational note to start my work day."} ])['message']['content'] print(f"🗓️ Daily Agent Note: {reply}") schedule.every().day.at("09:00").do(daily_summary_job) print("⏰ Scheduler running — waiting for 09:00 daily trigger...") while True: schedule.run_pending() time.sleep(30)
🌿 PHL EDU Eco System
ہمارے دیگر مفت ٹولز اور وسائل بھی دیکھیں
🔮 Upcoming Framework Architecture Updates
Multi-Agent Verification Framework
Research Pipeline
CrewAI pattern structuring multi-agent cross validation locally.
Localized Excel Log Auditor
Under Design
Automated CSV transaction classification parsing using Phi-3 hooks.
E2EE Local Network Sync
Planned Log
Encrypted network endpoints to safely pass action arrays over local Wi-Fi.
Frequently Asked Questions
اکثر پوچھے جانے والے سوالات
Is this AI Agents Code Hub completely free?
کیا یہ AI Agents Code Hub بالکل مفت ہے؟
Yes. Every script on this page — from setup scripts to voice, memory, and vision agents — is free to copy and use, with no sign-in or account required.
جی ہاں، اس صفحے پر موجود ہر کوڈ مکمل طور پر مفت ہے اور اسے استعمال کرنے کے لیے کسی سائن ان یا اکاؤنٹ کی ضرورت نہیں۔
Do these agents need an internet connection to run?
کیا ان ایجنٹس کو چلانے کے لیے انٹرنیٹ ضروری ہے؟
Most scripts run fully offline through a local Ollama model, except for optional features like web scraping, Gmail automation, or the Telegram bridge, which need internet access.
زیادہ تر اسکرپٹس مقامی Ollama ماڈل کے ذریعے مکمل آفلائن چلتے ہیں، سوائے ویب اسکریپنگ، جی میل آٹومیشن یا ٹیلیگرام بریج جیسے فیچرز کے جنہیں انٹرنیٹ درکار ہوتا ہے۔
Which Python libraries do I need before running these agents?
ان ایجنٹس کو چلانے کے لیے کون سی پائتھن لائبریریز درکار ہیں؟
Start with the Virtual Environment & Dependency Management script at the top of this page — it installs Ollama, Whisper, Flask, ChromaDB, and every other package used across the series in one step.
اس صفحے کے سب سے اوپر موجود Virtual Environment اسکرپٹ استعمال کریں، یہ تمام ضروری پیکجز ایک ہی مرحلے میں انسٹال کر دیتی ہے۔
Where can I learn more free AI skills after this?
اس کے بعد مزید مفت AI مہارتیں کہاں سے سیکھی جا سکتی ہیں؟
Visit our AI Tools hub for more free bilingual AI resources, or read the full AI Agents Guide Series linked above for a step-by-step explanation of every script on this page.
مزید مفت بلنگول AI وسائل کے لیے ہمارا AI Tools صفحہ دیکھیں، یا اوپر دیے گئے AI Agents Guide Series پڑھیں۔
