|
1 | 1 | from enum import Enum |
2 | 2 | from typing import Any, Dict, List, Tuple, Optional |
3 | 3 | from pydantic import BaseModel, SerializeAsAny |
4 | | -from lavague.sdk.action import Action |
| 4 | +from lavague.sdk.action import Action, ActionParser, Instruction |
5 | 5 | from lavague.sdk.action.base import DEFAULT_PARSER |
6 | 6 | from pydantic import model_validator |
| 7 | +from pydantic_core import from_json |
7 | 8 |
|
8 | 9 |
|
9 | 10 | class RunStatus(str, Enum): |
@@ -60,7 +61,53 @@ def write_to_file(self, file_path: str): |
60 | 61 | file.write(json_model) |
61 | 62 |
|
62 | 63 |
|
63 | | -class StepCompletion(BaseModel): |
64 | | - run_status: RunStatus |
| 64 | +class ActionWrapper(BaseModel): |
65 | 65 | action: Optional[Action] |
| 66 | + |
| 67 | + @classmethod |
| 68 | + def from_data( |
| 69 | + cls, |
| 70 | + data: str | bytes | bytearray, |
| 71 | + parser: ActionParser = DEFAULT_PARSER, |
| 72 | + ): |
| 73 | + obj = from_json(data) |
| 74 | + return cls.from_dict(obj, parser) |
| 75 | + |
| 76 | + @classmethod |
| 77 | + def from_dict( |
| 78 | + cls, |
| 79 | + data: Dict, |
| 80 | + parser: ActionParser = DEFAULT_PARSER, |
| 81 | + ): |
| 82 | + action = data.get("action") |
| 83 | + action = parser.parse(action) if action else None |
| 84 | + return cls.model_validate({**data, "action": action}) |
| 85 | + |
| 86 | + @model_validator(mode="before") |
| 87 | + @classmethod |
| 88 | + def deserialize_action(cls, values: Dict[str, Any]) -> Dict[str, Any]: |
| 89 | + if "action" in values: |
| 90 | + action_data = values["action"] |
| 91 | + if ( |
| 92 | + action_data |
| 93 | + and not isinstance(action_data, Action) |
| 94 | + and "action_type" in action_data |
| 95 | + ): |
| 96 | + action_class = DEFAULT_PARSER.engine_action_builders.get( |
| 97 | + action_data["action_type"], Action |
| 98 | + ) |
| 99 | + deserialized_action = action_class.parse(action_data) |
| 100 | + values["action"] = deserialized_action |
| 101 | + return values |
| 102 | + |
| 103 | + |
| 104 | +class StepKnowledge(ActionWrapper): |
| 105 | + instruction: Instruction |
| 106 | + |
| 107 | + |
| 108 | +class StepCompletion(ActionWrapper): |
| 109 | + run_status: RunStatus |
66 | 110 | run_mode: RunMode |
| 111 | + |
| 112 | + def to_knowledge(self, instruction: Instruction) -> StepKnowledge: |
| 113 | + return StepKnowledge(instruction=instruction, action=self.action) |
0 commit comments