|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import typing |
| 4 | +from typing import Any, get_args, get_origin |
| 5 | + |
| 6 | +from pydantic import BaseModel |
| 7 | + |
| 8 | + |
| 9 | +class LifecycleState(BaseModel): |
| 10 | + name: str |
| 11 | + description: str = "" |
| 12 | + waits_for_input: bool = False |
| 13 | + accepts: list[str] = [] |
| 14 | + transitions: list[str] = [] |
| 15 | + |
| 16 | + |
| 17 | +class AgentLifecycle(BaseModel): |
| 18 | + states: list[LifecycleState] |
| 19 | + initial_state: str |
| 20 | + queries: list[str] = [] |
| 21 | + |
| 22 | + |
| 23 | +class AgentCard(BaseModel): |
| 24 | + protocol: str = "acp" |
| 25 | + lifecycle: AgentLifecycle | None = None |
| 26 | + data_events: list[str] = [] |
| 27 | + input_types: list[str] = [] |
| 28 | + output_schema: dict | None = None |
| 29 | + |
| 30 | + @classmethod |
| 31 | + def from_state_machine( |
| 32 | + cls, |
| 33 | + state_machine: Any, |
| 34 | + output_event_model: type[BaseModel] | None = None, |
| 35 | + extra_input_types: list[str] | None = None, |
| 36 | + queries: list[str] | None = None, |
| 37 | + ) -> AgentCard: |
| 38 | + lifecycle_data = state_machine.get_lifecycle() |
| 39 | + lifecycle_data["queries"] = queries or [] |
| 40 | + |
| 41 | + data_events: list[str] = [] |
| 42 | + output_schema: dict | None = None |
| 43 | + if output_event_model: |
| 44 | + data_events = extract_literal_values(output_event_model, "type") |
| 45 | + output_schema = output_event_model.model_json_schema() |
| 46 | + |
| 47 | + derived_input_types: set[str] = set() |
| 48 | + for state in lifecycle_data["states"]: |
| 49 | + derived_input_types.update(state.get("accepts", [])) |
| 50 | + |
| 51 | + return cls( |
| 52 | + lifecycle=AgentLifecycle.model_validate(lifecycle_data), |
| 53 | + data_events=data_events, |
| 54 | + input_types=sorted(derived_input_types | set(extra_input_types or [])), |
| 55 | + output_schema=output_schema, |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +def extract_literal_values(model: type[BaseModel], field: str) -> list[str]: |
| 60 | + """Extract allowed values from a Literal[...] type annotation on a Pydantic model field.""" |
| 61 | + field_info = model.model_fields.get(field) |
| 62 | + if field_info is None: |
| 63 | + return [] |
| 64 | + |
| 65 | + annotation = field_info.annotation |
| 66 | + if annotation is None: |
| 67 | + return [] |
| 68 | + |
| 69 | + # Unwrap Optional (Union[X, None]) to get the inner type |
| 70 | + if get_origin(annotation) is typing.Union: |
| 71 | + args = [a for a in get_args(annotation) if a is not type(None)] |
| 72 | + annotation = args[0] if len(args) == 1 else annotation |
| 73 | + |
| 74 | + if get_origin(annotation) is typing.Literal: |
| 75 | + return list(get_args(annotation)) |
| 76 | + |
| 77 | + return [] |
0 commit comments