File size: 4,940 Bytes
962f2ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import re
from typing import Dict, List, Any, Optional

def parse_conversation(raw: str) -> Dict[str, Any]:
    """
    Parse a single conversation payload.
    
    - Everything before the `<dialogue>` tag becomes the system prompt.
    - Inside <dialogue>…</dialogue>, lines starting with `User:` or `Assistant:` open a new turn.
    - Lines starting with `<alt>` are stored as alternatives on the *current* turn, under key "alt".
    - <code>…</code> blocks are embedded into the current turn as a fenced code block (```).

    Returns:
        {
          "system": str,
          "messages": [
            {"role": "user"|"assistant", "content": str, "alt": [str, ...]?},
            ...
          ]
        }
    """
    # 1) Split system vs dialogue
    start = raw.find("<dialogue>")
    if start == -1:
        raise ValueError("No <dialogue> tag found.")
    end = raw.find("</dialogue>", start)
    if end == -1:
        # If no closing tag, assume dialogue runs to the end
        end = len(raw)

    system_prompt = raw[:start].strip()
    dialogue = raw[start + len("<dialogue>"):end].strip("\n")

    # 2) Helpers for building messages
    messages: List[Dict[str, Any]] = []
    current_role: Optional[str] = None
    current_lines: List[str] = []
    current_alts: List[str] = []

    def flush():
        nonlocal current_role, current_lines, current_alts
        if current_role is not None:
            msg: Dict[str, Any] = {
                "role": current_role,
                "content": "\n".join(current_lines).strip()
            }
            if current_alts:
                msg["alt"] = current_alts[:]
            messages.append(msg)
        current_role = None
        current_lines = []
        current_alts = []

    # 3) Line-by-line parse of dialogue
    i = 0
    lines = dialogue.splitlines()
    while i < len(lines):
        line = lines[i]

        # New speaker?
        m_user = re.match(r'^\s*User:\s*(.*)$', line)
        m_assistant = re.match(r'^\s*Assistant:\s*(.*)$', line)

        if m_user or m_assistant:
            # close previous turn
            flush()
            current_role = "user" if m_user else "assistant"
            first_text = (m_user or m_assistant).group(1)
            current_lines.append(first_text)
            i += 1
            continue

        # Alternative for current turn?
        m_alt = re.match(r'^\s*<alt>\s*(.*)$', line)
        if m_alt:
            # If there's no current role yet, ignore dangling <alt>
            if current_role is not None:
                current_alts.append(m_alt.group(1))
            i += 1
            continue

        # Code block?
        if "<code>" in line:
            # Collect until </code>
            code_content_lines: List[str] = []
            # If there is inline content after <code>, capture only what's after the tag
            after_open = line.split("<code>", 1)[1]
            # If the close is on the same line
            if "</code>" in after_open:
                inside, after = after_open.split("</code>", 1)
                code_content_lines.append(inside)
                code_text = "\n".join(code_content_lines).strip("\n")
                current_lines.append("```python\n" + code_text + "\n```")
                # If trailing text after </code> on same line, keep it
                if after.strip():
                    current_lines.append(after.strip())
                i += 1
                continue
            else:
                # Multi-line code
                code_content_lines.append(after_open)
                i += 1
                found_close = False
                while i < len(lines):
                    if "</code>" in lines[i]:
                        before_close, after = lines[i].split("</code>", 1)
                        code_content_lines.append(before_close)
                        code_text = "\n".join(code_content_lines).strip("\n")
                        current_lines.append("```python\n" + code_text + "\n```")
                        if after.strip():
                            current_lines.append(after.strip())
                        found_close = True
                        i += 1
                        break
                    else:
                        code_content_lines.append(lines[i])
                        i += 1
                if not found_close:
                    # No closing tag found; still append what we have as code
                    code_text = "\n".join(code_content_lines).strip("\n")
                    current_lines.append("```python\n" + code_text + "\n```")
                continue

        # Regular content line: attach to current turn if any
        if current_role is not None:
            current_lines.append(line)
        # else ignore blank/dangling lines

        i += 1

    # flush last
    flush()

    return {
        "system": system_prompt,
        "messages": messages
    }