-
Notifications
You must be signed in to change notification settings - Fork 79
/
action_service.py
286 lines (245 loc) · 10 KB
/
action_service.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
import asyncio
import json
import traceback
import typing
from typing import Any, Optional, Collection, Type, TypeVar, Iterable
import jinja2
import pydantic
from git.repo import Repo
from pydantic import ValidationError, BaseModel
from autopr.actions.base import get_actions_dict, Action, Outputs, Inputs
from autopr.log_config import get_logger
from autopr.models.config.transform import TransformsInto
from autopr.models.executable import ContextDict, ExecutableId
from autopr.models.config.elements import ActionConfig, IterableActionConfig, ValueDeclaration
from autopr.services.cache_service import CacheService, ShelveCacheService
from autopr.services.commit_service import CommitService
from autopr.services.platform_service import PlatformService
from autopr.services.publish_service import PublishService
from autopr.services.utils import truncate_strings, format_for_publishing
ActionSubclass = Action[Any, Any]
class ActionService:
# class Finished(Action):
# id = "finished"
def __init__(
self,
repo: Repo,
cache_dir: str,
platform_service: PlatformService,
commit_service: CommitService,
num_reasks: int = 3,
):
self.repo = repo
self.cache_dir = cache_dir
self.platform_service = platform_service
self.commit_service = commit_service
self.num_reasks = num_reasks
# Load all actions in the `autopr/actions` directory
self.actions: dict[ExecutableId, type[ActionSubclass]] = get_actions_dict()
self.log = get_logger(service="action_service")
def find_action(self, id_: ExecutableId) -> Optional[type[Action[Any, Any]]]:
if id_ in self.actions:
return self.actions[id_]
return None
def instantiate_action(
self,
action_type: Type[Action[Inputs, Outputs]],
publish_service: PublishService,
) -> Action[Inputs, Outputs]:
cache_service = ShelveCacheService(
cache_dir=self.cache_dir,
action_id=action_type.id,
)
return action_type(
repo=self.repo,
publish_service=publish_service,
platform_service=self.platform_service,
commit_service=self.commit_service,
cache_service=cache_service,
)
def get_action_inputs(
self,
action_type: Type[Action[Inputs, Outputs]],
action_inputs: Inputs,
context: ContextDict,
) -> Optional[Inputs]:
# Get the inputs
inputs_type = action_type._get_inputs_type()
if isinstance(None, inputs_type):
inputs = None
else:
if action_inputs is None:
specified_inputs = {}
else:
specified_inputs = action_inputs
input_values = {}
for input_name, template in specified_inputs:
# resolve prompt contexts
if isinstance(template, TransformsInto):
template = template.transform_from_config(template, context)
# resolve variable declarations
elif any(isinstance(template, t) for t in typing.get_args(ValueDeclaration)):
template = template.render(context)
# resolve string as template (backwards compatibility, should be removed)
elif isinstance(template, str):
template = context.render_nested_template(template)
if isinstance(template, pydantic.BaseModel):
template = template.dict()
if template is not None:
input_values[input_name] = template
try:
inputs = inputs_type(**input_values) # pyright: ignore[reportGeneralTypeIssues]
except ValidationError as e:
raise ValueError(f"Invalid inputs for {action_type.id}:\n\n{e}") from e
return inputs
async def _instantiate_and_run_action(
self,
action_type: Type[Action[Inputs, Outputs]],
action_id: str,
inputs: Inputs,
publish_service: PublishService,
):
if inputs is not None:
formatted_inputs = format_for_publishing(inputs)
else:
formatted_inputs = "None"
await publish_service.publish_code_block("Inputs", formatted_inputs, language="json")
# Instantiate the action
action = self.instantiate_action(
action_type=action_type,
publish_service=publish_service,
)
# Run the action
try:
outputs = await action.run(inputs)
except Exception:
self.log.exception(f"Failed to run action {action_id}")
await publish_service.publish_code_block(
heading="Error",
code=traceback.format_exc(),
language="python", # FIXME
# does nice syntax highlighting for tracebacks, but should be made configurable
)
await publish_service.end_section(f"❌ Failed {action_id}")
raise
return outputs
async def run_action(
self,
action_config: ActionConfig,
context: ContextDict,
publish_service: PublishService,
) -> ContextDict:
action_id = action_config.action
section_title = f"💧 Running `{action_id}`"
await publish_service.start_section(section_title)
action_type = self.actions[action_id]
# Get inputs
inputs = self.get_action_inputs(action_type, action_config.inputs, context)
# Run action
outputs = await self._instantiate_and_run_action(
action_type=action_type,
action_id=action_id,
inputs=inputs,
publish_service=publish_service,
)
if outputs is not None:
# Publish raw outputs
await publish_service.publish_code_block(
"Outputs",
format_for_publishing(outputs),
language="json",
)
# Extract outputs
new_context = {
context_key: getattr(outputs, output_name)
for output_name, context_key in action_config.outputs or {}
if context_key is not None
}
if new_context:
# Publish outputs
await publish_service.publish_code_block(
"New Variables",
format_for_publishing(new_context),
language="json",
)
# End the section
if publish_service.sections_stack[-1].title == section_title:
await publish_service.end_section(f"💧 Finished running `{action_id}`")
else:
await publish_service.end_section()
return ContextDict(new_context)
async def run_action_iteratively(
self,
iter_action_config: IterableActionConfig,
context: ContextDict,
publish_service: PublishService,
) -> ContextDict:
action_id = iter_action_config.action
section_title = f"💦 Iteratively running `{action_id}`"
await publish_service.start_section(section_title)
action_type = self.actions[action_id]
iteration = iter_action_config.iterate
if isinstance(iteration, int):
# iterate `iteration` times
item_name = iter_action_config.as_
iter_context = context
coros = []
for i in range(iteration):
if item_name is not None:
iter_context = ContextDict(iter_context | {item_name: i})
# Get inputs
inputs = self.get_action_inputs(
action_type, iter_action_config.inputs, iter_context
)
coros.append(
self._instantiate_and_run_action(
action_type=action_type,
action_id=action_id,
inputs=inputs,
publish_service=await publish_service.create_child(f"💧 Iteration {i+1}"),
)
)
else: # isinstance(iteration, ContextVarPath)
# iterate over a list in the context
list_var = context.get_path(iteration)
if not isinstance(list_var, Iterable):
raise ValueError(f"Expected {iteration} to be an iterable")
# Get inputs including the list item
item_name = iter_action_config.as_
if item_name is None:
raise ValueError("Expected `as` to be specified for action iterating over a list")
coros = []
for item in list_var:
iter_context = ContextDict(context | {item_name: item})
inputs = self.get_action_inputs(
action_type, iter_action_config.inputs, iter_context
)
coros.append(
self._instantiate_and_run_action(
action_type=action_type,
action_id=action_id,
inputs=inputs,
publish_service=await publish_service.create_child(
title=f"💧 Iteration: `{truncate_strings(str(item), length=40)}`"
),
)
)
# Gather the action runs
outputses = await asyncio.gather(*coros)
# Extract outputs
new_context = {}
for output_name, context_key in iter_action_config.list_outputs or {}:
if context_key is None:
continue
new_context[context_key] = [getattr(outputs, output_name) for outputs in outputses]
await publish_service.publish_code_block(
"Outputs",
format_for_publishing(new_context),
language="json",
)
# End the section
if publish_service.sections_stack[-1].title == section_title:
await publish_service.end_section(f"💦 Finished iterating `{action_id}`")
else:
await publish_service.end_section()
return ContextDict(new_context)