def _join_contents()

in google/generativeai/types/generation_types.py [0:0]


def _join_contents(contents: Iterable[protos.Content]):
    contents = tuple(contents)
    roles = [c.role for c in contents if c.role]
    if roles:
        role = roles[0]
    else:
        role = ""

    parts = []
    for content in contents:
        parts.extend(content.parts)

    merged_parts = []
    last = parts[0]
    for part in parts[1:]:
        if "text" in last and "text" in part:
            last = protos.Part(text=last.text + part.text)
            continue

        # Can we merge the new thing into last?
        # If not, put last in list of parts, and new thing becomes last
        if "executable_code" in last and "executable_code" in part:
            last = protos.Part(
                executable_code=_join_executable_code(last.executable_code, part.executable_code)
            )
            continue

        if "code_execution_result" in last and "code_execution_result" in part:
            last = protos.Part(
                code_execution_result=_join_code_execution_result(
                    last.code_execution_result, part.code_execution_result
                )
            )
            continue

        merged_parts.append(last)
        last = part

    merged_parts.append(last)

    return protos.Content(
        role=role,
        parts=merged_parts,
    )