File size: 11,493 Bytes
04f192c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# SPDX-FileCopyrightText: Copyright contributors to the CopilotJ project.
#
# SPDX-License-Identifier: Apache-2.0

import asyncio
from collections.abc import AsyncGenerator, Sequence
from typing import Any, override

from copilotj.core.message import ImageMessage, TextMessage
from copilotj.core.model_client import ModelClient, ModelResponse, ModelResponseChunk, ModelSyntaxError, ToolCall
from copilotj.core.tool import FunctionTool, Tool
from copilotj.util.react_parser import ReActChatCompletionClient, _build_last_line_prefix_regex


def lookup(query: str) -> str:
    return query


class _StubModelClient(ModelClient):
    def __init__(
        self,
        *,
        response: ModelResponse | None = None,
        stream_chunks: list[ModelResponseChunk | ToolCall] | None = None,
    ) -> None:
        self._response = response or ModelResponse(
            reasoning_content=None,
            content=None,
            tool_calls=None,
            finish_reason="unknown",
        )
        self._stream_chunks = stream_chunks or []

    @override
    def get_model(self) -> str:
        return "stub"

    @override
    def get_api_key(self) -> str | None:
        return None

    @override
    async def create(
        self,
        messages: Sequence[TextMessage | ImageMessage],
        *,
        tools: list[Tool] | None = None,
        extra_args: dict[str, Any] | None = None,
    ) -> ModelResponse:
        return self._response

    @override
    async def create_stream(
        self,
        messages: Sequence[TextMessage | ImageMessage],
        *,
        tools: list[Tool] | None = None,
        extra_args: dict[str, Any] | None = None,
    ) -> AsyncGenerator[ModelResponseChunk | ToolCall, None]:
        for chunk in self._stream_chunks:
            yield chunk


def test_create_parses_standard_react_response():
    tool = FunctionTool(lookup, "Look up a query.", name="lookup")
    client = ReActChatCompletionClient(
        _StubModelClient(
            response=ModelResponse(
                reasoning_content=None,
                content="""\
Thought: need more information
Action:
{"name": "lookup", "args": {"query": "cells"}}
Final Answer: found it
""",
                tool_calls=None,
                finish_reason="stop",
            )
        )
    )

    response = asyncio.run(client.create([TextMessage(role="user", text="help")], tools=[tool]))

    assert response.reasoning_content == "need more information"
    assert response.content == "found it"
    assert response.tool_calls is not None
    assert len(response.tool_calls) == 1
    assert response.tool_calls[0].tool.name == "lookup"
    assert response.tool_calls[0].args.query == "cells"
    assert response.finish_reason == "stop"


def test_create_parses_bolded_react_keywords():
    tool = FunctionTool(lookup, "Look up a query.", name="lookup")
    client = ReActChatCompletionClient(
        _StubModelClient(
            response=ModelResponse(
                reasoning_content=None,
                content="""\
**Thought**: need more information
**Action**:
{"name": "lookup", "args": {"query": "cells"}}
**Final Answer**: found it
""",
                tool_calls=None,
                finish_reason="stop",
            )
        )
    )

    response = asyncio.run(client.create([TextMessage(role="user", text="help")], tools=[tool]))

    assert response.reasoning_content == "need more information"
    assert response.content == "found it"
    assert response.tool_calls is not None
    assert len(response.tool_calls) == 1
    assert response.tool_calls[0].tool.name == "lookup"
    assert response.tool_calls[0].args.query == "cells"
    assert response.finish_reason == "stop"


def test_create_parses_bolded_keywords_with_colon_inside_bold():
    tool = FunctionTool(lookup, "Look up a query.", name="lookup")
    client = ReActChatCompletionClient(
        _StubModelClient(
            response=ModelResponse(
                reasoning_content=None,
                content="""\
**Thought:** need more information
**Action:**
{"name": "lookup", "args": {"query": "cells"}}
**Final Answer:** found it
""",
                tool_calls=None,
                finish_reason="stop",
            )
        )
    )

    response = asyncio.run(client.create([TextMessage(role="user", text="help")], tools=[tool]))

    assert response.reasoning_content == "need more information"
    assert response.content == "found it"
    assert response.tool_calls is not None
    assert len(response.tool_calls) == 1
    assert response.tool_calls[0].tool.name == "lookup"
    assert response.tool_calls[0].args.query == "cells"
    assert response.finish_reason == "stop"


def test_create_returns_raw_content_without_react_keywords():
    client = ReActChatCompletionClient(
        _StubModelClient(
            response=ModelResponse(
                reasoning_content=None,
                content="Just answer directly.",
                tool_calls=None,
                finish_reason="stop",
            )
        )
    )

    response = asyncio.run(client.create([TextMessage(role="user", text="help")], tools=[]))

    assert response.reasoning_content is None
    assert response.content == "Just answer directly."
    assert response.tool_calls == []
    assert response.finish_reason == "stop"


def test_create_parses_final_answer_without_thought_or_action():
    client = ReActChatCompletionClient(
        _StubModelClient(
            response=ModelResponse(
                reasoning_content=None,
                content="Final Answer: Just answer directly.",
                tool_calls=None,
                finish_reason="stop",
            )
        )
    )

    response = asyncio.run(client.create([TextMessage(role="user", text="help")], tools=[]))

    assert response.reasoning_content is None
    assert response.content == "Just answer directly."
    assert response.tool_calls is None
    assert response.finish_reason == "stop"


