Skip to content

Deserialize return_value of task result back to Pydantic model? #558

@tnychn

Description

@tnychn

Since I couldn't find any docs about Taskiq's Pydantic integration/behavior,

Suppose I have the following task:

@broker.task
async def analyze_audio(
    audio_b64: str,
    transcript: Transcript,
    context: Annotated[Context, TaskiqDepends()],
) -> Analysis | None:
    audio = base64.b64decode(audio_b64)
    return await context.state.pipeline(audio, transcript)

where both Transcript and Analysis are Pydantic models.

When retrieving the result, broker.result_backend.get_result returns TaskiqResult and TaskiqResult.return_value is a dict.
So I often need to do an extra step of model_validate on it.

task_result = await broker.result_backend.get_result(str(id))
value = task_result.return_value  # dict or None
if value is None:
    return None
return Analysis.model_validate(value)

Taskiq can handle Pydantic models for task arguments. I expect it can handle that for task return value as well.

Is it possible to support this Taskiq? This seems to be a trivial use case and the inconsistent behavior causes confusion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions