100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.
feat: Add AG-UI frontend for Negotiation Battle Simulator
awesomekoder5bda40ddb4e7
diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/.env.example b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/.env.exampleindex fa5e7aa0..69f45874 100644--- a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/.env.example+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/.env.example@@ -1,2 +1,5 @@-# Get your API key from https://aistudio.google.com/+# Backend (Python)GOOGLE_API_KEY=your_google_ai_studio_key_here++# Frontend (Next.js) - optional, defaults to localhost:8000+AGENT_URL=http://localhost:8000/diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/README.md b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/README.mdindex 8760a122..b7adc9b8 100644--- a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/README.md+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/README.md@@ -1,234 +1,219 @@# ๐ฎ AI Negotiation Battle Simulator-### A Real-Time Agent vs Agent Showdown!+### A Real-Time Agent vs Agent Showdown with AG-UI!-Watch two AI agents battle it out in an epic used car negotiation! One agent desperately wants that sweet 2019 Honda Civic, the other is determined to squeeze every last dollar. Who will crack first? ๐๐ฐ+Watch two AI agents battle it out in an epic used car negotiation! Built with **Google ADK** for the backend agents and **AG-UI + CopilotKit** for a jaw-dropping reactive frontend.++++## โจ Features-- **๐ค Dual AI Agents**: Buyer vs Seller with distinct personalities and strategies-- **๐ A2A Protocol Ready**: Demonstrates Google's Agent-to-Agent protocol for cross-agent communication-- **๐ Live Negotiation Tracking**: Watch offers, counteroffers, and dramatic moments unfold-- **๐ญ Configurable Personalities**: From "Desperate First-Time Buyer" to "Ruthless Used Car Dealer"-- **๐ฌ Dramatic Scenarios**: Pre-built scenarios with backstories and stakes+- **๐ค Dual AI Agents**: Buyer vs Seller with distinct personalities and negotiation strategies+- **๐ AG-UI Protocol**: Real-time streaming of agent actions, tool calls, and state changes+- **๐ Jaw-Dropping UI**: Animated battle arena with live negotiation timeline+- **๐ญ 8 Unique Personalities**: 4 buyers + 4 sellers with different negotiation styles+- **๐ Generative UI**: Custom React components render tool calls in real-time+- **๐ Shared State**: Agent state syncs bidirectionally with the frontend## ๐๏ธ Architecture```-โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-โ Streamlit UI โ-โ Buyer Panel โ Timeline โ Seller Panel โ-โโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโ- โ โ- โผ โผ-โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ-โ Buyer Agent โโโโโโโโโโโบโ Seller Agent โ-โ (Google ADK) โ A2A/ โ (Google ADK) โ-โ โ Direct โ โ-โ โข Budget: $12k โ โ โข Min: $14k โ-โ โข Strategy: ๐ฏ โ โ โข Strategy: ๐ฐ โ-โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ- โ โ- โโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ- โผ- โโโโโโโโโโโโโโโโโโโ- โ Orchestrator โ- โ (Manages Flow) โ- โโโโโโโโโโโโโโโโโโโ+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+โ Next.js + CopilotKit Frontend โ+โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โ+โ โ Battle Arenaโ โ VS Display โ โChat Sidebar โ โ+โ โ Timeline โ โ Buyer/Seller โ โ (AG-UI) โ โ+โ โโโโโโโโฌโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโฌโโโโโโโ โ+โโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโ+ โ AG-UI Events โ+ โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโ+ โ+ โโโโโโโโโโโโโผโโโโโโโโโโโโ+ โ CopilotKit Runtime โ+ โ (/api/copilotkit) โ+ โโโโโโโโโโโโโฌโโโโโโโโโโโโ+ โ HTTP/SSE+ โโโโโโโโโโโโโผโโโโโโโโโโโโ+ โ FastAPI + AG-UI โ+ โ ADK Middleware โ+ โโโโโโโโโโโโโฌโโโโโโโโโโโโ+ โ+ โโโโโโโโโโโโโผโโโโโโโโโโโโ+ โ ADK Negotiation Agent โ+ โ (Battle Master) โ+ โ โ+ โ Tools: โ+ โ โข configure_negotiationโ+ โ โข start_negotiation โ+ โ โข buyer_make_offer โ+ โ โข seller_respond โ+ โโโโโโโโโโโโโโโโโโโโโโโโโโ```## ๐ Quick Start+### Prerequisites++- Python 3.11++- Node.js 18++- Google AI API Key ([Get one here](https://aistudio.google.com/))+### 1. Clone and Navigate+```bashgit clone https://github.com/Shubhamsaboo/awesome-llm-apps.gitcd advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator```-### 2. Install Dependencies-```bash-pip install -r requirements.txt-```+### 2. Set Up Backend-### 3. Set Up Environment-Create a `.env` file:```bash-GOOGLE_API_KEY=your_google_ai_studio_key_here-```+cd backend+pip install -r requirements.txt-Get your API key from [Google AI Studio](https://aistudio.google.com/)+# Create .env file+echo "GOOGLE_API_KEY=your_api_key_here" > .env-### 4. Run the Battle!-```bash-streamlit run negotiation_app.py+# Start the backend+python agent.py```-## ๐ญ The Scenario: "The Craigslist Showdown"--**THE CAR**: 2019 Honda Civic EX, 45,000 miles, one owner, minor scratch on bumper+The backend will start on `http://localhost:8000`-**THE BUYER** ๐ฏ:-- Recently graduated, needs reliable car for new job-- Has exactly $12,500 saved (with $500 emergency buffer)-- Found 3 similar cars online priced $13,000-$16,000-- *Secret*: Job starts Monday. Desperately needs a car.+### 3. Set Up Frontend-**THE SELLER** ๐ฐ:-- Upgrading to an SUV, needs to sell the Civic first-- Paid $22,000 new, KBB says $14,500 private party-- Has one other interested buyer coming tomorrow-- *Secret*: The other buyer is flaky and might not show.+```bash+cd frontend+npm install-**THE STAKES**: Both have secrets. Both have pressure. Only one deal can be made.+# Start the frontend+npm run dev+```-## โ๏ธ Configuration Options+The frontend will start on `http://localhost:3000`-### Negotiation Settings+### 4. Start Negotiating! ๐ฎ-| Setting | Options | Description |-|---------|---------|-------------|-| **Buyer Strategy** | Aggressive, Balanced, Patient | How pushy the buyer is |-| **Seller Strategy** | Firm, Flexible, Desperate | How willing to negotiate |-| **Max Rounds** | 3-15 | How many back-and-forths before walkaway |-| **Initial Offer** | % of asking | Where buyer starts |-| **Drama Level** | ๐ญ to ๐ญ๐ญ๐ญ | How theatrical the agents get |+Open `http://localhost:3000` and tell the Battle Master:+- "Start a negotiation for a used car"+- "Show me available scenarios"+- "Use Desperate Dan as buyer and Shark Steve as seller"-### Preset Personalities+## ๐ญ Personalities-**Buyers:**-- ๐ฐ *Desperate Dan* - Needs car TODAY, weak poker face-- ๐งฎ *Analytical Alex* - Cites every data point, very logical-- ๐ *Cool-Hand Casey* - Master of the walkaway bluff-- ๐ค *Fair-Deal Fran* - Just wants a win-win+### Buyers+| Personality | Emoji | Style |+|-------------|-------|-------|+| Desperate Dan | ๐ฐ | Needs car TODAY, weak poker face |+| Analytical Alex | ๐งฎ | Cites every data point, very logical |+| Cool-Hand Casey | ๐ | Master of the walkaway bluff |+| Fair-Deal Fran | ๐ค | Just wants a win-win |-**Sellers:**-- ๐ฆ *Shark Steve* - Never drops more than 5%, take it or leave it-- ๐ *By-The-Book Beth* - Goes strictly by KBB, reasonable but firm-- ๐ *Motivated Mike* - Really needs to sell, more flexible-- ๐ญ *Drama Queen Diana* - Everything is "my final offer" (it's not)+### Sellers+| Personality | Emoji | Style |+|-------------|-------|-------|+| Shark Steve | ๐ฆ | Never drops more than 5% |+| By-The-Book Beth | ๐ | Goes strictly by KBB |+| Motivated Mike | ๐ | Really needs to sell |+| Drama Queen Diana | ๐ญ | Everything is "final offer" |## ๐ Project Structure```ai_negotiation_battle_simulator/-โโโ README.md # This file-โโโ requirements.txt # Dependencies-โโโ .env.example # Environment template-โโโ negotiation_app.py # Main Streamlit application-โโโ agents/-โ โโโ __init__.py-โ โโโ buyer_agent.py # Buyer agent with negotiation tools-โ โโโ seller_agent.py # Seller agent with pricing tools-โ โโโ orchestrator.py # Manages negotiation flow-โโโ config/-โ โโโ __init__.py-โ โโโ personalities.py # Agent personality presets-โ โโโ scenarios.py # Negotiation scenarios-โโโ utils/- โโโ __init__.py- โโโ negotiation_state.py # State management+โโโ README.md+โโโ .env.example+โ+โโโ backend/ # Python ADK + AG-UI+โ โโโ agent.py # Main agent with tools+โ โโโ requirements.txt+โ โโโ config/+โ โ โโโ personalities.py # 8 unique personalities+โ โ โโโ scenarios.py # 3 negotiation scenarios+โ โโโ agents/+โ โโโ buyer_agent.py+โ โโโ seller_agent.py+โ โโโ orchestrator.py+โ+โโโ frontend/ # Next.js + CopilotKit+ โโโ package.json+ โโโ src/+ โ โโโ app/+ โ โโโ layout.tsx # CopilotKit provider+ โ โโโ page.tsx # Battle Arena UI+ โ โโโ globals.css # Battle animations+ โ โโโ api/+ โ โโโ copilotkit/+ โ โโโ route.ts # CopilotKit runtime+ โโโ tailwind.config.js```-## ๐ A2A Protocol Mode (Advanced)+## ๐ฌ Sample Battle-For true cross-process agent communication, you can run agents as separate A2A servers:--### Terminal 1: Start Seller Agent-```bash-python -m agents.seller_agent --port 8001```--### Terminal 2: Start Buyer Agent-```bash-python -m agents.buyer_agent --port 8002-```--### Terminal 3: Run Orchestrator-```bash-python -m agents.orchestrator --buyer-url http://localhost:8002 --seller-url http://localhost:8001-```--## ๐ฌ Sample Negotiation--```-๐ NEGOTIATION BEGINS: 2019 Honda Civic EX+๐ NEGOTIATION BEGINS: 2019 Honda Civic EX๐ ASKING PRICE: $15,500-โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ--๐ฏ BUYER (Round 1):-"I've done my research - KBB shows similar Civics at $13,500.-Given the scratch on the bumper and the 45k miles, I'm prepared-to offer $11,500 cash today."+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-๐ฐ SELLER (Round 1):-"I appreciate the offer, but this Civic has been meticulously-maintained. Single owner, all service records. That KBB price-is for good condition - this is excellent. I could come down-to $15,000."+๐ COOL-HAND CASEY (Round 1):+"I've seen similar Civics go for less. $11,500 seems fair+given the market. Cash in hand today."-๐ฏ BUYER (Round 2):-"Look, I can see it's been well cared for, and I want to make-this work. But $15k is still above market. I can stretch to-$12,500 - that's my absolute max as a recent grad."+๐ฆ SHARK STEVE (Round 1):+"$15,000. This car is pristine. I've got two other+interested buyers coming this weekend."-๐ฐ SELLER (Round 2):-*pauses* "I've got another buyer coming tomorrow who seemed-very interested... but I'd rather close this today. $14,000-and it's yours."+๐ COOL-HAND CASEY (Round 2):+"$12,500 is my limit. Take it or I walk."-๐ฏ BUYER (Round 3):-"I hear you on the other buyer. Let me be straight with you --I start a new job Monday and I really need reliable transport.-$13,000 and I'll throw in taking it as-is, no inspection."+๐ฆ SHARK STEVE (Round 2):+*considers* "$14,000. Final offer."-๐ฐ SELLER (Round 3):-*considers* "You seem like someone who'll take care of her.-$13,500, I'll include the winter floor mats I was going to keep,-and we have a deal."+๐ COOL-HAND CASEY (Round 3):+"$13,000. Meet me in the middle."-๐ฏ BUYER (Round 4):-"$13,250 - right in the middle. Final offer. I've got cash ready."+๐ฆ SHARK STEVE (Round 3):+"...$13,500 and you've got a deal."-๐ฐ SELLER (Round 4):-"...You drive a hard bargain. Deal. ๐ค"+๐ COOL-HAND CASEY (Round 4):+"$13,250. Final answer."-โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+๐ฆ SHARK STEVE (Round 4):+"Deal. ๐ค"-โ DEAL CLOSED AT $13,250+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-๐ RESULTS:-โข Buyer saved: $2,250 (14.5% off asking)-โข Seller achieved: $13,250 (91% of asking, above KBB)-โข Rounds: 4-โข Winner: BOTH (True win-win! ๐)+โ DEAL CLOSED AT $13,250 ๐+ Buyer saved: $2,250 (14.5% off asking)```## ๐ง How It Works-1. **Scenario Loading**: The negotiation context (car details, buyer/seller situations) is loaded-2. **Agent Initialization**: Both agents receive their private information and strategies-3. **Turn-Based Negotiation**:- - Buyer makes offer with reasoning- - Seller evaluates and responds- - Process repeats until deal or walkaway-4. **State Tracking**: All offers, counteroffers, and reasoning are logged-5. **Outcome Determination**: Deal, walkaway, or max rounds reached+1. **User Request**: You tell the Battle Master what kind of negotiation to run+2. **Configuration**: The agent sets up the scenario and personalities+3. **Tool Calls**: The agent alternates between `buyer_make_offer` and `seller_respond` tools+4. **AG-UI Streaming**: Each tool call streams to the frontend via AG-UI protocol+5. **Generative UI**: Custom React components render each offer/response beautifully+6. **Shared State**: The negotiation timeline updates in real-time+7. **Outcome**: Deal or no-deal is celebrated with animations!++## ๐ Learn More++- [Google ADK Documentation](https://google.github.io/adk-docs/)+- [AG-UI Protocol Docs](https://docs.ag-ui.com/)+- [CopilotKit Documentation](https://docs.copilotkit.ai/)## ๐ค ContributingFeel free to add:- New negotiation scenarios (salary, apartment, contracts)- Additional personality types-- Enhanced UI visualizations-- Cross-framework agent support (LangChain, CrewAI)--## ๐ Learn More--- [Google ADK Documentation](https://google.github.io/adk-docs/)-- [A2A Protocol Specification](https://a2a-protocol.org/)-- [AG-UI Protocol](https://docs.ag-ui.com/)+- More dramatic UI effects+- Cross-framework agents (LangChain, CrewAI via A2A)---diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/.env.example b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/.env.examplenew file mode 100644index 00000000..fa5e7aa0--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/.env.example@@ -0,0 +1,2 @@+# Get your API key from https://aistudio.google.com/+GOOGLE_API_KEY=your_google_ai_studio_key_herediff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agent.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agent.pynew file mode 100644index 00000000..a0774534--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agent.py@@ -0,0 +1,443 @@+"""+AI Negotiation Battle Simulator - Backend Agent++This module creates an ADK agent wrapped with AG-UI middleware for+real-time negotiation between AI buyer and seller agents.+"""++import os+from typing import Optional+from dotenv import load_dotenv++from google.adk.agents import LlmAgent+from google.adk.tools import FunctionTool, ToolContext+from fastapi import FastAPI+from fastapi.middleware.cors import CORSMiddleware+from ag_ui_adk import ADKAgent, add_adk_fastapi_endpoint++from config.scenarios import SCENARIOS, get_scenario+from config.personalities import (+ BUYER_PERSONALITIES,+ SELLER_PERSONALITIES,+ get_personality_prompt+)++# Load environment variables+load_dotenv()+++# ============================================================================+# NEGOTIATION STATE (shared between tools)+# ============================================================================++class NegotiationState:+ """Tracks the state of the negotiation."""+ def __init__(self):+ self.reset()++ def reset(self):+ self.scenario_id = "craigslist_civic"+ self.buyer_personality = "cool_hand_casey"+ self.seller_personality = "by_the_book_beth"+ self.rounds = []+ self.current_round = 0+ self.status = "setup" # setup, negotiating, deal, no_deal+ self.final_price = None+ self.buyer_budget = 13000+ self.seller_minimum = 12500+ self.asking_price = 15500++# Global state+negotiation_state = NegotiationState()+++# ============================================================================+# NEGOTIATION TOOLS+# ============================================================================++def configure_negotiation(+ scenario_id: str = "craigslist_civic",+ buyer_personality: str = "cool_hand_casey",+ seller_personality: str = "by_the_book_beth",+ tool_context: Optional[ToolContext] = None+) -> dict:+ """+ Configure the negotiation scenario and personalities.++ Args:+ scenario_id: The scenario to use (craigslist_civic, vintage_guitar, apartment_sublet)+ buyer_personality: Buyer's personality (desperate_dan, analytical_alex, cool_hand_casey, fair_deal_fran)+ seller_personality: Seller's personality (shark_steve, by_the_book_beth, motivated_mike, drama_queen_diana)++ Returns:+ Configuration summary+ """+ scenario = get_scenario(scenario_id)++ negotiation_state.reset()+ negotiation_state.scenario_id = scenario_id+ negotiation_state.buyer_personality = buyer_personality+ negotiation_state.seller_personality = seller_personality+ negotiation_state.asking_price = scenario["asking_price"]+ negotiation_state.buyer_budget = scenario["buyer_budget"]+ negotiation_state.seller_minimum = scenario["seller_minimum"]+ negotiation_state.status = "ready"++ buyer_p = BUYER_PERSONALITIES[buyer_personality]+ seller_p = SELLER_PERSONALITIES[seller_personality]++ return {+ "status": "configured",+ "scenario": {+ "title": scenario["title"],+ "item": scenario["item"]["name"],+ "asking_price": scenario["asking_price"],+ "fair_market_value": scenario["fair_market_value"]+ },+ "buyer": {+ "name": buyer_p["name"],+ "emoji": buyer_p["emoji"],+ "budget": scenario["buyer_budget"]+ },+ "seller": {+ "name": seller_p["name"],+ "emoji": seller_p["emoji"],+ "minimum": scenario["seller_minimum"]+ }+ }+++def start_negotiation(tool_context: Optional[ToolContext] = None) -> dict:+ """+ Start the negotiation battle!++ Returns:+ Initial negotiation state and instructions+ """+ if negotiation_state.status != "ready":+ return {"error": "Please configure the negotiation first using configure_negotiation"}++ scenario = get_scenario(negotiation_state.scenario_id)+ negotiation_state.status = "negotiating"+ negotiation_state.current_round = 1++ return {+ "status": "started",+ "round": 1,+ "scenario": scenario["title"],+ "item": scenario["item"]["name"],+ "asking_price": scenario["asking_price"],+ "message": f"๐ NEGOTIATION BEGINS! The battle for the {scenario['item']['name']} is ON!"+ }+++def buyer_make_offer(+ offer_amount: int,+ message: str,+ reasoning: str = "",+ tool_context: Optional[ToolContext] = None+) -> dict:+ """+ Buyer makes an offer to the seller.++ Args:+ offer_amount: The dollar amount being offered+ message: What the buyer says to the seller+ reasoning: Internal reasoning for this offer++ Returns:+ Offer details and status+ """+ if negotiation_state.status != "negotiating":+ return {"error": "Negotiation not in progress"}++ scenario = get_scenario(negotiation_state.scenario_id)+ buyer_p = BUYER_PERSONALITIES[negotiation_state.buyer_personality]++ round_data = {+ "round": negotiation_state.current_round,+ "type": "buyer_offer",+ "offer_amount": offer_amount,+ "message": message,+ "reasoning": reasoning,+ "buyer_name": buyer_p["name"],+ "buyer_emoji": buyer_p["emoji"]+ }++ negotiation_state.rounds.append(round_data)++ return {+ "status": "offer_made",+ "round": negotiation_state.current_round,+ "offer": offer_amount,+ "message": message,+ "buyer": f"{buyer_p['emoji']} {buyer_p['name']}",+ "percent_of_asking": round(offer_amount / scenario["asking_price"] * 100, 1)+ }+++def seller_respond(+ action: str,+ counter_amount: Optional[int] = None,+ message: str = "",+ reasoning: str = "",+ tool_context: Optional[ToolContext] = None+) -> dict:+ """+ Seller responds to the buyer's offer.++ Args:+ action: One of 'accept', 'counter', 'reject', 'walk'+ counter_amount: If countering, the counter offer amount+ message: What the seller says to the buyer+ reasoning: Internal reasoning for this decision++ Returns:+ Response details and updated negotiation status+ """+ if negotiation_state.status != "negotiating":+ return {"error": "Negotiation not in progress"}++ scenario = get_scenario(negotiation_state.scenario_id)+ seller_p = SELLER_PERSONALITIES[negotiation_state.seller_personality]++ round_data = {+ "round": negotiation_state.current_round,+ "type": "seller_response",+ "action": action,+ "counter_amount": counter_amount,+ "message": message,+ "reasoning": reasoning,+ "seller_name": seller_p["name"],+ "seller_emoji": seller_p["emoji"]+ }++ negotiation_state.rounds.append(round_data)++ result = {+ "status": "response_given",+ "round": negotiation_state.current_round,+ "action": action,+ "message": message,+ "seller": f"{seller_p['emoji']} {seller_p['name']}"+ }++ if action == "accept":+ # Get the last buyer offer+ last_offer = None+ for r in reversed(negotiation_state.rounds):+ if r["type"] == "buyer_offer":+ last_offer = r["offer_amount"]+ break++ negotiation_state.status = "deal"+ negotiation_state.final_price = last_offer++ result["outcome"] = "DEAL"+ result["final_price"] = last_offer+ result["savings"] = scenario["asking_price"] - last_offer+ result["percent_off"] = round((scenario["asking_price"] - last_offer) / scenario["asking_price"] * 100, 1)++ elif action == "walk":+ negotiation_state.status = "no_deal"+ result["outcome"] = "SELLER_WALKED"++ elif action == "counter":+ result["counter_amount"] = counter_amount+ negotiation_state.current_round += 1++ else: # reject+ negotiation_state.current_round += 1++ return result+++def get_negotiation_state(tool_context: Optional[ToolContext] = None) -> dict:+ """+ Get the current state of the negotiation.++ Returns:+ Full negotiation state including history+ """+ scenario = get_scenario(negotiation_state.scenario_id)+ buyer_p = BUYER_PERSONALITIES[negotiation_state.buyer_personality]+ seller_p = SELLER_PERSONALITIES[negotiation_state.seller_personality]++ return {+ "status": negotiation_state.status,+ "scenario": scenario["title"],+ "item": scenario["item"]["name"],+ "asking_price": scenario["asking_price"],+ "current_round": negotiation_state.current_round,+ "buyer": {+ "name": buyer_p["name"],+ "emoji": buyer_p["emoji"],+ "budget": negotiation_state.buyer_budget+ },+ "seller": {+ "name": seller_p["name"],+ "emoji": seller_p["emoji"],+ "minimum": negotiation_state.seller_minimum+ },+ "rounds": negotiation_state.rounds,+ "final_price": negotiation_state.final_price+ }+++def get_available_scenarios(tool_context: Optional[ToolContext] = None) -> dict:+ """+ Get all available negotiation scenarios.++ Returns:+ List of available scenarios with details+ """+ scenarios = []+ for key, s in SCENARIOS.items():+ scenarios.append({+ "id": key,+ "title": s["title"],+ "emoji": s["emoji"],+ "description": s["description"],+ "item": s["item"]["name"],+ "asking_price": s["asking_price"]+ })+ return {"scenarios": scenarios}+++def get_available_personalities(tool_context: Optional[ToolContext] = None) -> dict:+ """+ Get all available buyer and seller personalities.++ Returns:+ Available personalities for both buyer and seller+ """+ buyers = []+ for key, p in BUYER_PERSONALITIES.items():+ buyers.append({+ "id": key,+ "name": p["name"],+ "emoji": p["emoji"],+ "description": p["description"]+ })++ sellers = []+ for key, p in SELLER_PERSONALITIES.items():+ sellers.append({+ "id": key,+ "name": p["name"],+ "emoji": p["emoji"],+ "description": p["description"]+ })++ return {"buyers": buyers, "sellers": sellers}+++# ============================================================================+# ADK AGENT DEFINITION+# ============================================================================++negotiation_agent = LlmAgent(+ name="NegotiationBattleAgent",+ model="gemini-3-flash-preview",+ description="AI Negotiation Battle Simulator - orchestrates dramatic negotiations between buyer and seller agents",+ instruction="""+You are the NEGOTIATION BATTLE MASTER! ๐ฎ You orchestrate epic negotiations between AI buyer and seller agents.++YOUR ROLE:+You manage a negotiation battle where a Buyer agent and a Seller agent negotiate over an item.+You play BOTH roles, switching between them to create a dramatic back-and-forth negotiation.++AVAILABLE TOOLS:+- get_available_scenarios: See what scenarios are available+- get_available_personalities: See buyer/seller personality options+- configure_negotiation: Set up the scenario and personalities+- start_negotiation: Begin the battle!+- buyer_make_offer: Make an offer as the buyer+- seller_respond: Respond as the seller (accept/counter/reject/walk)+- get_negotiation_state: Check current negotiation status++HOW TO RUN A NEGOTIATION:+1. First, use configure_negotiation to set up the scenario and personalities+2. Use start_negotiation to begin+3. Alternate between buyer_make_offer and seller_respond+4. Play each role authentically based on their personality!+5. Continue until a deal is reached or someone walks away++PERSONALITY GUIDELINES:+- Each personality has distinct traits - embody them fully!+- Buyers have budgets they shouldn't exceed+- Sellers have minimums they won't go below+- Create DRAMA and tension in the negotiation+- Make the dialogue feel real and entertaining++IMPORTANT:+- When the user asks to start a negotiation, first show them the options+- Let them pick scenario and personalities, or use defaults+- Once configured, run the full negotiation automatically+- Provide colorful commentary between rounds+- Celebrate deals and mourn walkways dramatically!++Be entertaining, dramatic, and make this feel like a real negotiation showdown! ๐ญ+""",+ tools=[+ FunctionTool(get_available_scenarios),+ FunctionTool(get_available_personalities),+ FunctionTool(configure_negotiation),+ FunctionTool(start_negotiation),+ FunctionTool(buyer_make_offer),+ FunctionTool(seller_respond),+ FunctionTool(get_negotiation_state),+ ]+)+++# ============================================================================+# AG-UI + FASTAPI SETUP+# ============================================================================++# Create ADK middleware agent+adk_negotiation_agent = ADKAgent(+ adk_agent=negotiation_agent,+ app_name="negotiation_battle",+ user_id="battle_user",+ session_timeout_seconds=3600,+ use_in_memory_services=True+)++# Create FastAPI app+app = FastAPI(+ title="AI Negotiation Battle Simulator",+ description="Watch AI agents battle it out in epic negotiations!",+ version="1.0.0"+)++# Add CORS middleware for frontend+app.add_middleware(+ CORSMiddleware,+ allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],+ allow_credentials=True,+ allow_methods=["*"],+ allow_headers=["*"],+)++# Add AG-UI endpoint+add_adk_fastapi_endpoint(app, adk_negotiation_agent, path="/")+++# ============================================================================+# MAIN+# ============================================================================++if __name__ == "__main__":+ import uvicorn++ if not os.getenv("GOOGLE_API_KEY"):+ print("โ ๏ธ Warning: GOOGLE_API_KEY not set!")+ print(" Get your key from: https://aistudio.google.com/")+ print()++ port = int(os.getenv("PORT", 8000))+ print(f"๐ฎ AI Negotiation Battle Simulator starting on port {port}")+ print(f" AG-UI endpoint: http://localhost:{port}/")++ uvicorn.run(app, host="0.0.0.0", port=port)diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/__init__.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/__init__.pysimilarity index 100%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/__init__.pyrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/__init__.pydiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/buyer_agent.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/buyer_agent.pysimilarity index 100%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/buyer_agent.pyrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/buyer_agent.pydiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/orchestrator.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/orchestrator.pysimilarity index 100%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/orchestrator.pyrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/orchestrator.pydiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/seller_agent.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/seller_agent.pysimilarity index 100%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/agents/seller_agent.pyrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/seller_agent.pydiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/config/__init__.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/config/__init__.pysimilarity index 100%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/config/__init__.pyrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/config/__init__.pydiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/config/personalities.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/config/personalities.pysimilarity index 100%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/config/personalities.pyrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/config/personalities.pydiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/config/scenarios.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/config/scenarios.pysimilarity index 100%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/config/scenarios.pyrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/config/scenarios.pydiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/requirements.txt b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/requirements.txtsimilarity index 60%rename from advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/requirements.txtrename to advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/requirements.txtindex 5dcd90a2..db557b23 100644--- a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/requirements.txt+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/requirements.txt@@ -1,5 +1,7 @@google-adk>=1.5.0google-genai>=1.0.0-streamlit>=1.45.0+ag-ui-adk>=0.1.0+fastapi>=0.115.0+uvicorn>=0.34.0python-dotenv>=1.0.0pydantic>=2.0.0diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/next.config.js b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/next.config.jsnew file mode 100644index 00000000..a843cbee--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/next.config.js@@ -0,0 +1,6 @@+/** @type {import('next').NextConfig} */+const nextConfig = {+ reactStrictMode: true,+}++module.exports = nextConfigdiff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/package.json b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/package.jsonnew file mode 100644index 00000000..7134494c--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/package.json@@ -0,0 +1,31 @@+{+ "name": "negotiation-battle-frontend",+ "version": "1.0.0",+ "private": true,+ "scripts": {+ "dev": "next dev",+ "build": "next build",+ "start": "next start",+ "lint": "next lint"+ },+ "dependencies": {+ "@copilotkit/react-core": "^1.8.0",+ "@copilotkit/react-ui": "^1.8.0",+ "@copilotkit/runtime": "^1.8.0",+ "@ag-ui/client": "^0.1.0",+ "next": "^15.0.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "framer-motion": "^11.0.0",+ "lucide-react": "^0.460.0"+ },+ "devDependencies": {+ "@types/node": "^22.0.0",+ "@types/react": "^19.0.0",+ "@types/react-dom": "^19.0.0",+ "autoprefixer": "^10.4.0",+ "postcss": "^8.4.0",+ "tailwindcss": "^3.4.0",+ "typescript": "^5.0.0"+ }+}diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/postcss.config.js b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/postcss.config.jsnew file mode 100644index 00000000..33ad091d--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/postcss.config.js@@ -0,0 +1,6 @@+module.exports = {+ plugins: {+ tailwindcss: {},+ autoprefixer: {},+ },+}diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/api/copilotkit/route.ts b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/api/copilotkit/route.tsnew file mode 100644index 00000000..042183a6--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/api/copilotkit/route.ts@@ -0,0 +1,30 @@+import {+ CopilotRuntime,+ ExperimentalEmptyAdapter,+ copilotRuntimeNextJSAppRouterEndpoint,+} from "@copilotkit/runtime";+import { HttpAgent } from "@ag-ui/client";+import { NextRequest } from "next/server";++// Service adapter for CopilotKit runtime+const serviceAdapter = new ExperimentalEmptyAdapter();++// Create the CopilotRuntime with our ADK agent+const runtime = new CopilotRuntime({+ agents: {+ negotiation_agent: new HttpAgent({+ url: process.env.AGENT_URL || "http://localhost:8000/",+ }),+ },+});++// Export POST handler for the API route+export const POST = async (req: NextRequest) => {+ const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({+ runtime,+ serviceAdapter,+ endpoint: "/api/copilotkit",+ });++ return handleRequest(req);+};diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/globals.css b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/globals.cssnew file mode 100644index 00000000..9f459284--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/globals.css@@ -0,0 +1,82 @@+@tailwind base;+@tailwind components;+@tailwind utilities;++:root {+ --foreground-rgb: 255, 255, 255;+ --background-start-rgb: 15, 23, 42;+ --background-end-rgb: 30, 41, 59;+}++body {+ color: rgb(var(--foreground-rgb));+ background: linear-gradient(+ 135deg,+ rgb(var(--background-start-rgb)),+ rgb(var(--background-end-rgb))+ );+ min-height: 100vh;+}++/* Battle Arena Styles */+.battle-arena {+ background: radial-gradient(ellipse at center, rgba(255,215,0,0.1) 0%, transparent 70%);+}++.buyer-glow {+ box-shadow: 0 0 30px rgba(59, 130, 246, 0.5);+}++.seller-glow {+ box-shadow: 0 0 30px rgba(239, 68, 68, 0.5);+}++.offer-pulse {+ animation: offerPulse 2s ease-in-out infinite;+}++@keyframes offerPulse {+ 0%, 100% { transform: scale(1); }+ 50% { transform: scale(1.02); }+}++/* VS Badge */+.vs-badge {+ background: linear-gradient(135deg, #ffd700 0%, #ff8c00 100%);+ text-shadow: 2px 2px 4px rgba(0,0,0,0.5);+}++/* Deal Animation */+.deal-celebration {+ animation: celebrate 0.5s ease-out;+}++@keyframes celebrate {+ 0% { transform: scale(0.8); opacity: 0; }+ 50% { transform: scale(1.1); }+ 100% { transform: scale(1); opacity: 1; }+}++/* Negotiation Timeline */+.timeline-connector {+ background: linear-gradient(180deg, #3b82f6 0%, #ffd700 50%, #ef4444 100%);+}++/* Custom scrollbar */+::-webkit-scrollbar {+ width: 8px;+}++::-webkit-scrollbar-track {+ background: rgba(255,255,255,0.1);+ border-radius: 4px;+}++::-webkit-scrollbar-thumb {+ background: rgba(255,255,255,0.3);+ border-radius: 4px;+}++::-webkit-scrollbar-thumb:hover {+ background: rgba(255,255,255,0.5);+}diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/layout.tsx b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/layout.tsxnew file mode 100644index 00000000..6fc8111d--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/layout.tsx@@ -0,0 +1,28 @@+import type { Metadata } from "next";+import { CopilotKit } from "@copilotkit/react-core";+import "@copilotkit/react-ui/styles.css";+import "./globals.css";++export const metadata: Metadata = {+ title: "๐ฎ AI Negotiation Battle Simulator",+ description: "Watch AI agents battle it out in epic negotiations!",+};++export default function RootLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <html lang="en">+ <body className="antialiased">+ <CopilotKit+ runtimeUrl="/api/copilotkit"+ agent="negotiation_agent"+ >+ {children}+ </CopilotKit>+ </body>+ </html>+ );+}diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/page.tsx b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/page.tsxnew file mode 100644index 00000000..83bd2f27--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/src/app/page.tsx@@ -0,0 +1,403 @@+"use client";++import { useState } from "react";+import {+ CopilotSidebar,+ CopilotKitCSSProperties+} from "@copilotkit/react-ui";+import { useCoAgent, useCopilotAction } from "@copilotkit/react-core";+import { motion, AnimatePresence } from "framer-motion";+import {+ Swords,+ DollarSign,+ TrendingDown,+ TrendingUp,+ Handshake,+ XCircle,+ Trophy+} from "lucide-react";++// Types for agent state+type NegotiationRound = {+ round: number;+ type: "buyer_offer" | "seller_response";+ offer_amount?: number;+ action?: string;+ counter_amount?: number;+ message: string;+ buyer_name?: string;+ buyer_emoji?: string;+ seller_name?: string;+ seller_emoji?: string;+};++type AgentState = {+ status: "setup" | "ready" | "negotiating" | "deal" | "no_deal";+ scenario?: {+ title: string;+ item: string;+ asking_price: number;+ };+ buyer?: {+ name: string;+ emoji: string;+ budget: number;+ };+ seller?: {+ name: string;+ emoji: string;+ minimum: number;+ };+ rounds: NegotiationRound[];+ current_round: number;+ final_price?: number;+};++// Offer Card Component+function OfferCard({ round, isLatest }: { round: NegotiationRound; isLatest: boolean }) {+ const isBuyer = round.type === "buyer_offer";++ return (+ <motion.div+ initial={{ opacity: 0, x: isBuyer ? -50 : 50, scale: 0.9 }}+ animate={{ opacity: 1, x: 0, scale: 1 }}+ transition={{ duration: 0.4 }}+ className={`+ relative p-4 rounded-xl mb-4+ ${isBuyer+ ? "bg-gradient-to-r from-blue-900/80 to-blue-800/60 border-l-4 border-blue-400 mr-8"+ : "bg-gradient-to-l from-red-900/80 to-red-800/60 border-r-4 border-red-400 ml-8"+ }+ ${isLatest ? "offer-pulse" : ""}+ `}+ >+ {/* Round Badge */}+ <div className={`+ absolute -top-2 ${isBuyer ? "-left-2" : "-right-2"}+ bg-gray-800 px-2 py-0.5 rounded-full text-xs font-bold+ `}>+ R{round.round}+ </div>++ {/* Agent Info */}+ <div className={`flex items-center gap-2 mb-2 ${!isBuyer && "flex-row-reverse"}`}>+ <span className="text-2xl">+ {isBuyer ? round.buyer_emoji : round.seller_emoji}+ </span>+ <span className="font-bold text-sm">+ {isBuyer ? round.buyer_name : round.seller_name}+ </span>+ </div>++ {/* Offer/Response */}+ <div className={`${!isBuyer && "text-right"}`}>+ {isBuyer && round.offer_amount && (+ <div className="flex items-center gap-2 mb-2">+ <DollarSign className="w-5 h-5 text-green-400" />+ <span className="text-2xl font-bold text-green-400">+ ${round.offer_amount.toLocaleString()}+ </span>+ </div>+ )}++ {!isBuyer && round.action && (+ <div className={`flex items-center gap-2 mb-2 ${!isBuyer && "justify-end"}`}>+ {round.action === "accept" && (+ <>+ <Handshake className="w-5 h-5 text-green-400" />+ <span className="text-xl font-bold text-green-400">ACCEPTED!</span>+ </>+ )}+ {round.action === "counter" && (+ <>+ <TrendingDown className="w-5 h-5 text-yellow-400" />+ <span className="text-xl font-bold text-yellow-400">+ ${round.counter_amount?.toLocaleString()}+ </span>+ </>+ )}+ {round.action === "reject" && (+ <>+ <XCircle className="w-5 h-5 text-red-400" />+ <span className="text-xl font-bold text-red-400">REJECTED</span>+ </>+ )}+ {round.action === "walk" && (+ <>+ <XCircle className="w-5 h-5 text-red-500" />+ <span className="text-xl font-bold text-red-500">WALKED AWAY</span>+ </>+ )}+ </div>+ )}++ {/* Message */}+ <p className="text-gray-300 italic text-sm">"{round.message}"</p>+ </div>+ </motion.div>+ );+}++// Deal Banner Component+function DealBanner({ finalPrice, askingPrice }: { finalPrice: number; askingPrice: number }) {+ const savings = askingPrice - finalPrice;+ const percentOff = ((savings / askingPrice) * 100).toFixed(1);++ return (+ <motion.div+ initial={{ scale: 0, rotate: -10 }}+ animate={{ scale: 1, rotate: 0 }}+ transition={{ type: "spring", bounce: 0.5 }}+ className="deal-celebration bg-gradient-to-r from-green-600 to-emerald-500 rounded-2xl p-8 text-center shadow-2xl"+ >+ <Trophy className="w-16 h-16 mx-auto mb-4 text-yellow-300" />+ <h2 className="text-4xl font-black mb-2">๐ DEAL CLOSED! ๐</h2>+ <p className="text-5xl font-black text-yellow-300 mb-4">+ ${finalPrice.toLocaleString()}+ </p>+ <div className="flex justify-center gap-8 text-lg">+ <div>+ <p className="text-green-200">Savings</p>+ <p className="font-bold text-2xl">${savings.toLocaleString()}</p>+ </div>+ <div>+ <p className="text-green-200">Off Asking</p>+ <p className="font-bold text-2xl">{percentOff}%</p>+ </div>+ </div>+ </motion.div>+ );+}++// Main Page Component+export default function NegotiationBattle() {+ const [themeColor] = useState("#6366f1");++ // Connect to agent state+ const { state } = useCoAgent<AgentState>({+ name: "negotiation_agent",+ initialState: {+ status: "setup",+ rounds: [],+ current_round: 0,+ },+ });++ // Register tool renderers for Generative UI+ useCopilotAction({+ name: "buyer_make_offer",+ description: "Buyer makes an offer",+ available: "disabled",+ parameters: [+ { name: "offer_amount", type: "number", required: true },+ { name: "message", type: "string", required: true },+ ],+ render: ({ args }) => (+ <div className="bg-blue-900/50 p-3 rounded-lg border border-blue-500">+ <div className="flex items-center gap-2">+ <TrendingUp className="w-4 h-4 text-blue-400" />+ <span className="font-bold">Buyer Offers:</span>+ <span className="text-green-400 font-bold">+ ${(args.offer_amount as number)?.toLocaleString()}+ </span>+ </div>+ </div>+ ),+ });++ useCopilotAction({+ name: "seller_respond",+ description: "Seller responds to offer",+ available: "disabled",+ parameters: [+ { name: "action", type: "string", required: true },+ { name: "counter_amount", type: "number", required: false },+ { name: "message", type: "string", required: true },+ ],+ render: ({ args }) => (+ <div className="bg-red-900/50 p-3 rounded-lg border border-red-500">+ <div className="flex items-center gap-2">+ <TrendingDown className="w-4 h-4 text-red-400" />+ <span className="font-bold">Seller {args.action}s:</span>+ {args.counter_amount && (+ <span className="text-yellow-400 font-bold">+ ${(args.counter_amount as number)?.toLocaleString()}+ </span>+ )}+ </div>+ </div>+ ),+ });++ return (+ <main+ className="min-h-screen"+ style={{ "--copilot-kit-primary-color": themeColor } as CopilotKitCSSProperties}+ >+ {/* Header */}+ <header className="bg-gradient-to-r from-gray-900 via-gray-800 to-gray-900 border-b border-gray-700">+ <div className="container mx-auto px-4 py-6">+ <div className="flex items-center justify-center gap-4">+ <Swords className="w-10 h-10 text-yellow-400" />+ <h1 className="text-4xl font-black bg-gradient-to-r from-yellow-400 via-red-500 to-blue-500 bg-clip-text text-transparent">+ AI NEGOTIATION BATTLE+ </h1>+ <Swords className="w-10 h-10 text-yellow-400 transform scale-x-[-1]" />+ </div>+ <p className="text-center text-gray-400 mt-2">+ Watch AI agents battle it out in epic negotiations!+ </p>+ </div>+ </header>++ {/* Battle Arena */}+ <div className="container mx-auto px-4 py-8 battle-arena">+ {/* Scenario Header */}+ {state.scenario && (+ <motion.div+ initial={{ opacity: 0, y: -20 }}+ animate={{ opacity: 1, y: 0 }}+ className="text-center mb-8"+ >+ <h2 className="text-2xl font-bold text-yellow-400">+ {state.scenario.title}+ </h2>+ <p className="text-xl text-gray-300">{state.scenario.item}</p>+ <p className="text-lg">+ Asking Price: <span className="text-green-400 font-bold">+ ${state.scenario.asking_price?.toLocaleString()}+ </span>+ </p>+ </motion.div>+ )}++ {/* VS Display */}+ {state.buyer && state.seller && (+ <div className="flex items-center justify-center gap-8 mb-8">+ {/* Buyer */}+ <motion.div+ initial={{ opacity: 0, x: -50 }}+ animate={{ opacity: 1, x: 0 }}+ className="buyer-glow bg-gradient-to-br from-blue-900 to-blue-800 rounded-2xl p-6 text-center min-w-[200px]"+ >+ <div className="text-5xl mb-2">{state.buyer.emoji}</div>+ <h3 className="text-xl font-bold text-blue-300">{state.buyer.name}</h3>+ <p className="text-sm text-gray-400">BUYER</p>+ <p className="text-green-400 font-bold mt-2">+ Budget: ${state.buyer.budget?.toLocaleString()}+ </p>+ </motion.div>++ {/* VS Badge */}+ <motion.div+ initial={{ scale: 0 }}+ animate={{ scale: 1 }}+ transition={{ delay: 0.3, type: "spring" }}+ className="vs-badge rounded-full w-20 h-20 flex items-center justify-center text-3xl font-black text-gray-900"+ >+ VS+ </motion.div>++ {/* Seller */}+ <motion.div+ initial={{ opacity: 0, x: 50 }}+ animate={{ opacity: 1, x: 0 }}+ className="seller-glow bg-gradient-to-bl from-red-900 to-red-800 rounded-2xl p-6 text-center min-w-[200px]"+ >+ <div className="text-5xl mb-2">{state.seller.emoji}</div>+ <h3 className="text-xl font-bold text-red-300">{state.seller.name}</h3>+ <p className="text-sm text-gray-400">SELLER</p>+ <p className="text-yellow-400 font-bold mt-2">+ Minimum: ${state.seller.minimum?.toLocaleString()}+ </p>+ </motion.div>+ </div>+ )}++ {/* Negotiation Timeline */}+ {state.rounds && state.rounds.length > 0 && (+ <div className="max-w-2xl mx-auto">+ <h3 className="text-xl font-bold text-center mb-4 text-gray-300">+ โฑ๏ธ NEGOTIATION TIMELINE+ </h3>+ <div className="relative">+ {/* Center line */}+ <div className="absolute left-1/2 top-0 bottom-0 w-1 timeline-connector transform -translate-x-1/2" />++ {/* Rounds */}+ <AnimatePresence>+ {state.rounds.map((round, index) => (+ <OfferCard+ key={`${round.type}-${round.round}-${index}`}+ round={round}+ isLatest={index === state.rounds.length - 1}+ />+ ))}+ </AnimatePresence>+ </div>+ </div>+ )}++ {/* Deal Banner */}+ {state.status === "deal" && state.final_price && state.scenario && (+ <div className="max-w-xl mx-auto mt-8">+ <DealBanner+ finalPrice={state.final_price}+ askingPrice={state.scenario.asking_price}+ />+ </div>+ )}++ {/* No Deal Banner */}+ {state.status === "no_deal" && (+ <motion.div+ initial={{ scale: 0 }}+ animate={{ scale: 1 }}+ className="max-w-xl mx-auto mt-8 bg-gradient-to-r from-red-800 to-red-600 rounded-2xl p-8 text-center"+ >+ <XCircle className="w-16 h-16 mx-auto mb-4 text-red-300" />+ <h2 className="text-3xl font-black mb-2">NO DEAL ๐</h2>+ <p className="text-gray-200">The negotiation has ended without an agreement.</p>+ </motion.div>+ )}++ {/* Instructions when no negotiation */}+ {state.status === "setup" && (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ className="text-center py-16"+ >+ <div className="text-6xl mb-4">๐ฎ</div>+ <h2 className="text-2xl font-bold text-gray-300 mb-4">+ Ready to Start a Battle?+ </h2>+ <p className="text-gray-400 max-w-md mx-auto">+ Open the chat sidebar and tell the Battle Master to start a negotiation!+ Try: "Start a negotiation for a used car"+ </p>+ </motion.div>+ )}+ </div>++ {/* CopilotKit Sidebar */}+ <CopilotSidebar+ clickOutsideToClose={false}+ defaultOpen={true}+ labels={{+ title: "๐ฎ Battle Master",+ initial: `๐ Welcome to the AI Negotiation Battle Simulator!++I'm your Battle Master. I'll orchestrate an epic negotiation between AI agents.++**Try saying:**+- "Show me the available scenarios"+- "Start a negotiation for a used car"+- "Use Desperate Dan as the buyer and Shark Steve as the seller"++Ready to watch some AI agents battle it out? ๐ฅ`+ }}+ />+ </main>+ );+}diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/tailwind.config.js b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/tailwind.config.jsnew file mode 100644index 00000000..7d390501--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/tailwind.config.js@@ -0,0 +1,22 @@+/** @type {import('tailwindcss').Config} */+module.exports = {+ content: [+ './src/pages/**/*.{js,ts,jsx,tsx,mdx}',+ './src/components/**/*.{js,ts,jsx,tsx,mdx}',+ './src/app/**/*.{js,ts,jsx,tsx,mdx}',+ ],+ theme: {+ extend: {+ colors: {+ 'battle-blue': '#1e3a5f',+ 'battle-red': '#5a1e1e',+ 'battle-gold': '#ffd700',+ },+ animation: {+ 'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',+ 'bounce-slow': 'bounce 2s infinite',+ },+ },+ },+ plugins: [],+}diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/tsconfig.json b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/tsconfig.jsonnew file mode 100644index 00000000..7b285893--- /dev/null+++ b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/frontend/tsconfig.json@@ -0,0 +1,26 @@+{+ "compilerOptions": {+ "lib": ["dom", "dom.iterable", "esnext"],+ "allowJs": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "preserve",+ "incremental": true,+ "plugins": [+ {+ "name": "next"+ }+ ],+ "paths": {+ "@/*": ["./src/*"]+ }+ },+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],+ "exclude": ["node_modules"]+}diff --git a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/negotiation_app.py b/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/negotiation_app.pydeleted file mode 100644index c4798a0f..00000000--- a/advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/negotiation_app.py+++ /dev/null@@ -1,370 +0,0 @@-"""-๐ฎ AI Negotiation Battle Simulator--A real-time agent vs agent negotiation showdown using Google ADK.--Run with: streamlit run negotiation_app.py-"""--import streamlit as st-import os-from dotenv import load_dotenv--# Load environment variables-load_dotenv()--# Page config - must be first Streamlit command-st.set_page_config(- page_title="๐ฎ AI Negotiation Battle",- page_icon="๐ค",- layout="wide"-)--# Custom CSS for the battle arena-st.markdown("""-<style>- .main-header {- text-align: center;- padding: 20px;- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);- border-radius: 15px;- margin-bottom: 20px;- }- .offer-bubble {- background: rgba(102, 126, 234, 0.1);- border-left: 4px solid #667eea;- padding: 15px;- border-radius: 0 10px 10px 0;- margin: 10px 0;- }- .counter-bubble {- background: rgba(220, 53, 69, 0.1);- border-left: 4px solid #dc3545;- padding: 15px;- border-radius: 0 10px 10px 0;- margin: 10px 0;- }- .deal-box {- background: linear-gradient(135deg, #28a745 0%, #20c997 100%);- padding: 30px;- border-radius: 15px;- text-align: center;- color: white;- }- .no-deal-box {- background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);- padding: 30px;- border-radius: 15px;- text-align: center;- color: white;- }-</style>-""", unsafe_allow_html=True)---# ============================================================================-# IMPORTS-# ============================================================================--from config.scenarios import SCENARIOS, get_scenario, format_item_description-from config.personalities import (- BUYER_PERSONALITIES,- SELLER_PERSONALITIES,- get_personality_prompt-)-from agents import NegotiationOrchestrator---# ============================================================================-# SESSION STATE-# ============================================================================--if "negotiation_started" not in st.session_state:- st.session_state.negotiation_started = False-if "negotiation_events" not in st.session_state:- st.session_state.negotiation_events = []---# ============================================================================-# HEADER-# ============================================================================--st.markdown("# ๐ฎ AI Negotiation Battle Simulator")-st.markdown("*Watch two AI agents duke it out in an epic negotiation showdown!*")-st.divider()---# ============================================================================-# SIDEBAR - CONFIGURATION-# ============================================================================--with st.sidebar:- st.header("โ๏ธ Battle Configuration")-- # API Key- api_key = st.text_input(- "๐ Google AI API Key",- type="password",- value=os.environ.get("GOOGLE_API_KEY", ""),- help="Get your key from https://aistudio.google.com/"- )-- if api_key:- os.environ["GOOGLE_API_KEY"] = api_key-- st.divider()-- # Scenario Selection- st.subheader("๐ Scenario")- scenario_id = st.selectbox(- "Choose your battlefield",- options=list(SCENARIOS.keys()),- format_func=lambda x: f"{SCENARIOS[x]['emoji']} {SCENARIOS[x]['title']}",- disabled=st.session_state.negotiation_started- )-- scenario = get_scenario(scenario_id)-- with st.expander("๐ Scenario Details"):- st.markdown(f"**{scenario['description']}**")- st.markdown(format_item_description(scenario))- st.markdown(f"**Asking Price:** ${scenario['asking_price']:,}")- st.markdown(f"**Fair Market Value:** ~${scenario['fair_market_value']:,}")-- st.divider()-- # Personality Selection- st.subheader("๐ญ Combatants")-- buyer_personality = st.selectbox(- "๐ฏ Buyer",- options=list(BUYER_PERSONALITIES.keys()),- format_func=lambda x: f"{BUYER_PERSONALITIES[x]['emoji']} {BUYER_PERSONALITIES[x]['name']}",- disabled=st.session_state.negotiation_started- )- st.caption(BUYER_PERSONALITIES[buyer_personality]["description"])-- seller_personality = st.selectbox(- "๐ฐ Seller",- options=list(SELLER_PERSONALITIES.keys()),- format_func=lambda x: f"{SELLER_PERSONALITIES[x]['emoji']} {SELLER_PERSONALITIES[x]['name']}",- disabled=st.session_state.negotiation_started- )- st.caption(SELLER_PERSONALITIES[seller_personality]["description"])-- st.divider()-- # Battle Settings- st.subheader("๐๏ธ Settings")- max_rounds = st.slider(- "Max Rounds",- 3, 15, 8,- disabled=st.session_state.negotiation_started- )---# ============================================================================-# MAIN BATTLE ARENA-# ============================================================================--if not st.session_state.negotiation_started:- # Pre-battle view- st.markdown(f"""- ## {scenario['emoji']} {scenario['title']}-- ### The Setup-- **Item:** {scenario['item']['name']}- **Asking Price:** ${scenario['asking_price']:,}- **Fair Market Value:** ~${scenario['fair_market_value']:,}-- ----- **๐ฏ Buyer ({BUYER_PERSONALITIES[buyer_personality]['emoji']} {BUYER_PERSONALITIES[buyer_personality]['name']})**- Budget: ${scenario['buyer_budget']:,}- *{BUYER_PERSONALITIES[buyer_personality]['description']}*-- **๐ฐ Seller ({SELLER_PERSONALITIES[seller_personality]['emoji']} {SELLER_PERSONALITIES[seller_personality]['name']})**- Minimum: ${scenario['seller_minimum']:,}- *{SELLER_PERSONALITIES[seller_personality]['description']}*-- ---- """)-- col1, col2, col3 = st.columns([1, 2, 1])- with col2:- if st.button("โ๏ธ START THE BATTLE!", use_container_width=True, type="primary"):- if not api_key:- st.error("โ ๏ธ Please enter your Google AI API key in the sidebar!")- else:- st.session_state.negotiation_started = True- st.session_state.negotiation_events = []- st.rerun()--else:- # Battle in progress or complete- st.markdown(f"## {scenario['emoji']} {scenario['title']}")- st.markdown(f"**{scenario['item']['name']}** | Asking: **${scenario['asking_price']:,}**")- st.divider()-- # Run negotiation if not already done- if not st.session_state.negotiation_events:-- buyer_prompt = get_personality_prompt("buyer", buyer_personality)- seller_prompt = get_personality_prompt("seller", seller_personality)-- orchestrator = NegotiationOrchestrator(- scenario=scenario,- buyer_personality=buyer_prompt,- seller_personality=seller_prompt,- max_rounds=max_rounds,- model="gemini-3-flash-preview"- )-- # Create progress container- progress_text = st.empty()- progress_bar = st.progress(0)-- events = []- round_count = 0-- try:- for event in orchestrator.run_negotiation_sync():- events.append(event)-- if event["type"] == "buyer_offer":- round_count = event["data"]["round"]- progress = min(round_count / max_rounds, 0.95)- progress_bar.progress(progress)- progress_text.markdown(f"๐ค **Round {round_count}** - Agents negotiating...")-- elif event["type"] in ["deal", "no_deal", "walk"]:- progress_bar.progress(1.0)- progress_text.empty()-- st.session_state.negotiation_events = events-- except Exception as e:- st.error(f"โ Error during negotiation: {str(e)}")- st.session_state.negotiation_events = [{"type": "error", "data": {"error": str(e)}}]-- st.rerun()-- # Display results- events = st.session_state.negotiation_events-- # Group events by round- rounds = {}- outcome = None-- for event in events:- if event["type"] == "buyer_offer":- round_num = event["data"]["round"]- rounds[round_num] = {"buyer": event["data"]}- elif event["type"] == "seller_response":- round_num = event["data"]["round"]- if round_num in rounds:- rounds[round_num]["seller"] = event["data"]- elif event["type"] in ["deal", "no_deal", "walk"]:- outcome = event-- # Display each round- for round_num in sorted(rounds.keys()):- round_data = rounds[round_num]-- st.markdown(f"### Round {round_num}")-- col1, col2 = st.columns(2)-- # Buyer offer- with col1:- if "buyer" in round_data:- buyer = round_data["buyer"]- st.markdown(f"""- <div class="offer-bubble">- <strong>๐ฏ Buyer Offers: ${buyer['offer']:,}</strong><br>- <em>"{buyer['message']}"</em><br>- <small>Confidence: {'๐ฅ' * (buyer['confidence'] // 2)}</small>- </div>- """, unsafe_allow_html=True)-- # Seller response- with col2:- if "seller" in round_data:- seller = round_data["seller"]- action_text = seller["action"].upper()- if seller["action"] == "counter" and seller["counter"]:- action_text = f"COUNTERS: ${seller['counter']:,}"-- st.markdown(f"""- <div class="counter-bubble">- <strong>๐ฐ Seller {action_text}</strong><br>- <em>"{seller['message']}"</em><br>- <small>Firmness: {'๐ช' * (seller['firmness'] // 2)}</small>- </div>- """, unsafe_allow_html=True)-- st.divider()-- # Show outcome- if outcome:- if outcome["type"] == "deal":- data = outcome["data"]- st.markdown(f"""- <div class="deal-box">- <h1>๐ DEAL CLOSED!</h1>- <h2>Final Price: ${data['final_price']:,}</h2>- <p>- Buyer saved: <strong>${data['savings']:,}</strong> ({data['percent_off']}% off asking)<br>- Rounds: <strong>{data['rounds']}</strong>- </p>- </div>- """, unsafe_allow_html=True)-- elif outcome["type"] == "walk":- data = outcome["data"]- st.markdown(f"""- <div class="no-deal-box">- <h1>๐ช {data['who'].upper()} WALKED AWAY</h1>- <h2>No Deal</h2>- <p>Last offer on the table: ${data['last_offer']:,}</p>- </div>- """, unsafe_allow_html=True)-- elif outcome["type"] == "no_deal":- data = outcome["data"]- st.markdown(f"""- <div class="no-deal-box">- <h1>โฐ TIME'S UP</h1>- <h2>Max Rounds Reached - No Deal</h2>- <p>Last offer: ${data['last_offer']:,} after {data['rounds']} rounds</p>- </div>- """, unsafe_allow_html=True)-- # New battle button- st.divider()- col1, col2, col3 = st.columns([1, 2, 1])- with col2:- if st.button("๐ New Battle", use_container_width=True):- st.session_state.negotiation_started = False- st.session_state.negotiation_events = []- st.rerun()-- # Show full log- with st.expander("๐ Full Negotiation Log (JSON)"):- for i, event in enumerate(events):- st.json(event)---# ============================================================================-# FOOTER-# ============================================================================--st.divider()-st.markdown("""-<div style='text-align: center; color: #888;'>- <p>Built with <strong>Google ADK</strong> + <strong>Streamlit</strong> |- <a href='https://github.com/Shubhamsaboo/awesome-llm-apps' target='_blank'>awesome-llm-apps</a></p>- <p>๐ฎ May the best negotiator win!</p>-</div>-""", unsafe_allow_html=True)