1+ """
2+ Single Agent CLI Feature Handler
3+
4+ Provides CLI commands for running a single agent:
5+ - praisonai agent run --name "assistant" --task "Hello world" --tool-search auto
6+
7+ Example:
8+ praisonai agent run \
9+ --name "assistant" \
10+ --instructions "You are a helpful assistant" \
11+ --task "Help me with something" \
12+ --tool-search auto
13+ """
14+
15+ import os
16+ from typing import Optional , List , Dict , Any , Union
17+
18+
19+ def parse_tool_search_param (value : str ) -> Union [bool , str , Dict [str , Any ]]:
20+ """Parse tool_search parameter from CLI.
21+
22+ Args:
23+ value: String value from CLI parameter
24+
25+ Returns:
26+ Parsed value for tool_search parameter
27+ """
28+ if value .lower () in ('false' , 'off' , 'disabled' ):
29+ return False
30+ elif value .lower () in ('true' , 'on' , 'enabled' ):
31+ return True
32+ elif value .lower () in ('auto' ,):
33+ return "auto"
34+ else :
35+ # Try to parse as JSON for advanced config
36+ try :
37+ import json
38+ return json .loads (value )
39+ except (json .JSONDecodeError , ValueError ):
40+ # Treat as mode string
41+ return value
42+
43+
44+ class SingleAgentHandler :
45+ """Handler for single agent CLI commands."""
46+
47+ def __init__ (self , verbose : bool = True ):
48+ """Initialize the single agent handler.
49+
50+ Args:
51+ verbose: Whether to print verbose output
52+ """
53+ self .verbose = verbose
54+
55+ def _load_tools (self , tool_names : List [str ]) -> List :
56+ """Load tool functions by name.
57+
58+ Args:
59+ tool_names: List of tool names to load
60+
61+ Returns:
62+ List of tool functions
63+ """
64+ tools = []
65+
66+ try :
67+ from praisonaiagents .tools import (
68+ internet_search , read_file , write_file , list_files ,
69+ execute_command , read_csv , write_csv , analyze_csv
70+ )
71+
72+ tool_map = {
73+ 'internet_search' : internet_search ,
74+ 'read_file' : read_file ,
75+ 'write_file' : write_file ,
76+ 'list_files' : list_files ,
77+ 'execute_command' : execute_command ,
78+ 'read_csv' : read_csv ,
79+ 'write_csv' : write_csv ,
80+ 'analyze_csv' : analyze_csv ,
81+ }
82+
83+ for name in tool_names :
84+ if name in tool_map :
85+ tools .append (tool_map [name ])
86+ else :
87+ if self .verbose :
88+ print (f"⚠ Tool '{ name } ' not found, skipping" )
89+ except ImportError as e :
90+ if self .verbose :
91+ print (f"⚠ Could not load tools: { e } " )
92+
93+ return tools
94+
95+ def run (
96+ self ,
97+ name : str = "assistant" ,
98+ instructions : Optional [str ] = None ,
99+ task : str = "Hello" ,
100+ llm : Optional [str ] = None ,
101+ tools : Optional [List [str ]] = None ,
102+ tool_search : Optional [str ] = None ,
103+ memory : bool = False ,
104+ verbose : bool = False
105+ ) -> str :
106+ """Run a single agent with the given parameters.
107+
108+ Args:
109+ name: Agent name
110+ instructions: Agent instructions
111+ task: Task to execute
112+ llm: LLM model to use
113+ tools: List of tool names
114+ tool_search: Tool search configuration
115+ memory: Whether to enable memory
116+ verbose: Whether to enable verbose output
117+
118+ Returns:
119+ Agent execution result
120+ """
121+ try :
122+ from praisonaiagents import Agent
123+
124+ # Parse tool_search parameter
125+ tool_search_config = None
126+ if tool_search :
127+ tool_search_config = parse_tool_search_param (tool_search )
128+
129+ # Load tools if specified
130+ agent_tools = None
131+ if tools :
132+ agent_tools = self ._load_tools (tools )
133+
134+ # Create and run agent
135+ agent = Agent (
136+ name = name ,
137+ instructions = instructions or f"You are a helpful agent named { name } ." ,
138+ llm = llm or os .environ .get ('OPENAI_MODEL_NAME' , 'gpt-4o-mini' ),
139+ tools = agent_tools ,
140+ tool_search = tool_search_config ,
141+ memory = memory ,
142+ verbose = verbose
143+ )
144+
145+ if self .verbose :
146+ print (f"\n 🚀 Running agent '{ name } '..." )
147+ print (f"Task: { task } " )
148+ if tool_search_config :
149+ print (f"Tool Search: { tool_search_config } " )
150+ print ()
151+
152+ result = agent .start (task )
153+ return str (result )
154+
155+ except Exception as e :
156+ if self .verbose :
157+ print (f"❌ Execution failed: { e } " )
158+ raise
159+
160+
161+ def handle_agent_command (args ) -> int :
162+ """Handle agent subcommand from CLI.
163+
164+ Args:
165+ args: Parsed command line arguments
166+
167+ Returns:
168+ Exit code (0 for success, non-zero for error)
169+ """
170+ handler = SingleAgentHandler (verbose = True )
171+
172+ try :
173+ if args .agent_command == "run" :
174+ result = handler .run (
175+ name = getattr (args , 'name' , 'assistant' ),
176+ instructions = getattr (args , 'instructions' , None ),
177+ task = getattr (args , 'task' , 'Hello' ),
178+ llm = getattr (args , 'llm' , None ),
179+ tools = getattr (args , 'tools' , None ),
180+ tool_search = getattr (args , 'tool_search' , None ),
181+ memory = getattr (args , 'memory' , False ),
182+ verbose = getattr (args , 'verbose' , False )
183+ )
184+
185+ print ("\n " + "=" * 50 )
186+ print ("RESULT:" )
187+ print ("=" * 50 )
188+ print (result )
189+
190+ else :
191+ print (f"Unknown agent command: { args .agent_command } " )
192+ return 1
193+
194+ except Exception as e :
195+ print (f"Error: { e } " )
196+ return 1
197+
198+ return 0
199+
200+
201+ def add_agent_parser (subparsers ) -> None :
202+ """Add agent subcommand to argument parser.
203+
204+ Args:
205+ subparsers: Subparsers object from argparse
206+ """
207+ # run command
208+ run_parser = subparsers .add_parser (
209+ 'run' ,
210+ help = 'Run a single agent with specified parameters'
211+ )
212+ run_parser .add_argument (
213+ '--name' , '-n' ,
214+ default = 'assistant' ,
215+ help = 'Agent name (default: assistant)'
216+ )
217+ run_parser .add_argument (
218+ '--instructions' , '-i' ,
219+ help = 'Agent instructions'
220+ )
221+ run_parser .add_argument (
222+ '--task' , '-t' ,
223+ default = 'Hello' ,
224+ help = 'Task for the agent to complete (default: Hello)'
225+ )
226+ run_parser .add_argument (
227+ '--llm' , '-m' ,
228+ help = 'LLM model to use'
229+ )
230+ run_parser .add_argument (
231+ '--tools' ,
232+ action = 'append' ,
233+ help = 'Tool names to load (can be used multiple times)'
234+ )
235+ run_parser .add_argument (
236+ '--tool-search' ,
237+ help = 'Tool search configuration (false/true/auto or JSON config)'
238+ )
239+ run_parser .add_argument (
240+ '--memory' ,
241+ action = 'store_true' ,
242+ help = 'Enable agent memory'
243+ )
244+ run_parser .add_argument (
245+ '--verbose' , '-v' ,
246+ action = 'store_true' ,
247+ help = 'Enable verbose output'
248+ )
0 commit comments