-
Notifications
You must be signed in to change notification settings - Fork 52
/
repl.py
309 lines (260 loc) · 11 KB
/
repl.py
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import abc
import contextlib
import logging
import signal
import uuid
from abc import ABC
from functools import partial
from json import JSONDecodeError
from typing import Any, Dict, List, Optional, Type, Union, cast
import requests
from steamship import Block, Steamship, Task, TaskState
from steamship.agents.logging import AgentLogging
from steamship.agents.schema import AgentContext, Tool
from steamship.agents.service.agent_service import AgentService
from steamship.data import TagKind, TagValueKey
from steamship.data.tags.tag_utils import get_tag
from steamship.data.workspace import Workspace
from steamship.invocable.dev_logging_handler import DevelopmentLoggingHandler
try:
from termcolor import colored # noqa: F401
except ImportError:
def colored(text: str, color: str, **kwargs):
print(text)
class SteamshipREPL(ABC):
"""Base class for building REPLs that facilitate running Steamship code in the IDE."""
client: Steamship
dev_logging_handler: DevelopmentLoggingHandler
def __init__(
self,
log_level=None,
dev_logging_handler=None,
):
if not dev_logging_handler:
self.dev_logging_handler = DevelopmentLoggingHandler.init_and_take_root()
else:
self.dev_logging_handler = dev_logging_handler
def print_string(self, output: str, metadata: Optional[Dict[str, Any]] = None):
"""Print a string to console. All REPL output should ideally route through this method."""
logging.info(
f"{output}",
extra={
AgentLogging.IS_MESSAGE: True,
AgentLogging.MESSAGE_AUTHOR: AgentLogging.AGENT,
AgentLogging.MESSAGE_TYPE: AgentLogging.MESSAGE,
},
)
def print_object(
self, obj: Union[Task, Block, str, dict], metadata: Optional[Dict[str, Any]] = None
):
"""Print an object, returned by the agent or tool, to the console.
Various epochs of the Agent SDK development have included Agents returning, to the repl: Blocks, strings, and
Tasks. Since this is something that users can write (e.g. not controlled by the SDK) the REPL needs to handle
all three cases in displaying output.
"""
# A string gets printed wholesale.
if isinstance(obj, str):
self.print_string(obj, metadata)
return
# A task gets its ID printed.
# TODO: It would be nice for this to be a link to the web UI.
if isinstance(obj, Task):
self.print_string(f"Task: {obj.task_id}", metadata)
return
# A dict is assumed to be a Block.
if isinstance(obj, dict):
obj = Block.parse_obj(obj)
# A block gets handled based on what it contains.
block = cast(Block, obj)
output = None
if block.is_text():
output = block.text
elif block.url:
output = block.url
elif block.content_url:
output = block.content_url
elif block.id:
block.set_public_data(True)
output = f"{self.client.config.api_base}block/{block.id}/raw"
if output:
self.print_string(output, metadata)
def print_object_or_objects(
self, output: Union[List, Any], metadata: Optional[Dict[str, Any]] = None
):
"""Print Agent or Tool output, whether a list or a single object."""
if isinstance(output, List):
objects = cast(List, output)
for obj in objects:
self.print_object(obj, metadata)
else:
self.print_object(output, metadata)
@contextlib.contextmanager
def temporary_workspace(self) -> Steamship:
workspace = Workspace.create(client=self.client)
temp_client = Steamship(workspace=workspace.handle)
yield temp_client
workspace.delete()
@abc.abstractmethod
def run(self):
raise NotImplementedError()
class ToolREPL(SteamshipREPL):
tool: Tool
client = Steamship
def __init__(self, tool: Tool, client: Optional[Steamship] = None, **kwargs):
super().__init__(**kwargs)
self.tool = tool
self.client = client or Steamship()
def run_with_client(self, client: Workspace, context: Optional[AgentContext] = None):
if context is None:
context = AgentContext()
context.client = client
print(f"Starting REPL for Tool {self.tool.name}...")
print("If you make code changes, restart this REPL. Press CTRL+C to exit at any time.\n")
while True:
input_text = input(colored("Input: ", "blue")) # noqa: F821
input_block = Block(text=input_text)
output = self.tool.run([input_block], context=context)
self.print_object_or_objects(output)
def run(self):
with self.temporary_workspace() as client:
self.run_with_client(client)
class AgentREPL(SteamshipREPL):
agent_class: Type[AgentService]
agent_instance: Optional[AgentService]
context_id: Optional[str] = None
client = Steamship
config = None
def __init__(
self,
agent_class: Type[AgentService],
method: Optional[str] = None,
agent_package_config: Optional[Dict[str, Any]] = None,
client: Optional[Steamship] = None,
context_id: Optional[str] = None,
**kwargs,
):
super().__init__(**kwargs)
self.agent_class = agent_class
self.method = method
self.client = client or Steamship()
self.config = agent_package_config
self.agent_instance = None
self.context_id = context_id or str(uuid.uuid4())
def run_with_client(self, client: Steamship, **kwargs):
try:
from termcolor import colored # noqa: F401
except ImportError:
def colored(text: str, color: str, **kwargs):
return text
print("Starting REPL for Agent...")
print("If you make code changes, restart this REPL. Press CTRL+C to exit at any time.\n")
self.agent_instance = self.agent_class(client=client, config=self.config)
# Determine the responder, which may have been custom-supplied on the agent.
responder = getattr(self.agent_instance, self.method or "prompt")
while True:
input_text = input(colored(text="Input: ", color="blue")) # noqa: F821
output = responder(prompt=input_text, context_id=self.context_id, **kwargs)
self.print_object_or_objects(output)
def run(self, dump_history_on_exit: Optional[bool] = False, **kwargs):
with self.temporary_workspace() as client:
if dump_history_on_exit:
signal.signal(signal.SIGTERM, partial(self.print_history, client))
signal.signal(signal.SIGINT, partial(self.print_history, client))
self.run_with_client(client, **kwargs)
def print_history(self, client: Steamship, *args, **kwargs):
agent_ctx = AgentContext.get_or_create(
client=client, context_keys={"id": f"{self.context_id}"}
)
print(f"\n\n----- Agent Chat History {agent_ctx.id} -----\n")
history = agent_ctx.chat_history
history.refresh()
for block in history.messages:
chat_role = block.chat_role
status_msg = get_tag(block.tags, kind=TagKind.STATUS_MESSAGE)
if not chat_role and not status_msg:
continue
if chat_role:
prefix = f"[{chat_role}]"
else:
if value := status_msg.value:
prefix = f"[{value.get(TagValueKey.STRING_VALUE)} status]"
else:
prefix = "[status]"
if block.is_text():
print(f"{prefix} {block.text}")
else:
print(f"{prefix} {block.id} ({block.mime_type})")
print("\n------------------------------\n")
exit(0)
class HttpREPL(SteamshipREPL):
"""REPL that uses an HTTP endpoint. Best for the `ship serve` command."""
prompt_url: Optional[str]
client = Steamship
config = None
context_id: Optional[str] = None
def __init__(
self,
prompt_url: str,
context_id: Optional[str] = None,
client: Optional[Steamship] = None,
**kwargs,
):
super().__init__(**kwargs)
self.prompt_url = prompt_url
self.client = client or Steamship()
self.context_id = context_id or str(uuid.uuid4())
def run_with_client(self, client: Steamship, **kwargs): # noqa: C901
try:
from termcolor import colored # noqa: F401
except ImportError:
def colored(text: str, color: str):
print(text)
print("Starting REPL for Agent...")
print("If you make code changes, restart this REPL. Press CTRL+C to exit at any time.\n")
while True:
input_text = input(colored(text="Input: ", color="blue")) # noqa: F821
resp = requests.post(
self.prompt_url,
json={"prompt": input_text, "context_id": self.context_id},
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.client.config.api_key.get_secret_value()}",
},
)
result = None
if not resp.ok:
logging.error(
f"Request to AgentService failed with HTTP Status {resp.status_code}."
)
logging.error(f"Message: {resp.text}")
try:
result = resp.json()
except JSONDecodeError as ex:
logging.exception(ex)
except BaseException as ex:
logging.exception(ex)
if result:
if isinstance(result, dict):
if result.get("status", {}).get("state", None) == TaskState.failed:
message = result.get("status", {}).get("status_message", None)
logging.error(
f"Response failed with remote error: {message or 'No message'}"
)
if suggestion := result.get("status", {}).get("status_suggestion", None):
logging.error(f"Suggestion: {suggestion}")
elif data := result.get("data", None):
self.print_object_or_objects(data)
else:
logging.warning(
"REPL interaction completed with empty data field in InvocableResponse."
)
elif isinstance(result, list):
self.print_object_or_objects(result)
else:
logging.warning("Unsure how to display result:")
logging.warning(f"{result}")
else:
logging.warning("REPL interaction completed with no result to print.")
def run(self, **kwargs):
with self.temporary_workspace() as client:
self.run_with_client(client, **kwargs)