File size: 9,889 Bytes
1689f23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import json
import time
import uuid
from typing import Any, AsyncIterator

from config import DEFAULT_MODEL, STOP_REASON_MAP, STREAM_RENDER_CHUNK_SIZE
from response_cache import CompletionArtifact
from tools import parse_function_calls_text, split_text_and_tools
from filters import P5jsLeadingFilter, ToolAwareTextBuffer, strip_p5js_noise
from upstream import fetch_completion_artifact


def extract_artifact_parts(artifact: CompletionArtifact) -> tuple[str, list[dict]]:
    clean_text, tool_uses = split_text_and_tools(artifact.raw_text)
    return strip_p5js_noise(clean_text), tool_uses


def render_anthropic_json_from_artifact(artifact: CompletionArtifact, has_tools: bool) -> dict:
    msg_id = f"msg_{uuid.uuid4().hex[:24]}"
    clean_text, tool_uses = extract_artifact_parts(artifact)

    content: list[dict] = []
    if clean_text:
        content.append({"type": "text", "text": clean_text})
    if has_tools:
        for tu in tool_uses:
            content.append({"type": "tool_use", "id": tu["id"], "name": tu["name"], "input": tu["input"]})

    stop_reason = "tool_use" if has_tools and tool_uses else artifact.stop_reason

    return {
        "id": msg_id,
        "type": "message",
        "role": "assistant",
        "model": artifact.model_id,
        "content": content or [{"type": "text", "text": ""}],
        "stop_reason": stop_reason,
        "stop_sequence": None,
        "usage": {
            "input_tokens": artifact.usage_input_tokens,
            "output_tokens": artifact.usage_output_tokens,
        },
    }


def render_openai_json_from_artifact(artifact: CompletionArtifact, has_tools: bool) -> dict:
    clean_text, tool_uses = extract_artifact_parts(artifact)
    finish_reason = "tool_calls" if has_tools and tool_uses else STOP_REASON_MAP.get(artifact.stop_reason, "stop")

    message: dict[str, Any] = {
        "role": "assistant",
        "content": clean_text or (None if has_tools and tool_uses else ""),
    }
    if has_tools and tool_uses:
        message["tool_calls"] = [
            {
                "id": f"call_{tu['id'].removeprefix('toolu_')}",
                "type": "function",
                "function": {
                    "name": tu["name"],
                    "arguments": json.dumps(tu["input"], ensure_ascii=False),
                },
            }
            for tu in tool_uses
        ]

    return {
        "id": f"chatcmpl-{uuid.uuid4().hex[:24]}",
        "object": "chat.completion",
        "created": int(time.time()),
        "model": artifact.model_id,
        "choices": [
            {
                "index": 0,
                "message": message,
                "finish_reason": finish_reason,
            }
        ],
        "usage": {
            "prompt_tokens": artifact.usage_input_tokens,
            "completion_tokens": artifact.usage_output_tokens,
            "total_tokens": artifact.usage_input_tokens + artifact.usage_output_tokens,
        },
    }


def _iter_text_chunks(text: str, chunk_size: int = STREAM_RENDER_CHUNK_SIZE):
    if not text:
        return
    for index in range(0, len(text), chunk_size):
        yield text[index:index + chunk_size]


def iter_stream_segments(raw_text: str, has_tools: bool):
    p5_filter = P5jsLeadingFilter()
    tool_buffer = ToolAwareTextBuffer()

    for raw_chunk in _iter_text_chunks(raw_text):
        filtered = p5_filter.feed(raw_chunk)
        if not filtered:
            continue
        if has_tools:
            yield from tool_buffer.feed(filtered)
        else:
            yield ("text", filtered)

    tail = p5_filter.flush()
    if tail:
        if has_tools:
            yield from tool_buffer.feed(tail)
        else:
            yield ("text", tail)

    if has_tools:
        yield from tool_buffer.flush()


