Skip to content

Support accumulated/partial streamed objects #420

@jackmpcollins

Description

@jackmpcollins

Add a new Partial class that enables accumulation of a streamed pydantic model or list/set/str/etc i.e. returns the partially received object repeatedly until the stream is complete.

Use pydantic's support for partial parsing. See https://docs.pydantic.dev/latest/concepts/experimental/#partial-validation

from magentic import prompt, Partial
from pydantic import BaseModel, Field


class Superhero(BaseModel):
    name: str
    age: int | None = None
    power: str | None = None
    enemies: list[str] = Field(default_factory=list)


@prompt("Create a Superhero named {name}.")
def create_superhero(name: str) -> Partial[Superhero]: ...


for hero in create_superhero_team("Food Dude"):
    print(hero)
# Superhero()
# Superhero(name="Food")
# Superhero(name="Food Dude")
# Superhero(name="Food Dude", age=99)
# ...

Instructor has this concept https://python.useinstructor.com/concepts/partial/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions