dmChatbotBackend / improvement /examples /improve_agent_examples.py
github-actions
Auto deploy from GitHub
4a0825f
Raw History Blame Contribute Delete
10.6 kB
"""
Example: Using the Self-Improvement Interface
This script demonstrates how to use the agent improvement system
in different scenarios.
"""
import asyncio
import sys
from pathlib import Path
# Add parent directories to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from improvement.improveAgent import (
ImprovementSessionManager,
ValidationQuestion,
AgentDiscovery,
InitAgent,
CritiqueAgent,
ReviewerAgent
)
async def example_1_list_agents():
"""Example 1: Discover available agents."""
print("=" * 80)
print("Example 1: Discovering Available Agents")
print("=" * 80)
discovery = AgentDiscovery()
agents = discovery.list_agents()
print(f"\nFound {len(agents)} agents:")
for agent_name in agents:
agent_info = discovery.get_agent(agent_name)
prompt_file = agent_info.get("prompt_file", "N/A")
print(f" • {agent_name} (Prompt: {prompt_file})")
async def example_2_full_improvement_session():
"""Example 2: Run a complete improvement session."""
print("\n" + "=" * 80)
print("Example 2: Complete Improvement Session")
print("=" * 80)
manager = ImprovementSessionManager()
# Create session
session_id = manager.create_session("PatientLLM")
print(f"\nCreated session: {session_id}")
# Define validation questions
validation_questions = [
ValidationQuestion(
question="Does the agent show empathy to the patient?",
expected_quality="Clearly acknowledges patient concerns and emotions",
evaluation_criteria="Response mentions understanding of patient's feelings"
),
ValidationQuestion(
question="Is the medical advice accurate and safe?",
expected_quality="Accurate with proper disclaimers and safety considerations",
evaluation_criteria="No contradictions to established medical guidelines"
),
ValidationQuestion(
question="Is the response clear and well-organized?",
expected_quality="Easy to understand with clear structure",
evaluation_criteria="Response has logical flow and clear sections"
)
]
# Test input
test_input = "I've been having persistent headaches for a week and I'm worried it might be serious"
print(f"\nTest input: {test_input}")
print(f"\nRunning 3 improvement iterations...")
# Run improvement loop
results = await manager.run_improvement_loop(
session_id=session_id,
agent_name="PatientLLM",
validation_questions=validation_questions,
test_input=test_input,
num_iterations=3,
target_agent_instance=None # Set to actual agent instance if available
)
if results:
print(f"\n✅ Improvement session completed!")
print(f"\nResults Summary:")
print(f" Session ID: {results.session_id}")
print(f" Agent: {results.agent_name}")
print(f" Iterations: {results.iterations_performed}")
print(f" Baseline Score: {results.improvement_metrics.get('baseline_score', 0):.2f}")
print(f" Final Score: {results.improvement_metrics.get('final_score', 0):.2f}")
print(f" Improvement: +{results.improvement_metrics.get('improvement_delta', 0):.2f}")
print(f"\nBaseline Output:\n{results.baseline_output[:200]}...")
print(f"\nFinal Output:\n{results.final_output[:200]}...")
async def example_3_interactive_clarification():
"""Example 3: Interactive goal clarification with Init Agent."""
print("\n" + "=" * 80)
print("Example 3: Interactive Goal Clarification")
print("=" * 80)
manager = ImprovementSessionManager()
discovery = AgentDiscovery()
agent_name = "CaregiverLLM"
agent_info = discovery.get_agent(agent_name)
if not agent_info:
print(f"Agent {agent_name} not found")
return
current_prompt = agent_info.get("current_prompt", "")
print(f"\nImproving agent: {agent_name}")
print(f"Current prompt: {current_prompt[:100]}...")
# Simulate interactive clarification
conversation_history = []
print("\n--- Starting Interactive Clarification ---")
print("User: I want to improve how this agent responds to caregivers with different experience levels")
# First clarification round
result = await manager.init_agent.clarify_goals(
agent_name=agent_name,
current_prompt=current_prompt,
user_input="I want to improve how this agent responds to caregivers with different experience levels",
conversation_history=[]
)
print(f"\nInit Agent: {result['response'][:300]}...")
print(f"Is complete: {result['is_complete']}")
if not result['is_complete']:
# Continue clarification
conversation_history.append({"role": "user", "content": "I want to improve how this agent responds to caregivers"})
conversation_history.append({"role": "assistant", "content": result['response']})
print("\nUser: They should be able to use simpler language for newer caregivers")
result = await manager.init_agent.clarify_goals(
agent_name=agent_name,
current_prompt=current_prompt,
user_input="They should be able to use simpler language for newer caregivers",
conversation_history=conversation_history
)
print(f"\nInit Agent: {result['response'][:300]}...")
print(f"Is complete: {result['is_complete']}")
if result['is_complete'] and result['parsed_data']:
print(f"\n✅ Goals clarified!")
parsed = result['parsed_data']
if 'validation_questions' in parsed:
print(f"\nGenerated {len(parsed['validation_questions'])} validation questions:")
for i, vq in enumerate(parsed['validation_questions'][:2], 1):
print(f" {i}. {vq.get('question', 'N/A')}")
async def example_4_critique_and_review():
"""Example 4: Critique and review an agent output."""
print("\n" + "=" * 80)
print("Example 4: Output Critique and Prompt Review")
print("=" * 80)
manager = ImprovementSessionManager()
# Sample output to critique
user_prompt = "I think my blood pressure is too high"
agent_output = "Your blood pressure might be high. You should check it."
agent_name = "PatientLLM"
print(f"\nCritiquing output from {agent_name}...")
print(f"User input: {user_prompt}")
print(f"Agent output: {agent_output}")
# Get critique
print("\n--- Running Critique Agent ---")
critique = await manager.critique_agent.critique_output(
user_prompt=user_prompt,
agent_output=agent_output,
agent_name=agent_name
)
print(f"\nCritique Results:")
print(f" Overall Score: {critique.overall_score:.2f}")
print(f" Categories:")
for category, issues in critique.categories.items():
print(f" • {category}: {len(issues)} issues")
for issue in issues[:1]: # Show first issue
print(f" - {issue}")
# Now review and get updated prompt
print("\n--- Running Reviewer Agent ---")
discovery = AgentDiscovery()
agent_info = discovery.get_agent(agent_name)
original_prompt = agent_info.get("current_prompt", "")
review_result = await manager.reviewer_agent.review_and_update_prompt(
original_prompt=original_prompt,
user_prompt=user_prompt,
agent_output=agent_output,
critique=critique
)
print(f"\nUpdated Prompt Generated:")
print(f" Changes Made: {len(review_result['changes_made'])} updates")
for i, change in enumerate(review_result['changes_made'][:2], 1):
print(f" {i}. {change}")
print(f"\n Sample of new prompt:\n{review_result['updated_prompt'][:200]}...")
async def example_5_version_management():
"""Example 5: Managing prompt versions."""
print("\n" + "=" * 80)
print("Example 5: Prompt Version Management")
print("=" * 80)
from improveAgent import PromptVersionManager
version_manager = PromptVersionManager()
agent_name = "PatientLLM"
session_id = "improve_PatientLLM_12345"
print(f"\nManaging versions for {agent_name} in session {session_id}")
# Save multiple versions
print("\nSaving version 1...")
version_manager.save_prompt_version(
agent_name=agent_name,
session_id=session_id,
version_number=1,
prompt="Updated prompt v1: Focus on empathy",
metadata={"iteration": 1, "score": 0.75, "focus": "empathy"}
)
print("Saving version 2...")
version_manager.save_prompt_version(
agent_name=agent_name,
session_id=session_id,
version_number=2,
prompt="Updated prompt v2: Improved clarity and medical accuracy",
metadata={"iteration": 2, "score": 0.82, "focus": "clarity"}
)
print("Saving version 3...")
version_manager.save_prompt_version(
agent_name=agent_name,
session_id=session_id,
version_number=3,
prompt="Updated prompt v3: Combined empathy and accuracy",
metadata={"iteration": 3, "score": 0.88, "focus": "combined"}
)
# List versions
versions = version_manager.list_versions(agent_name, session_id)
print(f"\n✅ Saved {len(versions)} versions: {versions}")
# Load and compare
print(f"\nLoading version 1:")
v1 = version_manager.load_prompt_version(agent_name, session_id, 1)
print(f" {v1[:60]}...")
print(f"\nLoading version 3:")
v3 = version_manager.load_prompt_version(agent_name, session_id, 3)
print(f" {v3[:60]}...")
async def main():
"""Run all examples."""
print("\n" + "=" * 80)
print("AGENT SELF-IMPROVEMENT INTERFACE - EXAMPLES")
print("=" * 80)
# Run examples
await example_1_list_agents()
print("\n" + "-" * 80)
print("Note: Examples 2, 3, 4, 5 require LLM API access and will take time.")
print("Uncomment the examples below to run them.")
print("-" * 80)
# Uncomment to run these examples (requires API access):
# await example_2_full_improvement_session()
# await example_3_interactive_clarification()
# await example_4_critique_and_review()
# await example_5_version_management()
print("\n✅ Examples completed!")
if __name__ == "__main__":
asyncio.run(main())