Skip to content

Add AI Court Simulation Python Script #691

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 208 additions & 0 deletions examples/python/tools/exa-tool/AI-CourtSimulation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
# # -*- coding: utf-8 -*-
# """AI-CourtSimulation.ipynb

# Automatically generated by Colab.

# Original file is located at
# https://colab.research.google.com/drive/1Pc6GCFJN9Fyq_oP4MCtPmeTSt_AZmRMT

# # ⚖️ AI - Mini Court Simulation

# A simplified court case simulation with essential AI agents.

# [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/LegaliaAI_MiniCourt.ipynb)

# ## Install Dependencies
# """

# !pip install praisonaiagents openai python-dotenv

# """## Import Libraries & Setup"""

import os
from dotenv import load_dotenv
from IPython.display import display, HTML
import time

load_dotenv()

# Setup API key
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
print("🔑 Enter your OpenAI API key:")
api_key = input("API Key: ").strip()
os.environ['OPENAI_API_KEY'] = "Enter your api key"

print("✅ Setup complete!")

# """## Create Mini Agents"""

from praisonaiagents import Agent

# Judge Agent
judge = Agent(
name="Judge",
role="Preside over court proceedings",
llm="gpt-4o-mini",
instructions=[
"You are an impartial judge",
"Make fair decisions based on evidence",
"Keep responses under 100 words"
],
markdown=True
)

# Prosecutor Agent
prosecutor = Agent(
name="Prosecutor",
role="Present case against defendant",
llm="gpt-4o-mini",
instructions=[
"You are a prosecutor seeking conviction",
"Present evidence methodically",
"Keep responses under 80 words"
],
markdown=True
)

# Defense Agent
defense = Agent(
name="Defense",
role="Defend the accused",
llm="gpt-4o-mini",
instructions=[
"You are a defense attorney",
"Create reasonable doubt",
"Keep responses under 80 words"
],
markdown=True
)

# Witness Agent
witness = Agent(
name="Witness",
role="Provide testimony",
llm="gpt-4o-mini",
instructions=[
"You are a witness testifying",
"Provide factual testimony",
"Keep responses under 60 words"
],
markdown=True
)

print("✅ Mini agents created!")

"""# Case Details Input"""

# Simple case details
case_title = input("Case Title (e.g., 'State vs. Smith'): ") or "State vs. Smith"
case_description = input("Case Description: ") or "Theft case involving stolen laptop"
evidence = input("Key Evidence: ") or "Security camera footage and witness testimony"

print(f"\n📋 Case: {case_title}")
print(f"📝 Description: {case_description}")
print(f"🔍 Evidence: {evidence}")

"""# Helper Functions (Fixed with .start())## Cell 4: Case Details Input"""

# Display function
def show_message(name, role, message, color="#4CAF50"):
html = f"""
<div style="
background: {color};
color: white;
padding: 15px;
border-radius: 10px;
margin: 10px 0;
">
<strong>⚖️ {name}</strong> • <em>{role}</em><br>
<div style="margin-top: 10px;">{message}</div>
</div>
"""
display(HTML(html))

# Run agent using .start()
def run_agent(agent, prompt, name, role, color="#4CAF50"):
try:
response = agent.start(prompt)
show_message(name, role, response, color)
return response
except Exception as e:
show_message("System", "Error", str(e), "#f44336")
return ""

"""## Mini Court Simulation"""

# Mini court simulation
print("🚀 Starting Mini Court Simulation...")

# Day 1: Opening
display(HTML(f"<h2>📅 Day 1: Opening Statements</h2>"))

# Judge opens court
judge_prompt = f"""
You are Judge presiding over "{case_title}".
Open the court proceedings professionally.
Case: {case_description}
Keep it brief and formal.
"""
judge_response = run_agent(judge, judge_prompt, "Judge", "Presiding Judge", "#8B4513")

# Prosecutor opening
prosecutor_prompt = f"""
You are the Prosecutor for "{case_title}".
Give your opening statement.
Evidence: {evidence}
Be confident and factual.
"""
prosecutor_response = run_agent(prosecutor, prosecutor_prompt, "Prosecutor", "State Attorney", "#d32f2f")

# Defense opening
defense_prompt = f"""
You are the Defense Attorney for "{case_title}".
Give your opening statement.
Challenge the prosecution's case.
Emphasize presumption of innocence.
"""
defense_response = run_agent(defense, defense_prompt, "Defense", "Defense Attorney", "#1976d2")

time.sleep(1)

# Day 2: Testimony
display(HTML(f"<h2>📅 Day 2: Witness Testimony</h2>"))

