完整代码如下:
-- coding: utf-8 --
import torch
import copy
import json
from typing import Dict, List, Literal, Optional, Union, Tuple
from threading import Thread
from pprint import pprint
from pydantic import BaseModel
from sse_starlette.sse import EventSourceResponse
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, TextIteratorStreamer
from fastapi import APIRouter, Depends, HTTPException
from common.request_vo import ChatCompletionRequest, ChatCompletionResponse, ChatMessage,
ChatCompletionResponseStreamChoice, DeltaMessage, ChatCompletionResponseChoice
from common.setting import AppSettings
from dependencies import check_token_header
router = APIRouter(
prefix="/standard",
tags=["Standard"],
dependencies=[Depends(check_token_header)],
responses={404: {"description": "Not found"}},
)
_TEXT_COMPLETION_CMD = object()
TOOL_DESC = (
'{name_for_model}: Call this tool to interact with the {name_for_human} API.'
' What is the {name_for_human} API useful for? {description_for_model} Parameters: {parameters}'
)
REACT_INSTRUCTION = """Answer the following questions as best you can. You have access to the following APIs:
{tools_text}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tools_name_text}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!"""
def _gc():
import gc
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
def add_extra_stop_words(stop_words):
if stop_words:
_stop_words = []
_stop_words.extend(stop_words)
for x in stop_words:
s = x.lstrip('\n')
if s and (s not in _stop_words):
_stop_words.append(s)
return _stop_words
return stop_words
def _dump_json(data: BaseModel, *args, **kwargs) -> str:
try:
return data.model_dump_json(*args, **kwargs)
except AttributeError: # pydantic<2.0.0
return data.json(*args, **kwargs) # noqa
def parse_messages(messages, functions):
if all(m.role != 'user' for m in messages):
raise HTTPException(
status_code=400,
detail='Invalid request: Expecting at least one user message.',
)
messages = copy.deepcopy(messages)
if messages[0].role == 'system':
system = messages.pop(0).content.lstrip('\n').rstrip()
else:
system = 'You are a helpful assistant.'
if functions:
tools_text = []
tools_name_text = []
for func_info in functions:
name = func_info.get('name', '')
name_m = func_info.get('name_for_model', name)
name_h = func_info.get('name_for_human', name)
desc = func_info.get('description', '')
desc_m = func_info.get('description_for_model', desc)
tool = TOOL_DESC.format(
name_for_model=name_m,
name_for_human=name_h,
# Hint: You can add the following format requirements in description:
# "Format the arguments as a JSON object."
# "Enclose the code within triple backticks (`) at the beginning and end of the code."
description_for_model=desc_m,
parameters=json.dumps(func_info['parameters'],
ensure_ascii=False),
)
tools_text.append(tool)
tools_name_text.append(name_m)
tools_text = '\n\n'.join(tools_text)
tools_name_text = ', '.join(tools_name_text)
instruction = (REACT_INSTRUCTION.format(
tools_text=tools_text,
tools_name_text=tools_name_text,
).lstrip('\n').rstrip())
else:
instruction = ''
messages_with_fncall = messages
messages = []
for m_idx, m in enumerate(messages_with_fncall):
role, content, func_call = m.role, m.content, m.function_call
content = content or ''
content = content.lstrip('\n').rstrip()
if role == 'function':
if (len(messages) == 0) or (messages[-1].role != 'assistant'):
raise HTTPException(
status_code=400,
detail=
'Invalid request: Expecting role assistant before role function.',
)
messages[-1].content += f'\nObservation: {content}'
if m_idx == len(messages_with_fncall) - 1:
# add a prefix for text completion
messages[-1].content += '\nThought:'
elif role == 'assistant':
if len(messages) == 0:
raise HTTPException(
status_code=400,
detail=
'Invalid request: Expecting role user before role assistant.',
)
if func_call is None:
if functions:
content = f'Thought: I now know the final answer.\nFinal Answer: {content}'
else:
f_name, f_args = func_call['name'], func_call['arguments']
if not content.startswith('Thought:'):
content = f'Thought: {content}'
content = f'{content}\nAction: {f_name}\nAction Input: {f_args}'
if messages[-1].role == 'user':
messages.append(
ChatMessage(role='assistant',
content=content.lstrip('\n').rstrip()))
else:
messages[-1].content += '\n' + content
elif role == 'user':
messages.append(
ChatMessage(role='user',
content=content.lstrip('\n').rstrip()))
else:
raise HTTPException(
status_code=400,
detail=f'Invalid request: Incorrect role {role}.')
query = _TEXT_COMPLETION_CMD
if messages[-1].role == 'user':
query = messages[-1].content
messages = messages[:-1]
if len(messages) % 2 != 0:
raise HTTPException(status_code=400, detail='Invalid request')
history = [] # [(Q1, A1), (Q2, A2), ..., (Q_last_turn, A_last_turn)]
for i in range(0, len(messages), 2):
if messages[i].role == 'user' and messages[i + 1].role == 'assistant':
usr_msg = messages[i].content.lstrip('\n').rstrip()
bot_msg = messages[i + 1].content.lstrip('\n').rstrip()
if instruction and (i == len(messages) - 2):
usr_msg = f'{instruction}\n\nQuestion: {usr_msg}'
instruction = ''
history.append((usr_msg, bot_msg))
else:
raise HTTPException(
status_code=400,
detail=
'Invalid request: Expecting exactly one user (or function) role before every assistant role.',
)
if instruction:
assert query is not _TEXT_COMPLETION_CMD
query = f'{instruction}\n\nQuestion: {query}'
return query, history, system
def _chat_stream(model, tokenizer, query, history, system: str, **gen_kwargs: Dict):
"""
:param model:
:param tokenizer:
:param query:
:param history: [(Q1, A1), (Q2, A2), ..., (Q_last_turn, A_last_turn)]
:param system:
:param gen_kwargs:
:return:
"""
conversation = [
{'role': 'system', 'content': system},
]
for query_h, response_h in history:
conversation.append({'role': 'user', 'content': query_h})
conversation.append({'role': 'assistant', 'content': response_h})
conversation.append({'role': 'user', 'content': query})
inputs = tokenizer.apply_chat_template(
conversation,
add_generation_prompt=True, tokenize=False,
return_tensors='pt',
)
inputs = inputs.to(model.device)
streamer = TextIteratorStreamer(
tokenizer=tokenizer,
skip_prompt=True,
# timeout=60.0,
skip_special_tokens=True
)
generation_kwargs = dict(
input_ids=inputs,
streamer=streamer,
)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
for new_text in streamer:
yield new_text
def _chat(model, tokenizer, query, history, system: str, stop_words_ids, **gen_kwargs: Dict):
"""
:param model:
:param tokenizer:
:param query:
:param history:
:param system:
:param stop_words_ids:
:param gen_kwargs:
:return:
"""
conversation = [
{'role': 'system', 'content': system},
]
for query_h, response_h in history:
conversation.append({'role': 'user', 'content': query_h})
conversation.append({'role': 'assistant', 'content': response_h})
conversation.append({'role': 'user', 'content': query})
inputs = tokenizer.apply_chat_template(
conversation,
add_generation_prompt=True,
tokenize=False,
return_tensors='pt',
)
model_inputs = tokenizer([inputs], return_tensors="pt").to(model.device)
generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=1024)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
return response
async def predict(
query: str,
history: List[Tuple[str, str]], # [(Q1, A1), (Q2, A2), ..., (Q_last_turn, A_last_turn)]
model_id: str,
stop_words: List[str],
system: str,
**gen_kwargs: Dict,
):
"""
:param query:
:param history:
:param model_id:
:param stop_words:
:param gen_kwargs:
:param system:
:return:
"""
model = AppSettings.qwen2_llm.get_model()
tokenizer = AppSettings.qwen2_llm.get_tokenize()
choice_data = ChatCompletionResponseStreamChoice(
index=0, delta=DeltaMessage(role='assistant'), finish_reason=None)
chunk = ChatCompletionResponse(model=model_id,
choices=[choice_data],
object='chat.completion.chunk')
yield '{}'.format(_dump_json(chunk, exclude_unset=True))
current_length = 0
stop_words_ids = [tokenizer.encode(s)
for s in stop_words] if stop_words else None
delay_token_num = max([len(x) for x in stop_words])
full_response = ""
response = ""
for new_text in _chat_stream(model, tokenizer, query, history=history, system=system, gen_kwargs=gen_kwargs):
response += new_text
choice_data = ChatCompletionResponseStreamChoice(
index=0, delta=DeltaMessage(content=new_text), finish_reason=None)
chunk = ChatCompletionResponse(model=model_id,
choices=[choice_data],
object='chat.completion.chunk')
yield '{}'.format(_dump_json(chunk, exclude_unset=True))
full_response = response
choice_data = ChatCompletionResponseStreamChoice(index=0,
delta=DeltaMessage(),
finish_reason='stop')
chunk = ChatCompletionResponse(model=model_id,
choices=[choice_data],
object='chat.completion.chunk')
yield '{}'.format(_dump_json(chunk, exclude_unset=True))
yield '[DONE]'
_gc()
def trim_stop_words(response, stop_words):
if stop_words:
for stop in stop_words:
idx = response.find(stop)
if idx != -1:
response = response[:idx]
return response
def text_complete_last_message(history, stop_words_ids, gen_kwargs, system):
model = AppSettings.qwen2_llm.get_model()
tokenizer = AppSettings.qwen2_llm.get_tokenize()
im_start = '<|im_start|>'
im_end = '<|im_end|>'
prompt = f'{im_start}system\n{system}{im_end}'
for i, (query, response) in enumerate(history):
query = query.lstrip('\n').rstrip()
response = response.lstrip('\n').rstrip()
prompt += f'\n{im_start}user\n{query}{im_end}'
prompt += f'\n{im_start}assistant\n{response}{im_end}'
prompt = prompt[:-len(im_end)]
_stop_words_ids = [tokenizer.encode(im_end)]
if stop_words_ids:
for s in stop_words_ids:
_stop_words_ids.append(s)
stop_words_ids = _stop_words_ids
input_ids = torch.tensor([tokenizer.encode(prompt)]).to(model.device)
output = model.generate(input_ids,
stop_words_ids=stop_words_ids,
**gen_kwargs).tolist()[0]
output = tokenizer.decode(output, errors='ignore')
assert output.startswith(prompt)
output = output[len(prompt):]
output = trim_stop_words(output, ['<|endoftext|>', im_end])
print(f'<completion>\n{prompt}\n<!-- *** -->\n{output}\n</completion>')
return output
def parse_response(response):
func_name, func_args = '', ''
i = response.find('\nAction:')
j = response.find('\nAction Input:')
k = response.find('\nObservation:')
if 0 <= i < j: # If the text has Action and Action input,
if k < j: # but does not contain Observation,
# then it is likely that Observation is omitted by the LLM,
# because the output text may have discarded the stop word.
response = response.rstrip() + '\nObservation:' # Add it back.
k = response.find('\nObservation:')
func_name = response[i + len('\nAction:'):j].strip()
func_args = response[j + len('\nAction Input:'):k].strip()
if func_name:
response = response[:i]
t = response.find('Thought: ')
if t >= 0:
response = response[t + len('Thought: '):]
response = response.strip()
choice_data = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(
role='assistant',
content=response,
function_call={
'name': func_name,
'arguments': func_args
},
),
finish_reason='function_call',
)
return choice_data
z = response.rfind('\nFinal Answer: ')
if z >= 0:
response = response[z + len('\nFinal Answer: '):]
choice_data = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role='assistant', content=response),
finish_reason='stop',
)
return choice_data
@router.post('/v1/chat/completions', response_model=ChatCompletionResponse)
async def create_chat_completion(request: ChatCompletionRequest):
model = AppSettings.qwen2_llm.get_model()
tokenizer = AppSettings.qwen2_llm.get_tokenize()
gen_kwargs = {}
if request.top_k is not None:
gen_kwargs['top_k'] = request.top_k
if request.temperature is not None:
if request.temperature < 0.01:
gen_kwargs['top_k'] = 1 # greedy decoding
else:
# Not recommended. Please tune top_p instead.
gen_kwargs['temperature'] = request.temperature
if request.top_p is not None:
gen_kwargs['top_p'] = request.top_p
stop_words = add_extra_stop_words(request.stop)
if request.functions and len(request.functions) > 0:
stop_words = stop_words or []
if 'Observation:' not in stop_words:
stop_words.append('Observation:')
query, history, system = parse_messages(request.messages,
request.functions)
if request.stream:
if request.functions and len(request.functions) > 0:
raise HTTPException(
status_code=400,
detail=
'Invalid request: Function calling is not yet implemented for stream mode.',
)
generate = predict(
query,
history,
request.model,
stop_words,
system=system,
**gen_kwargs
)
return EventSourceResponse(generate, media_type='text/event-stream')
stop_words_ids = [tokenizer.encode(s)
for s in stop_words] if stop_words else None
if query is _TEXT_COMPLETION_CMD:
response = text_complete_last_message(history,
stop_words_ids=stop_words_ids,
gen_kwargs=gen_kwargs,
system=system)
else:
response = _chat(
model=model,
tokenizer=tokenizer,
query=query,
history=history,
system=system,
stop_words_ids=stop_words_ids,
**gen_kwargs
)
print('<chat>')
pprint(history, indent=2)
print(f'{query}\n<!-- *** -->\n{response}\n</chat>')
_gc()
response = trim_stop_words(response, stop_words)
if request.functions and len(request.functions) > 0:
choice_data = parse_response(response)
else:
choice_data = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role='assistant', content=response),
finish_reason='stop',
)
return ChatCompletionResponse(model=request.model,
choices=[choice_data],
object='chat.completion')
请求如下:
curl -X 'POST'
'http://127.0.0.1:8000/standard/v1/chat/completions'
-H 'accept: application/json'
-H 'x-token: test-token'
-H 'Content-Type: application/json'
-d '{
"model": "model_name",
"messages": [
{
"role": "user",
"content": "介绍下自己?",
"function_call": {}
}
],
"functions": [],
"temperature": null,
"top_p": null,
"top_k": null,
"max_length": null,
"stream": true,
"stop": []
}
完整报错信息如下:
INFO: 127.0.0.1:40533 - "POST /standard/v1/chat/completions HTTP/1.1" 200 OK
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\sse_starlette\sse.py", line 282, in call
await wrap(partial(self.listen_for_disconnect, receive))
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\sse_starlette\sse.py", line 271, in wrap
await func()
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\sse_starlette\sse.py", line 221, in listen_for_disconnect
message = await receive()
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 535, in receive
await self.message_event.wait()
File "D:\Developer\Python\Python38\lib\asyncio\locks.py", line 309, in wait
await fut
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 407, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 69, in call
return await self.app(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\fastapi\applications.py", line 1054, in call
await super().call(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\applications.py", line 123, in call
await self.middleware_stack(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\middleware\errors.py", line 186, in call
raise exc
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\middleware\errors.py", line 164, in call
await self.app(scope, receive, _send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\middleware\exceptions.py", line 62, in call
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette_exception_handler.py", line 64, in wrapped_app
raise exc
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette_exception_handler.py", line 53, in wrapped_app
await app(scope, receive, sender)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\routing.py", line 758, in
await self.middleware_stack(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\routing.py", line 778, in app
await route.handle(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\routing.py", line 299, in handle
await self.app(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\routing.py", line 79, in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette_exception_handler.py", line 64, in wrapped_app
raise exc
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette_exception_handler.py", line 53, in wrapped_app
await app(scope, receive, sender)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\starlette\routing.py", line 77, in app
await response(scope, receive, send)
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\sse_starlette\sse.py", line 282, in
await wrap(partial(self.listen_for_disconnect, receive))
File "F:\repository\github\ai\udc-llm\venv\lib\site-packages\anyio_backends_asyncio.py", line 678, in
raise BaseExceptionGroup(
exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)