def test_create_raises_for_unknown_tool():
    client = ReActChatCompletionClient(
        _StubModelClient(
            response=ModelResponse(
                reasoning_content=None,
                content='Action: {"name": "missing_tool", "args": {}}',
                tool_calls=None,
                finish_reason="stop",
            )
        )
    )

    try:
        asyncio.run(client.create([TextMessage(role="user", text="help")], tools=[]))
    except ModelSyntaxError as exc:
        assert "Tool 'missing_tool' not found" in exc.message
    else:
        raise AssertionError("Expected ModelSyntaxError for unknown tool")


def test_create_stream_parses_standard_react_response():
    tool = FunctionTool(lookup, "Look up a query.", name="lookup")
    client = ReActChatCompletionClient(
        _StubModelClient(
            stream_chunks=[
                ModelResponseChunk(reasoning_content=None, content="Thought: inspect\n", finish_reason=None),
                ModelResponseChunk(
                    reasoning_content=None,
                    content='Action: {"name": "lookup", "args": {"query": "cells"}}\nFinal Answer: done',
                    finish_reason=None,
                ),
                ModelResponseChunk(reasoning_content=None, content=None, finish_reason="stop"),
            ]
        )
    )

    items = [
        item
        for item in asyncio.run(_collect_stream(client, [tool]))
        if not (isinstance(item, ModelResponseChunk) and item.reasoning_content == "")
    ]

    assert len(items) == 4
    assert isinstance(items[0], ModelResponseChunk)
    assert items[0].reasoning_content == "inspect\n"
    assert isinstance(items[1], ToolCall)
    assert items[1].tool.name == "lookup"
    assert items[1].args.query == "cells"
    assert isinstance(items[2], ModelResponseChunk)
    assert items[2].content == "done"
    assert isinstance(items[3], ModelResponseChunk)
    assert items[3].finish_reason == "stop"


def test_create_stream_parses_bolded_react_keywords():
    tool = FunctionTool(lookup, "Look up a query.", name="lookup")
    client = ReActChatCompletionClient(
        _StubModelClient(
            stream_chunks=[
                ModelResponseChunk(reasoning_content=None, content="**Thought**: inspect\n", finish_reason=None),
                ModelResponseChunk(
                    reasoning_content=None,
                    content='**Action**: {"name": "lookup", "args": {"query": "cells"}}\n**Final Answer**: done',
                    finish_reason=None,
                ),
                ModelResponseChunk(reasoning_content=None, content=None, finish_reason="stop"),
            ]
        )
    )

    items = [
        item
        for item in asyncio.run(_collect_stream(client, [tool]))
        if not (isinstance(item, ModelResponseChunk) and item.reasoning_content == "")
    ]

    assert len(items) == 4
    assert isinstance(items[0], ModelResponseChunk)
    assert items[0].reasoning_content == "inspect\n"
    assert isinstance(items[1], ToolCall)
    assert items[1].tool.name == "lookup"
    assert items[1].args.query == "cells"
    assert isinstance(items[2], ModelResponseChunk)
    assert items[2].content == "done"
    assert isinstance(items[3], ModelResponseChunk)
    assert items[3].finish_reason == "stop"


def test_create_stream_parses_bolded_keywords_with_colon_inside_bold():
    tool = FunctionTool(lookup, "Look up a query.", name="lookup")
    client = ReActChatCompletionClient(
        _StubModelClient(
            stream_chunks=[
                ModelResponseChunk(reasoning_content=None, content="**Thought:** inspect\n", finish_reason=None),
                ModelResponseChunk(
                    reasoning_content=None,
                    content='**Action:** {"name": "lookup", "args": {"query": "cells"}}\n**Final Answer:** done',
                    finish_reason=None,
                ),
                ModelResponseChunk(reasoning_content=None, content=None, finish_reason="stop"),
            ]
        )
    )

    items = [
        item
        for item in asyncio.run(_collect_stream(client, [tool]))
        if not (isinstance(item, ModelResponseChunk) and item.reasoning_content == "")
    ]

    assert len(items) == 4
    assert isinstance(items[0], ModelResponseChunk)
    assert items[0].reasoning_content == "inspect\n"
    assert isinstance(items[1], ToolCall)
    assert items[1].tool.name == "lookup"
    assert items[1].args.query == "cells"
    assert isinstance(items[2], ModelResponseChunk)
    assert items[2].content == "done"
    assert isinstance(items[3], ModelResponseChunk)
    assert items[3].finish_reason == "stop"


def test_build_last_line_prefix_regex_matches_action_and_final_prefixes():
    pattern = _build_last_line_prefix_regex("Action", "Final Answer")

    assert pattern.search("A")
    assert pattern.search("Actio")
    assert pattern.search("**Act")
    assert pattern.search("**Action**")
    assert pattern.search("**Action:")
    assert pattern.search("**Action:**")
    assert pattern.search("Final")
    assert pattern.search("**Final Answe")
    assert pattern.search("Final Answe")
    assert not pattern.search("Observation")


async def _collect_stream(client: ReActChatCompletionClient, tools: list[Tool]) -> list[ModelResponseChunk | ToolCall]:
    items: list[ModelResponseChunk | ToolCall] = []
    async for item in client.create_stream([TextMessage(role="user", text="help")], tools=tools):
        items.append(item)
    return items