# Witness testimony
witness_prompt = f"""
You are a witness in "{case_title}".
Provide your testimony about what you saw.
Evidence: {evidence}
Be factual and clear.
"""
witness_response = run_agent(witness, witness_prompt, "Witness", "Court Witness", "#ff9800")

time.sleep(1)

# Day 3: Verdict
display(HTML(f"<h2>📅 Day 3: Final Verdict</h2>"))

# Judge's verdict
verdict_prompt = f"""
You are Judge presiding over "{case_title}".
Deliver your final verdict.
Consider all evidence: {evidence}
Be fair and explain your reasoning.
"""
verdict_response = run_agent(judge, verdict_prompt, "Judge", "Final Verdict", "#8B4513")

print("\n✅ Mini court simulation completed!")

# """# Summary"""

print("🎯 Mini Legalia AI Complete!")
print("\nThis simplified version demonstrates:")
print("- 4 Essential Agents: Judge, Prosecutor, Defense, Witness")
print("- 3-Day Trial: Opening, Testimony, Verdict")
print("- Real-time Interaction: Each agent responds based on case context")
print("- Easy Setup: Minimal dependencies and configuration")
print("\nPerfect for quick demonstrations and learning! ⚖️")
100 changes: 100 additions & 0 deletions examples/python/tools/exa-tool/Cybersecurity-PoC Agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""Cybersecurity-PoC Agent.ipynb

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/drive/1hnNLGS90GopXOhwHHIqxaGJERcajSMQJ

# Pocky Query Tool: Automated CVE PoC Search & Validation

A lightweight, web-scale agent that helps you find, filter, and fetch real-world PoC exploits — so you don't have to.

**Features:**
- Automatically searches multiple security-related websites
- Intelligently analyzes and extracts PoC code
- Automatically selects the most reliable PoC samples
- Supports collection of PoCs from multiple sources

[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/Pocky_Cybersecurity_PoC_Agent.ipynb)

# Install Dependencies
"""

!pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4

"""# Set API Keys"""

import os

# Set your API keys here (replace with your actual keys)
os.environ["EXA_API_KEY"] = "your api key"
os.environ["OPENAI_API_KEY"] = "your api key"
os.environ["OPENAI_BASE_URL"] = "https://api.openai.com/v1" # Optional, for custom OpenAI endpoints

"""# Tools (Core Functions)"""

import json
from openai import OpenAI
from exa_py import Exa

# Dummy/Minimal agent classes for notebook demo
class ValidationAgent:
def __init__(self, input_json):
self.input_json = input_json
def run(self):
# Dummy validation logic for notebook demo
data = json.loads(self.input_json)
return True if "attack_intent" in data and "poc_sample" in data else False

class AttackIntentAgent:
def __init__(self, description):
self.description = description
def run(self):
# Dummy intent extraction for notebook demo
return f"Intent for: {self.description[:50]}..."

"""## YAML Prompt (Validation Example)
This is the prompt used for PoC validation.
"""

validation_prompt = """
You are a highly skilled technical assistant with deep expertise in PoC sample validation.

Given the attack intent of a CVE vulnerability and a PoC sample gathered from public sources, your task is to analyze whether the PoC correctly implements the intended attack behavior.

Specifically:
- Understand the CVE's attack intent, including the attack goal and the underlying exploitation mechanism.
- Analyze the PoC to determine whether it is designed to achieve this intent.
- Check whether the payloads, request structures, and overall logic of the PoC align with the described attack intent.
- You do not need to execute the PoC. Focus on static validation through reasoning and consistency.

Your output must be a JSON object with two fields:
- "valid": a boolean indicating whether the PoC correctly reflects the attack intent.
- "reasoning": a brief explanation of your judgment. If "valid" is false, the reasoning must clearly explain what is incorrect or inconsistent in the PoC compared to the attack intent, so that the PoC can be revised accordingly.
"""
print(validation_prompt)

"""# Main (Query and Validate a CVE PoC)"""

def run_pocky_for_cve(cve_id):
# Example: Simulate fetching a description and PoC (replace with real logic)
description = f"Description for {cve_id} (replace with real Exa/OpenAI search)"
poc_sample = f"PoC code for {cve_id} (replace with real PoC search)"

# Stage 2: Attack Intent
intent = AttackIntentAgent(description).run()
print(f"Attack Intent: {intent}")

# Stage 3: Validation
validation_input = json.dumps({"attack_intent": intent, "poc_sample": poc_sample}, indent=2)
valid = ValidationAgent(validation_input).run()
print(f"Validation Result: {valid}")
if valid:
print(f"PoC for {cve_id} is valid and ready to use.")
else:
print(f"PoC for {cve_id} failed validation.")

"""# Example Usage"""

run_pocky_for_cve("CVE-2023-4450")
Loading
Loading