chat.py 11.5 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base64
import io
import json
import os
luopl's avatar
luopl committed
19
import re
chenych's avatar
chenych committed
20
import uuid
chenych's avatar
chenych committed
21
22
from collections.abc import AsyncGenerator
from typing import TYPE_CHECKING, Optional
chenych's avatar
chenych committed
23
24

from ..data import Role as DataRole
luopl's avatar
luopl committed
25
from ..extras import logging
chenych's avatar
chenych committed
26
from ..extras.constants import AUDIO_PLACEHOLDER, IMAGE_PLACEHOLDER, VIDEO_PLACEHOLDER
chenych's avatar
chenych committed
27
from ..extras.misc import is_env_enabled
chenych's avatar
chenych committed
28
from ..extras.packages import is_fastapi_available, is_pillow_available, is_requests_available
shihm's avatar
uodata  
shihm committed
29
from .common import check_lfi_path, check_ssrf_url, dictify, jsonify
chenych's avatar
chenych committed
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
from .protocol import (
    ChatCompletionMessage,
    ChatCompletionResponse,
    ChatCompletionResponseChoice,
    ChatCompletionResponseUsage,
    ChatCompletionStreamResponse,
    ChatCompletionStreamResponseChoice,
    Finish,
    Function,
    FunctionCall,
    Role,
    ScoreEvaluationResponse,
)


if is_fastapi_available():
    from fastapi import HTTPException, status


if is_pillow_available():
    from PIL import Image


if is_requests_available():
    import requests


if TYPE_CHECKING:
    from ..chat import ChatModel
chenych's avatar
chenych committed
59
    from ..data.mm_plugin import AudioInput, ImageInput, VideoInput
chenych's avatar
chenych committed
60
61
62
    from .protocol import ChatCompletionRequest, ScoreEvaluationRequest


luopl's avatar
luopl committed
63
logger = logging.get_logger(__name__)
chenych's avatar
chenych committed
64
65
66
67
68
69
70
71
72
73
74
ROLE_MAPPING = {
    Role.USER: DataRole.USER.value,
    Role.ASSISTANT: DataRole.ASSISTANT.value,
    Role.SYSTEM: DataRole.SYSTEM.value,
    Role.FUNCTION: DataRole.FUNCTION.value,
    Role.TOOL: DataRole.OBSERVATION.value,
}


def _process_request(
    request: "ChatCompletionRequest",
chenych's avatar
chenych committed
75
76
77
78
79
80
81
82
) -> tuple[
    list[dict[str, str]],
    Optional[str],
    Optional[str],
    Optional[list["ImageInput"]],
    Optional[list["VideoInput"]],
    Optional[list["AudioInput"]],
]:
chenych's avatar
chenych committed
83
84
    if is_env_enabled("API_VERBOSE", "1"):
        logger.info_rank0(f"==== request ====\n{json.dumps(dictify(request), indent=2, ensure_ascii=False)}")
chenych's avatar
chenych committed
85
86
87
88
89

    if len(request.messages) == 0:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid length")

    if request.messages[0].role == Role.SYSTEM:
chenych's avatar
chenych committed
90
91
        content = request.messages.pop(0).content
        system = content[0].text if isinstance(content, list) else content
chenych's avatar
chenych committed
92
93
94
95
96
97
98
    else:
        system = None

    if len(request.messages) % 2 == 0:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Only supports u/a/u/a/u...")

    input_messages = []
chenych's avatar
chenych committed
99
    images, videos, audios = [], [], []
chenych's avatar
chenych committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    for i, message in enumerate(request.messages):
        if i % 2 == 0 and message.role not in [Role.USER, Role.TOOL]:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid role")
        elif i % 2 == 1 and message.role not in [Role.ASSISTANT, Role.FUNCTION]:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid role")

        if message.role == Role.ASSISTANT and isinstance(message.tool_calls, list) and len(message.tool_calls):
            tool_calls = [
                {"name": tool_call.function.name, "arguments": tool_call.function.arguments}
                for tool_call in message.tool_calls
            ]
            content = json.dumps(tool_calls, ensure_ascii=False)
            input_messages.append({"role": ROLE_MAPPING[Role.FUNCTION], "content": content})
        elif isinstance(message.content, list):
chenych's avatar
chenych committed
114
            text_content = ""
chenych's avatar
chenych committed
115
116
            for input_item in message.content:
                if input_item.type == "text":
chenych's avatar
chenych committed
117
                    text_content += input_item.text
chenych's avatar
chenych committed
118
                elif input_item.type == "image_url":
