11import json
22from typing import Dict , Optional
3+ from pathlib import Path
4+
5+ CODE_SAMPLES_DIR = Path ("benchmarking/code_samples" )
6+
37
48class Command :
59 """Represents a command an agent can issue to a neighboring agent."""
@@ -12,63 +16,107 @@ def __repr__(self) -> str:
1216 return (f"Command(name='{ self .name } ', target='{ self .target_agent } ', "
1317 f"desc='{ self .description [:30 ]} ...')" )
1418
19+
1520class Agent :
1621 """Represents a single agent in the system."""
17- def __init__ (self , name : str , prompt : str , commands : Dict [str , Command ]):
22+ # Updated to accept a dictionary of loaded code samples
23+ def __init__ (self , name : str , prompt : str , commands : Dict [str , Command ], code_samples : Dict [str , str ]):
1824 self .name = name
1925 self .prompt = prompt
2026 self .commands = commands
27+ self .code_samples = code_samples
2128
2229 def __repr__ (self ) -> str :
23- return f"Agent(name='{ self .name } ', commands={ list (self .commands .keys ())} )"
30+ # Updated to show if code samples are loaded
31+ sample_keys = list (self .code_samples .keys ())
32+ return f"Agent(name='{ self .name } ', commands={ list (self .commands .keys ())} , samples={ sample_keys } )"
33+
34+ def get_full_prompt (self , global_policy = None ) -> str :
35+ """Constructs the full prompt including the global policy and command descriptions."""
36+ full_prompt = ""
37+ if global_policy :
38+ full_prompt += f"**GLOBAL POLICY**: { global_policy } \n \n ---\n \n "
39+
40+ full_prompt += self .prompt
2441
25- def get_full_prompt (self ) -> str :
26- """Constructs the full prompt including command descriptions for the LLM."""
27- full_prompt = self .prompt
2842 if self .commands :
2943 full_prompt += "\n \n You can use the following commands to delegate tasks:"
3044 for name , command in self .commands .items ():
3145 full_prompt += f"\n - Command: `{ name } `"
3246 full_prompt += f"\n - Description: { command .description } "
3347 full_prompt += f"\n - Target Agent: { command .target_agent } "
34- full_prompt += "YOU MUST USE THESE EXACT COMMANDS TO DELEGATE TASKS. NO OTHER FORMATTING OR COMMANDS ARE ALLOWED."
48+ full_prompt += "\n \n **YOU MUST USE THESE EXACT COMMANDS TO DELEGATE TASKS. NO OTHER FORMATTING OR COMMANDS ARE ALLOWED.**"
49+
50+ if self .code_samples :
51+ full_prompt += "\n - Code Samples Available:"
52+ for sample_name in self .code_samples .keys ():
53+ full_prompt += f"\n - `{ sample_name } `"
54+
3555 return full_prompt
3656
57+
3758class AgentSystem :
3859 """
3960 Loads and holds the entire agent system configuration from a JSON file,
40- representing the network of agents and their communication channels .
61+ including the global policy and the network of agents .
4162 """
42- def __init__ (self , agents : Dict [str , Agent ]):
63+ def __init__ (self , global_policy : str , agents : Dict [str , Agent ]):
64+ self .global_policy = global_policy
4365 self .agents = agents
4466
4567 @classmethod
4668 def load_from_json (cls , file_path : str ) -> 'AgentSystem' :
47- """Parses the JSON blueprint and builds the AgentSystem data structure."""
69+ """
70+ Parses the JSON blueprint, reads code sample files from disk,
71+ and builds the AgentSystem data structure.
72+ """
4873 print (f"Loading agent system from: { file_path } " )
74+ blueprint_path = Path (file_path ).parent
4975 with open (file_path , 'r' ) as f :
5076 config = json .load (f )
5177
78+ global_policy = config .get ('global_policy' , '' )
5279 agents : Dict [str , Agent ] = {}
80+
5381 for agent_name , agent_data in config .get ('agents' , {}).items ():
82+ # --- Load Commands (unchanged) ---
5483 commands : Dict [str , Command ] = {}
5584 for cmd_name , cmd_data in agent_data .get ('neighbors' , {}).items ():
56- command = Command (
85+ commands [ cmd_name ] = Command (
5786 name = cmd_name ,
5887 target_agent = cmd_data ['target_agent' ],
5988 description = cmd_data ['description' ]
6089 )
61- commands [cmd_name ] = command
90+
91+ loaded_samples : Dict [str , str ] = {}
92+ # Get the list of filenames from the JSON, e.g., ["load_data.py", "plot.py"]
93+ sample_filenames = agent_data .get ('code_samples' , [])
6294
95+ if sample_filenames :
96+ print (f" Loading code samples for '{ agent_name } '..." )
97+ for filename in sample_filenames :
98+ try :
99+ # Construct the full path to the sample file
100+ sample_path = CODE_SAMPLES_DIR / filename
101+ # Read the file content and store it in the dictionary
102+ loaded_samples [filename ] = sample_path .read_text (encoding = "utf-8" )
103+ print (f" ✅ Loaded { filename } " )
104+ except FileNotFoundError :
105+ print (f" ❌ WARNING: Code sample file not found and will be skipped: { sample_path } " )
106+ except Exception as e :
107+ print (f" ❌ ERROR: Could not read code sample file { sample_path } : { e } " )
108+
109+ # --- Create Agent with loaded samples ---
63110 agent = Agent (
64111 name = agent_name ,
65112 prompt = agent_data ['prompt' ],
66- commands = commands
113+ commands = commands ,
114+ code_samples = loaded_samples # Pass the dictionary of loaded code
67115 )
68116 agents [agent_name ] = agent
69117
70118 print ("Agent system loaded successfully." )
71- return cls (agents )
119+ return cls (global_policy , agents )
72120
73121 def get_agent (self , name : str ) -> Optional [Agent ]:
74122 """Retrieves an agent by its unique name."""
@@ -78,65 +126,17 @@ def get_all_agents(self) -> Dict[str, Agent]:
78126 """Returns a dictionary of all agents in the system."""
79127 return self .agents
80128
81- def get_insturctions (self ) -> str :
82- """Generates a summary of the system's instructions for the LLM."""
83- instructions = "You are part of a multi-agent system with the following agents:\n "
129+ def get_instructions (self ) -> str :
130+ """Generates a summary of the system's instructions, including the global policy."""
131+ instructions = f"**GLOBAL POLICY FOR ALL AGENTS**: { self .global_policy } \n \n ---\n \n "
132+ instructions += "**SYSTEM AGENTS**:\n "
84133 for agent in self .agents .values ():
85- instructions += f"\n - Agent: { agent .name } \n Prompt: { agent .prompt } \n "
134+ instructions += f"\n - ** Agent** : { agent .name } \n - ** Prompt** : { agent .prompt } \n "
86135 if agent .commands :
87- instructions += " Commands:\n "
136+ instructions += " - ** Commands** :\n "
88137 for cmd in agent .commands .values ():
89- instructions += f" - { cmd .name } : { cmd .description } (target : { cmd .target_agent } )\n "
138+ instructions += f" - ` { cmd .name } ` : { cmd .description } (delegates to : { cmd .target_agent } )\n "
90139 return instructions
91140
92141 def __repr__ (self ) -> str :
93- return f"AgentSystem(agents={ list (self .agents .keys ())} )"
94-
95- # --- Example Usage ---
96- if __name__ == '__main__' :
97- # 1. Define the agent system blueprint in a JSON structure
98- SYSTEM_BLUEPRINT = {
99- "agents" : {
100- "master_agent" : {
101- "prompt" : "You are the master agent. Your primary role is to analyze incoming user requests and delegate them to the appropriate specialist agent. You do not perform tasks yourself." ,
102- "neighbors" : {
103- "delegate_to_coder" : {
104- "target_agent" : "coder_agent" ,
105- "description" : "Use this command for any request that involves writing, debugging, or explaining code."
106- },
107- "delegate_to_researcher" : {
108- "target_agent" : "research_agent" ,
109- "description" : "Use this command for any request that requires searching for information, summarizing articles, or answering general knowledge questions."
110- }
111- }
112- },
113- "coder_agent" : {
114- "prompt" : "You are a specialist coder agent. Your job is to write high-quality, executable code based on the user's request. You do not delegate tasks." ,
115- "neighbors" : {}
116- },
117- "research_agent" : {
118- "prompt" : "You are a specialist research agent. You fulfill user requests by finding and synthesizing information from reliable sources. You do not write code or delegate tasks." ,
119- "neighbors" : {}
120- }
121- }
122- }
123-
124- # 2. Write the blueprint to a file
125- file_path = 'system_blueprint.json'
126- with open (file_path , 'w' ) as f :
127- json .dump (SYSTEM_BLUEPRINT , f , indent = 2 )
128-
129- # 3. Load the blueprint into the AgentSystem data structure
130- agent_system = AgentSystem .load_from_json (file_path )
131- print ("\n --- Loaded Agent System ---" )
132- print (agent_system )
133-
134- # 4. Inspect a specific agent and its full prompt
135- print ("\n --- Inspecting 'master_agent' ---" )
136- master_agent = agent_system .get_agent ('master_agent' )
137- if master_agent :
138- print (f"Agent Name: { master_agent .name } " )
139- print (f"Agent Commands: { master_agent .commands } " )
140- print ("\n --- Full Prompt for LLM ---" )
141- print (master_agent .get_full_prompt ())
142-
142+ return f"AgentSystem(global_policy='{ self .global_policy [:40 ]} ...', agents={ list (self .agents .keys ())} )"
0 commit comments