|
| 1 | +from temporalio import activity |
| 2 | +from openai import AsyncOpenAI |
| 3 | +import braintrust |
| 4 | +from braintrust import wrap_openai |
| 5 | +from typing import Optional, List, cast, Any, TypeVar, Generic |
| 6 | +from typing_extensions import Annotated |
| 7 | +from pydantic import BaseModel |
| 8 | +from pydantic.functional_validators import BeforeValidator |
| 9 | +from pydantic.functional_serializers import PlainSerializer |
| 10 | + |
| 11 | +import importlib |
| 12 | +import os |
| 13 | + |
| 14 | +T = TypeVar("T", bound=BaseModel) |
| 15 | + |
| 16 | + |
| 17 | +def _coerce_class(v: Any) -> type[Any]: |
| 18 | + """Pydantic validator: convert string path to class during deserialization.""" |
| 19 | + if isinstance(v, str): |
| 20 | + mod_path, sep, qual = v.partition(":") |
| 21 | + if not sep: # support "package.module.Class" |
| 22 | + mod_path, _, qual = v.rpartition(".") |
| 23 | + module = importlib.import_module(mod_path) |
| 24 | + obj = module |
| 25 | + for attr in qual.split("."): |
| 26 | + obj = getattr(obj, attr) |
| 27 | + return cast(type[Any], obj) |
| 28 | + elif isinstance(v, type): |
| 29 | + return v |
| 30 | + else: |
| 31 | + raise ValueError(f"Cannot coerce {v} to class") |
| 32 | + |
| 33 | + |
| 34 | +def _dump_class(t: type[Any]) -> str: |
| 35 | + """Pydantic serializer: convert class to string path during serialization.""" |
| 36 | + return f"{t.__module__}:{t.__qualname__}" |
| 37 | + |
| 38 | + |
| 39 | +# Custom type that automatically handles class <-> string conversion in Pydantic serialization |
| 40 | +ClassReference = Annotated[ |
| 41 | + type[T], |
| 42 | + BeforeValidator(_coerce_class), |
| 43 | + PlainSerializer(_dump_class, return_type=str), |
| 44 | +] |
| 45 | + |
| 46 | + |
| 47 | +class InvokeModelRequest(BaseModel, Generic[T]): |
| 48 | + model: str |
| 49 | + instructions: str # Fallback if Braintrust prompt unavailable |
| 50 | + input: str |
| 51 | + prompt_slug: Optional[str] = None # Braintrust prompt slug (e.g., "report-synthesis") |
| 52 | + response_format: Optional[ClassReference[T]] = None |
| 53 | + tools: Optional[List[dict]] = None |
| 54 | + |
| 55 | + |
| 56 | +class InvokeModelResponse(BaseModel, Generic[T]): |
| 57 | + # response_format records the type of the response model |
| 58 | + response_format: Optional[ClassReference[T]] = None |
| 59 | + response_model: Any |
| 60 | + |
| 61 | + @property |
| 62 | + def response(self) -> T: |
| 63 | + """Reconstruct the original response type if response_format was provided.""" |
| 64 | + if self.response_format: |
| 65 | + model_cls = self.response_format |
| 66 | + return model_cls.model_validate(self.response_model) |
| 67 | + return self.response_model |
| 68 | + |
| 69 | + |
| 70 | +@activity.defn |
| 71 | +async def invoke_model(request: InvokeModelRequest[T]) -> InvokeModelResponse[T]: |
| 72 | + instructions = request.instructions |
| 73 | + |
| 74 | + # Load prompt from Braintrust if slug provided |
| 75 | + if request.prompt_slug: |
| 76 | + try: |
| 77 | + prompt = braintrust.load_prompt( |
| 78 | + project=os.environ.get("BRAINTRUST_PROJECT", "deep-research"), |
| 79 | + slug=request.prompt_slug, |
| 80 | + ) |
| 81 | + # Extract system message content only |
| 82 | + # NOTE: Other params (temperature, max_tokens, model) are NOT used |
| 83 | + built = prompt.build() |
| 84 | + for msg in built.get("messages", []): |
| 85 | + if msg.get("role") == "system": |
| 86 | + instructions = msg["content"] |
| 87 | + activity.logger.info( |
| 88 | + f"Loaded prompt '{request.prompt_slug}' from Braintrust" |
| 89 | + ) |
| 90 | + break |
| 91 | + except Exception as e: |
| 92 | + # Log warning but continue with fallback |
| 93 | + activity.logger.warning( |
| 94 | + f"Failed to load prompt '{request.prompt_slug}': {e}. " |
| 95 | + "Using hardcoded fallback." |
| 96 | + ) |
| 97 | + |
| 98 | + client = wrap_openai(AsyncOpenAI(max_retries=0)) |
| 99 | + |
| 100 | + kwargs: dict[str, Any] = { |
| 101 | + "model": request.model, |
| 102 | + "instructions": instructions, |
| 103 | + "input": request.input, |
| 104 | + } |
| 105 | + |
| 106 | + if request.response_format: |
| 107 | + kwargs["text_format"] = request.response_format |
| 108 | + |
| 109 | + if request.tools: |
| 110 | + kwargs["tools"] = request.tools |
| 111 | + |
| 112 | + # Use responses API consistently |
| 113 | + resp = await client.responses.parse(**kwargs) |
| 114 | + |
| 115 | + if request.response_format: |
| 116 | + # Convert structured response to dict for managed serialization. |
| 117 | + # This allows us to reconstruct the original response type while maintaining type safety. |
| 118 | + parsed_model = cast(BaseModel, resp.output_parsed) |
| 119 | + return InvokeModelResponse( |
| 120 | + response_model=parsed_model.model_dump(), |
| 121 | + response_format=request.response_format, |
| 122 | + ) |
| 123 | + else: |
| 124 | + return InvokeModelResponse( |
| 125 | + response_model=resp.output_text, response_format=None |
| 126 | + ) |
0 commit comments