Skip to content

Clean up Context and Component Formatting #952

Closed

Description

@nrfulton

To support model agnosticism, the system design originally converted contests into conversation JSON format using this pipeline:

Context --> list of Components --> list of `stdlib.chat.Messages` --> conversation JSON to pass to model endpoint

There were pretty specific contracts at each point in this pipeline, and it was really important that each Message was only content + role + optional image. (That's why there is a special code path for Message in utils.py).

This has a couple of problems:

  1. we're using stdlib.chat.Messages as both a Component and an IR for the pipeline. This special treatment is bad, because it creates a special case treatment for Message, which leads to bugs (see: Documents dropped in standard chat context path (generate_from_chat_context) #949)
  2. some APIs/models want us to break out images/docs/tools/etc. into top-level fields.
  3. some APIs/models don't want us to do that same break-out

This means that we need an additional step in backends that extracts stuff from template reprs and puts it into other api args or fields on the conversation json.

Propose fixing this by making the flow look more like:

Context --> formatted Components   |--> content  --> content with inlined stuff not extractable to api args |
        |      AND their         ->|               ^                                                        |--> conversation JSON + api args
        |-> Template Reprs.        |--> API Args --|                                                        |
		* docs
		* images
		* etc.

The pipeline psuedocode looks like:

msgs = list[Component | CBlock | ModelOutputThunk] = context.to_list()

formatted_messages : list[Tuple[RoleName, MessageContents, TemplateRepresentation]] = [Formatter.format(msg) for msg in msgs]
# where RoleName == str, MessageContents == str, TemplateRepresentation is a dict with stuff that we might want to extract.

# this code depends on whether doc handling can be done entirely by the formatter or not.
# ie, whether it's a model-specific thing or a mode l +infernce engine thing.
if model and IE have special docs handling:
	api_args.extend(...or wahtever..)
else:
	formatted_messages : list[Tuple[RoleName, MessageContents, TemplateRepresentation]] = [Formatter.inline_docs(msg) for msg in msgs]


# and similar for images and other stuff...

Activity

  1. nrfulton commented on Apr 28, 2026

    @nrfulton
    MemberAuthor

    Then we need to add docs to TemplateRepresentation:

    @dataclass
    class TemplateRepresentation:
        """Representing a component as a set of important attributes that can be consumed by the formatter.
    
        Args:
            obj (Any): The original component object being represented.
            args (dict): Named arguments extracted from the component for template substitution.
            tools (dict[str, AbstractMelleaTool] | None): Tools available for this representation,
                keyed by the tool's function name. Defaults to ``None``.
            fields (list[Any] | None): An optional ordered list of field values for positional templates.
            template (str | None): An optional Jinja2 template string to use when rendering.
            template_order (list[str] | None): An optional ordering hint for template sections/keys.
            images (list[ImageBlock] | None): Optional list of image blocks associated with this representation.
            +docs (list[Document] | None): Optional list of Documents associated with this component.
    
        """
    
        obj: Any
        args: dict[
            str,
            str | Component | CBlock | Iterable | Mapping | TemplateRepresentation | None,
        ]
        tools: dict[str, AbstractMelleaTool] | None = (
            None  # the key must be the name of the function.
        )
        fields: list[Any] | None = None
        template: str | None = None
        template_order: list[str] | None = None
        images: list[ImageBlock] | None = None
        +docs: list[Document] | None = None
    +
    +
       + # somewhere assert "docs" not in args.keys() if docs is not None <- not sure how to do that at instantiation for a dataclass...
    
  2. nrfulton commented on Apr 28, 2026

    @nrfulton
    MemberAuthor

    A better way of saying this is that there are 3 processing steps:

    1. context to list
    2. components to template reprs
    3. extract anything from template repr that the current model and backend wants at top-level. This might also modify the template reprs eg moving documents to first message
    4. format the new template reprs into a list of role/content pairs.

    The benefit of the rewriting happening in 3 is that it's more a defensive way of programming this (silently dropping a template arg would be a lot harder.

  3. jakelorocco commented on Apr 28, 2026

    @jakelorocco
    Contributor

    The open question is then how do we want to actually handle the documents that we extract. Intrinsics allow specifying a field that determines the outcome: docs_as_message with the transformations.

    The equivalent in Mellea would be to pass in a ModelOption that indicates how to handle docs, and we choose a strategy to default to.

  4. nrfulton commented on Apr 28, 2026

    @nrfulton
    MemberAuthor

    The open question is then how do we want to actually handle the documents that we extract.

    If the model supports a docs kwarg then we pass it in there; else, the formatter needs to specify how the cos get inlined into the template (and throw exception of the template for that component doesn't explain what to do with docs).

    For messages, we can support of the docs kwarg by appending? or prepending?

  5. linked a pull request that will close this issuefeat: handle message docs correctly #975on Apr 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

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