forked from Intelligent-Internet/ii-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
206 lines (176 loc) · 6.94 KB
/
Copy pathcli.py
File metadata and controls
206 lines (176 loc) · 6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env python3
"""
CLI interface for the Agent.
This script provides a command-line interface for interacting with the Agent.
It instantiates an Agent and prompts the user for input, which is then passed to the Agent.
"""
import os
import argparse
import logging
import asyncio
from dotenv import load_dotenv
load_dotenv()
from ii_agent.core.event import RealtimeEvent, EventType
from ii_agent.utils.constants import DEFAULT_MODEL
from utils import parse_common_args, create_workspace_manager_for_connection
from rich.console import Console
from rich.panel import Panel
from ii_agent.tools import get_system_tools
from ii_agent.prompts.system_prompt import SYSTEM_PROMPT
from ii_agent.agents.anthropic_fc import AnthropicFC
from ii_agent.utils import WorkspaceManager
from ii_agent.llm import get_client
from ii_agent.llm.context_manager.llm_summarizing import LLMSummarizingContextManager
from ii_agent.llm.context_manager.amortized_forgetting import (
AmortizedForgettingContextManager,
)
from ii_agent.llm.token_counter import TokenCounter
from ii_agent.db.manager import DatabaseManager
MAX_OUTPUT_TOKENS_PER_TURN = 32768
MAX_TURNS = 200
async def async_main():
"""Async main entry point"""
# Parse command-line arguments
parser = argparse.ArgumentParser(description="CLI for interacting with the Agent")
parser = parse_common_args(parser)
args = parser.parse_args()
if os.path.exists(args.logs_path):
os.remove(args.logs_path)
logger_for_agent_logs = logging.getLogger("agent_logs")
logger_for_agent_logs.setLevel(logging.DEBUG)
# Prevent propagation to root logger to avoid duplicate logs
logger_for_agent_logs.propagate = False
logger_for_agent_logs.addHandler(logging.FileHandler(args.logs_path))
if not args.minimize_stdout_logs:
logger_for_agent_logs.addHandler(logging.StreamHandler())
# Initialize console
console = Console()
# Initialize database manager
db_manager = DatabaseManager()
# Create a new workspace manager for the CLI session
workspace_manager, session_id = create_workspace_manager_for_connection(
args.workspace, args.use_container_workspace
)
workspace_path = workspace_manager.root
# Create a new session and get its workspace directory
db_manager.create_session(
session_uuid=session_id, workspace_path=workspace_manager.root
)
logger_for_agent_logs.info(
f"Created new session {session_id} with workspace at {workspace_manager.root}"
)
# Print welcome message
if not args.minimize_stdout_logs:
console.print(
Panel(
"[bold]Agent CLI[/bold]\n\n"
+ f"Session ID: {session_id}\n"
+ f"Workspace: {workspace_path}\n\n"
+ "Type your instructions to the agent. Press Ctrl+C to exit.\n"
+ "Type 'exit' or 'quit' to end the session.",
title="[bold blue]Agent CLI[/bold blue]",
border_style="blue",
padding=(1, 2),
)
)
else:
logger_for_agent_logs.info(
f"Agent CLI started with session {session_id}. Waiting for user input. Press Ctrl+C to exit. Type 'exit' or 'quit' to end the session."
)
# Initialize LLM client
client = get_client(
"anthropic-direct",
model_name=DEFAULT_MODEL,
use_caching=False,
project_id=args.project_id,
region=args.region,
)
# Initialize workspace manager with the session-specific workspace
workspace_manager = WorkspaceManager(
root=workspace_path, container_workspace=args.use_container_workspace
)
# Initialize token counter
token_counter = TokenCounter()
# Create context manager based on argument
if args.context_manager == "llm-summarizing":
context_manager = LLMSummarizingContextManager(
client=client,
token_counter=token_counter,
logger=logger_for_agent_logs,
token_budget=120_000,
)
elif args.context_manager == "amortized-forgetting":
context_manager = AmortizedForgettingContextManager(
token_counter=token_counter,
logger=logger_for_agent_logs,
token_budget=120_000,
)
else:
raise ValueError(f"Unknown context manager type: {args.context_manager}")
queue = asyncio.Queue()
tools = get_system_tools(
client=client,
workspace_manager=workspace_manager,
message_queue=queue,
container_id=args.docker_container_id,
ask_user_permission=args.needs_permission,
tool_args={
"deep_research": False,
"pdf": True,
"media_generation": False,
"audio_generation": False,
"browser": True,
"memory_tool": args.memory_tool,
},
)
agent = AnthropicFC(
system_prompt=SYSTEM_PROMPT,
client=client,
workspace_manager=workspace_manager,
tools=tools,
message_queue=queue,
logger_for_agent_logs=logger_for_agent_logs,
context_manager=context_manager,
max_output_tokens_per_turn=MAX_OUTPUT_TOKENS_PER_TURN,
max_turns=MAX_TURNS,
session_id=session_id, # Pass the session_id from database manager
)
# Create background task for message processing
message_task = agent.start_message_processing()
loop = asyncio.get_running_loop()
# Main interaction loop
try:
while True:
# Use async input
user_input = await loop.run_in_executor(None, lambda: input("User input: "))
agent.message_queue.put_nowait(
RealtimeEvent(type=EventType.USER_MESSAGE, content={"text": user_input})
)
if user_input.lower() in ["exit", "quit"]:
console.print("[bold]Exiting...[/bold]")
logger_for_agent_logs.info("Exiting...")
break
logger_for_agent_logs.info("\nAgent is thinking...")
try:
# Run synchronous method in executor
result = await loop.run_in_executor(
None, # Uses default ThreadPoolExecutor
lambda: agent.run_agent(user_input, resume=True),
)
logger_for_agent_logs.info(f"Agent: {result}")
except (KeyboardInterrupt, asyncio.CancelledError):
agent.cancel()
logger_for_agent_logs.info("Agent cancelled")
except Exception as e:
logger_for_agent_logs.info(f"Error: {str(e)}")
logger_for_agent_logs.debug("Full error:", exc_info=True)
logger_for_agent_logs.info("\n" + "-" * 40 + "\n")
except KeyboardInterrupt:
console.print("\n[bold]Session interrupted. Exiting...[/bold]")
loop.stop()
finally:
# Cleanup tasks
message_task.cancel()
console.print("[bold]Goodbye![/bold]")
if __name__ == "__main__":
asyncio.run(async_main())