|
1 | | -def convert_mml_to_llm_format(mml): |
| 1 | +import inspect |
| 2 | +from typing import Dict, List |
| 3 | + |
| 4 | +ROLES_MAP = { |
| 5 | + "bot": "assistant", |
| 6 | + "human": "user", |
| 7 | +} |
| 8 | + |
| 9 | + |
| 10 | +def convert_mml_to_llm_format(mml: List[Dict]) -> List[Dict]: |
2 | 11 | """ |
3 | 12 | Converts the MML (Message Markup Language) format to the common LLM message format. |
| 13 | + Analogous to format_msgs_chain_to_llm_context in back/back/apps/language_model/consumers/__init__.py |
| 14 | +
|
4 | 15 |
|
5 | 16 | :param mml: List of messages in MML format |
6 | 17 | :return: List of messages in LLM format {'role': 'user', 'content': '...'} |
7 | 18 | """ |
8 | | - roles_map = { |
9 | | - "bot": "assistant", |
10 | | - "human": "user", |
| 19 | + aggregated_messages = [] |
| 20 | + current_role = None # "user" for human and "assistant" for bot |
| 21 | + aggregated_contents = [] # list of Content objects for the current group |
| 22 | + |
| 23 | + def process_stack(stack: Dict) -> List[Dict]: |
| 24 | + """ |
| 25 | + Process a single stack item into a list of LLM message format. |
| 26 | + """ |
| 27 | + contents = [] |
| 28 | + type = stack.get("type") |
| 29 | + |
| 30 | + if type == "message": |
| 31 | + contents.append( |
| 32 | + { |
| 33 | + "type": "text", |
| 34 | + "text": stack["payload"]["content"], |
| 35 | + } |
| 36 | + ) |
| 37 | + elif type == "tool_use": |
| 38 | + contents.append( |
| 39 | + { |
| 40 | + "type": "tool_use", |
| 41 | + "tool_use": stack["payload"], |
| 42 | + } |
| 43 | + ) |
| 44 | + elif type == "tool_result": |
| 45 | + contents.append( |
| 46 | + { |
| 47 | + "type": "tool_result", |
| 48 | + "tool_result": stack["payload"], |
| 49 | + } |
| 50 | + ) |
| 51 | + |
| 52 | + return contents |
| 53 | + |
| 54 | + def process_msg(msg: Dict) -> List[Dict]: |
| 55 | + """ |
| 56 | + Process each broker message into a list of LLM message format by iterating over its stacks. |
| 57 | + """ |
| 58 | + contents = [] |
| 59 | + for stack in msg.get("stack", []): |
| 60 | + contents.extend(process_stack(stack)) |
| 61 | + return contents |
| 62 | + |
| 63 | + def merge_contents(existing: List[Dict], new: List[Dict]) -> List[Dict]: |
| 64 | + """ |
| 65 | + Merge two lists of LLM message format. |
| 66 | + If the last element of the existing list and the first element of the new list are both text, |
| 67 | + then they are concatenated. |
| 68 | + """ |
| 69 | + if not existing: |
| 70 | + return new |
| 71 | + if not new: |
| 72 | + return existing |
| 73 | + |
| 74 | + merged = existing.copy() |
| 75 | + if merged and new and merged[-1]["type"] == "text" and new[0]["type"] == "text": |
| 76 | + merged[-1]["text"] = ( |
| 77 | + merged[-1]["text"].strip() + " " + new[0]["text"].strip() |
| 78 | + ) |
| 79 | + merged.extend(new[1:]) |
| 80 | + else: |
| 81 | + merged.extend(new) |
| 82 | + return merged |
| 83 | + |
| 84 | + for msg in mml: |
| 85 | + role = ROLES_MAP[msg["sender"]["type"]] |
| 86 | + msg_contents = process_msg(msg) |
| 87 | + if not msg_contents: |
| 88 | + continue |
| 89 | + |
| 90 | + if current_role is None: |
| 91 | + current_role = role |
| 92 | + aggregated_contents = msg_contents |
| 93 | + elif current_role == role: |
| 94 | + aggregated_contents = merge_contents(aggregated_contents, msg_contents) |
| 95 | + else: |
| 96 | + aggregated_messages.append( |
| 97 | + { |
| 98 | + "role": current_role, |
| 99 | + "content": aggregated_contents, |
| 100 | + } |
| 101 | + ) |
| 102 | + current_role = role |
| 103 | + aggregated_contents = msg_contents |
| 104 | + |
| 105 | + if aggregated_contents: |
| 106 | + aggregated_messages.append( |
| 107 | + { |
| 108 | + "role": current_role, |
| 109 | + "content": aggregated_contents, |
| 110 | + } |
| 111 | + ) |
| 112 | + |
| 113 | + return aggregated_messages |
| 114 | + |
| 115 | + |
| 116 | +def function_to_json(func) -> dict: |
| 117 | + """ |
| 118 | + Converts a Python function into a JSON-serializable dictionary |
| 119 | + that describes the function's signature, including its name, |
| 120 | + description, and parameters. |
| 121 | + Function from https://github.com/openai/swarm |
| 122 | +
|
| 123 | + Args: |
| 124 | + func: The function to be converted. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + A dictionary representing the function's signature in JSON format. |
| 128 | + """ |
| 129 | + type_map = { |
| 130 | + str: "string", |
| 131 | + int: "integer", |
| 132 | + float: "number", |
| 133 | + bool: "boolean", |
| 134 | + list: "array", |
| 135 | + dict: "object", |
| 136 | + type(None): "null", |
| 137 | + } |
| 138 | + |
| 139 | + try: |
| 140 | + signature = inspect.signature(func) |
| 141 | + except ValueError as e: |
| 142 | + raise ValueError( |
| 143 | + f"Failed to get signature for function {func.__name__}: {str(e)}" |
| 144 | + ) |
| 145 | + |
| 146 | + parameters = {} |
| 147 | + for param in signature.parameters.values(): |
| 148 | + try: |
| 149 | + param_type = type_map.get(param.annotation, "string") |
| 150 | + except KeyError as e: |
| 151 | + raise KeyError( |
| 152 | + f"Unknown type annotation {param.annotation} for parameter {param.name}: {str(e)}" |
| 153 | + ) |
| 154 | + parameters[param.name] = {"type": param_type} |
| 155 | + |
| 156 | + required = [ |
| 157 | + param.name |
| 158 | + for param in signature.parameters.values() |
| 159 | + if param.default == inspect._empty |
| 160 | + ] |
| 161 | + |
| 162 | + return { |
| 163 | + "type": "function", |
| 164 | + "function": { |
| 165 | + "name": func.__name__, |
| 166 | + "description": func.__doc__ or "", |
| 167 | + "parameters": { |
| 168 | + "type": "object", |
| 169 | + "properties": parameters, |
| 170 | + "required": required, |
| 171 | + }, |
| 172 | + }, |
11 | 173 | } |
12 | | - messages = [] |
13 | | - |
14 | | - for message in mml: |
15 | | - for stack in message.get("stack", []): |
16 | | - content = stack["payload"].get("content") |
17 | | - if not content: |
18 | | - continue |
19 | | - messages.append({ |
20 | | - "role": roles_map[message["sender"]["type"]], |
21 | | - "content": content, |
22 | | - }) |
23 | | - |
24 | | - return messages |
|
0 commit comments