|
| 1 | +from aidial_sdk.chat_completion import ChatCompletion, Request, Response |
| 2 | +from tests.utils.chunks import ( |
| 3 | + check_sse_stream, |
| 4 | + create_single_choice_chunk, |
| 5 | + create_tool_call_chunk, |
| 6 | +) |
| 7 | +from tests.utils.client import create_app_client |
| 8 | + |
| 9 | + |
| 10 | +class ToolCaller(ChatCompletion): |
| 11 | + async def chat_completion( |
| 12 | + self, request: Request, response: Response |
| 13 | + ) -> None: |
| 14 | + response.set_response_id("test_id") |
| 15 | + response.set_created(0) |
| 16 | + |
| 17 | + with response.create_single_choice() as choice: |
| 18 | + choice.append_content("Test content") |
| 19 | + |
| 20 | + tool_call1 = choice.create_function_tool_call( |
| 21 | + "tool_call_id1", "tool_name" |
| 22 | + ) |
| 23 | + tool_call1.append_arguments('{"key') |
| 24 | + tool_call1.append_arguments('":"') |
| 25 | + tool_call1.append_arguments('val"}') |
| 26 | + |
| 27 | + choice.create_function_tool_call( |
| 28 | + "tool_call_id2", "tool_name", '{"foo":"bar"}' |
| 29 | + ) |
| 30 | + |
| 31 | + |
| 32 | +def test_tool_call_non_streaming(): |
| 33 | + response = create_app_client(ToolCaller()).post( |
| 34 | + "chat/completions", json={"messages": [], "stream": False} |
| 35 | + ) |
| 36 | + |
| 37 | + body = response.json() |
| 38 | + assert body["choices"][0]["message"]["tool_calls"] == [ |
| 39 | + { |
| 40 | + "id": "tool_call_id1", |
| 41 | + "type": "function", |
| 42 | + "function": { |
| 43 | + "name": "tool_name", |
| 44 | + "arguments": '{"key":"val"}', |
| 45 | + }, |
| 46 | + }, |
| 47 | + { |
| 48 | + "id": "tool_call_id2", |
| 49 | + "type": "function", |
| 50 | + "function": { |
| 51 | + "name": "tool_name", |
| 52 | + "arguments": '{"foo":"bar"}', |
| 53 | + }, |
| 54 | + }, |
| 55 | + ] |
| 56 | + |
| 57 | + |
| 58 | +def test_tool_call_streaming(): |
| 59 | + response = create_app_client(ToolCaller()).post( |
| 60 | + "chat/completions", json={"messages": [], "stream": True} |
| 61 | + ) |
| 62 | + |
| 63 | + check_sse_stream( |
| 64 | + response.iter_lines(), |
| 65 | + [ |
| 66 | + create_single_choice_chunk({"role": "assistant"}), |
| 67 | + create_single_choice_chunk({"content": "Test content"}), |
| 68 | + create_tool_call_chunk( |
| 69 | + 0, type="function", id="tool_call_id1", name="tool_name" |
| 70 | + ), |
| 71 | + create_tool_call_chunk(0, arguments='{"key'), |
| 72 | + create_tool_call_chunk(0, arguments='":"'), |
| 73 | + create_tool_call_chunk(0, arguments='val"}'), |
| 74 | + create_tool_call_chunk( |
| 75 | + 1, |
| 76 | + type="function", |
| 77 | + id="tool_call_id2", |
| 78 | + name="tool_name", |
| 79 | + arguments='{"foo":"bar"}', |
| 80 | + ), |
| 81 | + create_single_choice_chunk({}, "tool_calls"), |
| 82 | + ], |
| 83 | + ) |
0 commit comments