求面向主体编程(Agent Oriented Programming)演示示例代码链接
Hey there! I totally get how tricky it can be to find practical, multi-language examples that highlight the core ideas of Agent Oriented Programming (AOP). Let’s break this down with simple, runnable snippets in three common languages that showcase the key pillars of AOP: autonomous agents, goal-driven behavior, and inter-agent communication.
First, a quick recap of AOP's core principles we'll be demonstrating:
- Autonomy: Agents make decisions based on their internal state without external control
- Communication: Agents interact by sending/receiving messages (like tasks or requests)
- Reactivity: Agents respond to changes in their environment (like new tasks)
Python Example: Basic Task Agents
This uses classes to model agents that can accept tasks, execute them, and communicate with other agents.
class TaskAgent: def __init__(self, name): self.name = name self.current_task = None self.is_busy = False def receive_task(self, task, sender=None): if not self.is_busy: self.current_task = task self.is_busy = True print(f"[{self.name}] Received task: {task} from {sender.name if sender else 'unknown'}") self.execute_task() else: print(f"[{self.name}] Busy, cannot accept new task: {task}") def execute_task(self): # Simulate task execution (replace with real logic) print(f"[{self.name}] Executing task: {self.current_task}") self.is_busy = False self.current_task = None print(f"[{self.name}] Task completed!") # Demo agent interaction agent_alice = TaskAgent("Alice") agent_bob = TaskAgent("Bob") agent_alice.receive_task("Process user data", agent_bob) agent_bob.receive_task("Generate performance report", agent_alice) agent_alice.receive_task("Validate report results", agent_bob) # Alice is busy initially, then accepts after completion
JavaScript Example: Async Task Agents
JavaScript's async/await is perfect for simulating agents that handle asynchronous tasks (like API calls or I/O operations).
class TaskAgent { constructor(name) { this.name = name; this.currentTask = null; this.isBusy = false; } async receiveTask(task, sender) { if (!this.isBusy) { this.currentTask = task; this.isBusy = true; console.log(`[${this.name}] Received task: "${task}" from ${sender ? sender.name : "unknown"}`); await this.executeTask(); } else { console.log(`[${this.name}] Busy, cannot accept new task: "${task}"`); } } async executeTask() { // Simulate async work (e.g., fetching data, processing files) await new Promise(resolve => setTimeout(resolve, 1000)); console.log(`[${this.name}] Finished executing task: "${this.currentTask}"`); this.isBusy = false; this.currentTask = null; } } // Demo concurrent agent behavior const agent_charlie = new TaskAgent("Charlie"); const agent_diana = new TaskAgent("Diana"); agent_charlie.receiveTask("Fetch real-time weather data", agent_diana); agent_diana.receiveTask("Update dashboard with weather stats", agent_charlie); // Send a follow-up task once Charlie is free setTimeout(() => agent_charlie.receiveTask("Analyze weather trend patterns", agent_diana), 1500);
Java Example: Threaded Task Agents
Java's threading model lets us create agents that run concurrently, mimicking real-world autonomous entities.
class TaskAgent implements Runnable { private final String name; private String currentTask; private boolean isBusy; private final Object lock = new Object(); public TaskAgent(String name) { this.name = name; this.isBusy = false; new Thread(this).start(); // Launch agent's thread } public void receiveTask(String task, TaskAgent sender) { synchronized (lock) { if (!isBusy) { this.currentTask = task; this.isBusy = true; System.out.printf("[%s] Received task: \"%s\" from %s%n", name, task, sender != null ? sender.name : "unknown"); lock.notify(); // Wake up the agent's thread to execute the task } else { System.out.printf("[%s] Busy, cannot accept new task: \"%s\"%n", name, task); } } } @Override public void run() { while (true) { synchronized (lock) { while (!isBusy) { try { lock.wait(); // Wait for a new task } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } // Execute the task System.out.printf("[%s] Executing task: \"%s\"%n", name, currentTask); try { Thread.sleep(1000); // Simulate work duration } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } System.out.printf("[%s] Task completed: \"%s\"%n", name, currentTask); isBusy = false; currentTask = null; } } } public static void main(String[] args) { TaskAgent agent_eve = new TaskAgent("Eve"); TaskAgent agent_frank = new TaskAgent("Frank"); agent_eve.receiveTask("Process customer payment", agent_frank); agent_frank.receiveTask("Send payment confirmation receipt", agent_eve); agent_eve.receiveTask("Verify transaction integrity", agent_frank); // Eve is busy until first task finishes } }
Each of these examples hits the core of AOP:
- Agents are independent entities with their own state (
is_busy,current_task) - They communicate by sending messages (
receive_taskmethod) - They act autonomously to fulfill their goals (executing tasks without external direction)
内容的提问来源于stack exchange,提问作者Alphas Supremum