chenych's avatar
chenych committed
119
                    text_content += IMAGE_PLACEHOLDER
chenych's avatar
chenych committed
120
                    image_url = input_item.image_url.url
luopl's avatar
luopl committed
121
122
                    if re.match(r"^data:image\/(png|jpg|jpeg|gif|bmp);base64,(.+)$", image_url):  # base64 image
                        image_stream = io.BytesIO(base64.b64decode(image_url.split(",", maxsplit=1)[1]))
chenych's avatar
chenych committed
123
                    elif os.path.isfile(image_url):  # local file
shihm's avatar
uodata  
shihm committed
124
                        check_lfi_path(image_url)
luopl's avatar
luopl committed
125
                        image_stream = open(image_url, "rb")
chenych's avatar
chenych committed
126
                    else:  # web uri
shihm's avatar
uodata  
shihm committed
127
                        check_ssrf_url(image_url)
luopl's avatar
luopl committed
128
                        image_stream = requests.get(image_url, stream=True).raw
chenych's avatar
chenych committed
129

luopl's avatar
luopl committed
130
                    images.append(Image.open(image_stream).convert("RGB"))
chenych's avatar
chenych committed
131
132
133
                elif input_item.type == "video_url":
                    text_content += VIDEO_PLACEHOLDER
                    video_url = input_item.video_url.url
chenych's avatar
chenych committed
134
135
136
                    if re.match(r"^data:video\/(mp4|mkv|avi|mov);base64,(.+)$", video_url):  # base64 video
                        video_stream = io.BytesIO(base64.b64decode(video_url.split(",", maxsplit=1)[1]))
                    elif os.path.isfile(video_url):  # local file
shihm's avatar
uodata  
shihm committed
137
                        check_lfi_path(video_url)
chenych's avatar
chenych committed
138
                        video_stream = video_url
chenych's avatar
chenych committed
139
                    else:  # web uri
shihm's avatar
uodata  
shihm committed
140
                        check_ssrf_url(video_url)
chenych's avatar
chenych committed
141
142
143
144
145
146
                        video_stream = requests.get(video_url, stream=True).raw

                    videos.append(video_stream)
                elif input_item.type == "audio_url":
                    text_content += AUDIO_PLACEHOLDER
                    audio_url = input_item.audio_url.url
chenych's avatar
chenych committed
147
148
149
                    if re.match(r"^data:audio\/(mpeg|mp3|wav|ogg);base64,(.+)$", audio_url):  # base64 audio
                        audio_stream = io.BytesIO(base64.b64decode(audio_url.split(",", maxsplit=1)[1]))
                    elif os.path.isfile(audio_url):  # local file
shihm's avatar
uodata  
shihm committed
150
                        check_lfi_path(audio_url)
chenych's avatar
chenych committed
151
                        audio_stream = audio_url
chenych's avatar
chenych committed
152
                    else:  # web uri
shihm's avatar
uodata  
shihm committed
153
                        check_ssrf_url(audio_url)
chenych's avatar
chenych committed
154
155
156
157
158
159
160
                        audio_stream = requests.get(audio_url, stream=True).raw

                    audios.append(audio_stream)
                else:
                    raise HTTPException(
                        status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid input type {input_item.type}."
                    )
chenych's avatar
chenych committed
161
162

            input_messages.append({"role": ROLE_MAPPING[message.role], "content": text_content})
chenych's avatar
chenych committed
163
164
165
166
167
168
169
170
171
172
173
174
        else:
            input_messages.append({"role": ROLE_MAPPING[message.role], "content": message.content})

    tool_list = request.tools
    if isinstance(tool_list, list) and len(tool_list):
        try:
            tools = json.dumps([dictify(tool.function) for tool in tool_list], ensure_ascii=False)
        except json.JSONDecodeError:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid tools")
    else:
        tools = None

chenych's avatar
chenych committed
175
    return input_messages, system, tools, images or None, videos or None, audios or None
chenych's avatar
chenych committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192


def _create_stream_chat_completion_chunk(
    completion_id: str,
    model: str,
    delta: "ChatCompletionMessage",
    index: Optional[int] = 0,
    finish_reason: Optional["Finish"] = None,
) -> str:
    choice_data = ChatCompletionStreamResponseChoice(index=index, delta=delta, finish_reason=finish_reason)
    chunk = ChatCompletionStreamResponse(id=completion_id, model=model, choices=[choice_data])
    return jsonify(chunk)