async def anthropic_stream_from_artifact(artifact: CompletionArtifact, has_tools: bool) -> AsyncIterator[bytes]:
    msg_id = f"msg_{uuid.uuid4().hex[:24]}"
    usage = {
        "input_tokens": artifact.usage_input_tokens,
        "output_tokens": artifact.usage_output_tokens,
    }
    next_index = 0
    text_index: int | None = None
    text_opened = False
    saw_tool_use = False

    def sse(event: str, obj: dict) -> bytes:
        return f"event: {event}\ndata: {json.dumps(obj, ensure_ascii=False)}\n\n".encode()

    yield sse("message_start", {
        "type": "message_start",
        "message": {
            "id": msg_id,
            "type": "message",
            "role": "assistant",
            "model": artifact.model_id,
            "content": [],
            "stop_reason": None,
            "stop_sequence": None,
            "usage": usage,
        },
    })

    def close_text_if_open() -> bytes | None:
        nonlocal text_opened
        if text_opened and text_index is not None:
            text_opened = False
            return sse("content_block_stop", {"type": "content_block_stop", "index": text_index})
        return None

    for kind, payload_text in iter_stream_segments(artifact.raw_text, has_tools):
        if kind == "text":
            if not payload_text:
                continue
            if not text_opened:
                text_index = next_index
                next_index += 1
                yield sse("content_block_start", {
                    "type": "content_block_start",
                    "index": text_index,
                    "content_block": {"type": "text", "text": ""},
                })
                text_opened = True
            for chunk in _iter_text_chunks(payload_text):
                yield sse("content_block_delta", {
                    "type": "content_block_delta",
                    "index": text_index,
                    "delta": {"type": "text_delta", "text": chunk},
                })
        elif kind == "tool_block":
            tool_uses = parse_function_calls_text(payload_text)
            if not tool_uses:
                continue
            closed = close_text_if_open()
            if closed:
                yield closed
            for tu in tool_uses:
                saw_tool_use = True
                index = next_index
                next_index += 1
                yield sse("content_block_start", {
                    "type": "content_block_start",
                    "index": index,
                    "content_block": {"type": "tool_use", "id": tu["id"], "name": tu["name"], "input": {}},
                })
                yield sse("content_block_delta", {
                    "type": "content_block_delta",
                    "index": index,
                    "delta": {"type": "input_json_delta", "partial_json": json.dumps(tu["input"], ensure_ascii=False)},
                })
                yield sse("content_block_stop", {"type": "content_block_stop", "index": index})

    closed = close_text_if_open()
    if closed:
        yield closed

    stop_reason = "tool_use" if saw_tool_use else artifact.stop_reason
    yield sse("message_delta", {
        "type": "message_delta",
        "delta": {"stop_reason": stop_reason, "stop_sequence": None},
        "usage": usage,
    })
    yield sse("message_stop", {"type": "message_stop"})
    yield b"data: [DONE]\n\n"


async def openai_stream_from_artifact(artifact: CompletionArtifact, has_tools: bool) -> AsyncIterator[bytes]:
    chat_id = f"chatcmpl-{uuid.uuid4().hex[:24]}"
    created = int(time.time())
    first_chunk_sent = False
    saw_tool_use = False
    next_tool_index = 0

    def chunk(delta: dict, finish: str | None = None) -> bytes:
        obj = {
            "id": chat_id,
            "object": "chat.completion.chunk",
            "created": created,
            "model": artifact.model_id,
            "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
        }
        return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode()

    for kind, payload_text in iter_stream_segments(artifact.raw_text, has_tools):
        if kind == "text":
            if not payload_text:
                continue
            for text_chunk in _iter_text_chunks(payload_text):
                if not first_chunk_sent:
                    yield chunk({"role": "assistant", "content": ""})
                    first_chunk_sent = True
                yield chunk({"content": text_chunk})
        elif kind == "tool_block":
            tool_uses = parse_function_calls_text(payload_text)
            if not tool_uses:
                continue
            if not first_chunk_sent:
                yield chunk({"role": "assistant", "content": None})
                first_chunk_sent = True
            for tu in tool_uses:
                saw_tool_use = True
                index = next_tool_index
                next_tool_index += 1
                yield chunk({"tool_calls": [{
                    "index": index,
                    "id": f"call_{tu['id'].removeprefix('toolu_')}",
                    "type": "function",
                    "function": {"name": tu["name"], "arguments": ""},
                }]})
                yield chunk({"tool_calls": [{
                    "index": index,
                    "function": {"arguments": json.dumps(tu["input"], ensure_ascii=False)},
                }]})

    finish_reason = "tool_calls" if saw_tool_use else STOP_REASON_MAP.get(artifact.stop_reason, "stop")
    if not first_chunk_sent:
        yield chunk({"role": "assistant", "content": ""})
    yield chunk({}, finish=finish_reason)
    yield b"data: [DONE]\n\n"


async def anthropic_aggregate(payload: dict, has_tools: bool) -> dict:
    artifact = await fetch_completion_artifact(payload)
    return render_anthropic_json_from_artifact(artifact, has_tools)


async def openai_aggregate(payload: dict, requested_model: str, has_tools: bool) -> dict:
    artifact = await fetch_completion_artifact(payload)
    return render_openai_json_from_artifact(artifact, has_tools)