Converts a list of examples to a string that can be used in a system instruction.
(
examples: list[Example], model: Optional[str]
)
| 47 | |
| 48 | |
| 49 | def convert_examples_to_text( |
| 50 | examples: list[Example], model: Optional[str] |
| 51 | ) -> str: |
| 52 | """Converts a list of examples to a string that can be used in a system instruction.""" |
| 53 | examples_str = "" |
| 54 | for example_num, example in enumerate(examples): |
| 55 | output = f"{_EXAMPLE_START.format(example_num + 1)}{_USER_PREFIX}" |
| 56 | if example.input and example.input.parts: |
| 57 | output += ( |
| 58 | "\n".join(part.text for part in example.input.parts if part.text) |
| 59 | + "\n" |
| 60 | ) |
| 61 | |
| 62 | gemini2 = model is None or "gemini-2" in model |
| 63 | previous_role = None |
| 64 | for content in example.output: |
| 65 | role = _MODEL_PREFIX if content.role == "model" else _USER_PREFIX |
| 66 | if role != previous_role: |
| 67 | output += role |
| 68 | previous_role = role |
| 69 | for part in content.parts: |
| 70 | if part.function_call: |
| 71 | args = [] |
| 72 | # Convert function call part to python-like function call |
| 73 | for k, v in part.function_call.args.items(): |
| 74 | if isinstance(v, str): |
| 75 | args.append(f"{k}='{v}'") |
| 76 | else: |
| 77 | args.append(f"{k}={v}") |
| 78 | prefix = _FUNCTION_PREFIX if gemini2 else _FUNCTION_CALL_PREFIX |
| 79 | output += ( |
| 80 | f"{prefix}{part.function_call.name}({', '.join(args)}){_FUNCTION_CALL_SUFFIX}" |
| 81 | ) |
| 82 | # Convert function response part to json string |
| 83 | elif part.function_response: |
| 84 | prefix = _FUNCTION_PREFIX if gemini2 else _FUNCTION_RESPONSE_PREFIX |
| 85 | output += f"{prefix}{part.function_response.__dict__}{_FUNCTION_RESPONSE_SUFFIX}" |
| 86 | elif part.text: |
| 87 | output += f"{part.text}\n" |
| 88 | |
| 89 | output += _EXAMPLE_END |
| 90 | examples_str += output |
| 91 | |
| 92 | return f"{_EXAMPLES_INTRO}{examples_str}{_EXAMPLES_END}" |
| 93 | |
| 94 | |
| 95 | def _get_latest_message_from_user(session: "Session") -> str: |
no test coverage detected