async def create_chat_completion_response(
    request: "ChatCompletionRequest", chat_model: "ChatModel"
) -> "ChatCompletionResponse":
luopl's avatar
luopl committed
193
    completion_id = f"chatcmpl-{uuid.uuid4().hex}"
chenych's avatar
chenych committed
194
    input_messages, system, tools, images, videos, audios = _process_request(request)
chenych's avatar
chenych committed
195
196
197
198
    responses = await chat_model.achat(
        input_messages,
        system,
        tools,
luopl's avatar
luopl committed
199
        images,
chenych's avatar
chenych committed
200
201
        videos,
        audios,
chenych's avatar
chenych committed
202
203
204
205
206
        do_sample=request.do_sample,
        temperature=request.temperature,
        top_p=request.top_p,
        max_new_tokens=request.max_tokens,
        num_return_sequences=request.n,
chenych's avatar
chenych committed
207
        repetition_penalty=request.presence_penalty,
chenych's avatar
chenych committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
        stop=request.stop,
    )

    prompt_length, response_length = 0, 0
    choices = []
    for i, response in enumerate(responses):
        if tools:
            result = chat_model.engine.template.extract_tool(response.response_text)
        else:
            result = response.response_text

        if isinstance(result, list):
            tool_calls = []
            for tool in result:
luopl's avatar
luopl committed
222
                function = Function(name=tool.name, arguments=tool.arguments)
luopl's avatar
luopl committed
223
                tool_calls.append(FunctionCall(id=f"call_{uuid.uuid4().hex}", function=function))
chenych's avatar
chenych committed
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

            response_message = ChatCompletionMessage(role=Role.ASSISTANT, tool_calls=tool_calls)
            finish_reason = Finish.TOOL
        else:
            response_message = ChatCompletionMessage(role=Role.ASSISTANT, content=result)
            finish_reason = Finish.STOP if response.finish_reason == "stop" else Finish.LENGTH

        choices.append(ChatCompletionResponseChoice(index=i, message=response_message, finish_reason=finish_reason))
        prompt_length = response.prompt_length
        response_length += response.response_length

    usage = ChatCompletionResponseUsage(
        prompt_tokens=prompt_length,
        completion_tokens=response_length,
        total_tokens=prompt_length + response_length,
    )

    return ChatCompletionResponse(id=completion_id, model=request.model, choices=choices, usage=usage)


async def create_stream_chat_completion_response(
    request: "ChatCompletionRequest", chat_model: "ChatModel"
) -> AsyncGenerator[str, None]:
luopl's avatar
luopl committed
247
    completion_id = f"chatcmpl-{uuid.uuid4().hex}"
chenych's avatar
chenych committed
248
    input_messages, system, tools, images, videos, audios = _process_request(request)
chenych's avatar
chenych committed
249
250
251
252
253
254
255
256
257
258
259
260
261
    if tools:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot stream function calls.")

    if request.n > 1:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot stream multiple responses.")

    yield _create_stream_chat_completion_chunk(
        completion_id=completion_id, model=request.model, delta=ChatCompletionMessage(role=Role.ASSISTANT, content="")
    )
    async for new_token in chat_model.astream_chat(
        input_messages,
        system,
        tools,
luopl's avatar
luopl committed
262
        images,
chenych's avatar
chenych committed
263
264
        videos,
        audios,
chenych's avatar
chenych committed
265
266
267
268
        do_sample=request.do_sample,
        temperature=request.temperature,
        top_p=request.top_p,
        max_new_tokens=request.max_tokens,
chenych's avatar
chenych committed
269
        repetition_penalty=request.presence_penalty,
chenych's avatar
chenych committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        stop=request.stop,
    ):
        if len(new_token) != 0:
            yield _create_stream_chat_completion_chunk(
                completion_id=completion_id, model=request.model, delta=ChatCompletionMessage(content=new_token)
            )

    yield _create_stream_chat_completion_chunk(
        completion_id=completion_id, model=request.model, delta=ChatCompletionMessage(), finish_reason=Finish.STOP
    )
    yield "[DONE]"


async def create_score_evaluation_response(
    request: "ScoreEvaluationRequest", chat_model: "ChatModel"
) -> "ScoreEvaluationResponse":
luopl's avatar
luopl committed
286
    score_id = f"scoreval-{uuid.uuid4().hex}"
chenych's avatar
chenych committed
287
288
289
290
    if len(request.messages) == 0:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid request")

    scores = await chat_model.aget_scores(request.messages, max_length=request.max_length)
luopl's avatar
luopl committed
291
    return ScoreEvaluationResponse(id=score_id, model=request.model, scores=scores)