2023-12-20 21:13:05 +08:00
|
|
|
|
# flake8: noqa: E402
|
2024-01-05 12:27:57 +08:00
|
|
|
|
import json
|
2023-12-13 14:18:08 +08:00
|
|
|
|
import os
|
2024-01-05 12:27:57 +08:00
|
|
|
|
import re
|
2024-01-31 16:14:50 +08:00
|
|
|
|
import sys
|
|
|
|
|
from functools import wraps
|
|
|
|
|
from typing import Dict, List, Optional
|
2023-12-08 10:37:32 +08:00
|
|
|
|
|
|
|
|
|
import openai
|
|
|
|
|
|
2024-01-31 12:52:45 +08:00
|
|
|
|
from .pipeline import (
|
|
|
|
|
RetryException,
|
|
|
|
|
exception_err,
|
|
|
|
|
exception_handle,
|
|
|
|
|
exception_output_handle,
|
|
|
|
|
parallel,
|
|
|
|
|
pipeline,
|
|
|
|
|
retry,
|
|
|
|
|
)
|
2023-12-20 21:13:05 +08:00
|
|
|
|
|
2023-12-08 10:55:48 +08:00
|
|
|
|
|
|
|
|
|
def _try_remove_markdown_block_flag(content):
|
|
|
|
|
"""
|
|
|
|
|
如果content是一个markdown块,则删除它的头部```xxx和尾部```
|
|
|
|
|
"""
|
|
|
|
|
# 定义正则表达式模式,用于匹配markdown块的头部和尾部
|
2023-12-08 18:28:36 +08:00
|
|
|
|
pattern = r"^\s*```\s*(\w+)\s*\n(.*?)\n\s*```\s*$"
|
|
|
|
|
|
2023-12-08 10:55:48 +08:00
|
|
|
|
# 使用re模块进行匹配
|
|
|
|
|
match = re.search(pattern, content, re.DOTALL | re.MULTILINE)
|
2023-12-08 18:28:36 +08:00
|
|
|
|
|
2023-12-08 10:55:48 +08:00
|
|
|
|
if match:
|
|
|
|
|
# 如果匹配成功,则提取出markdown块的内容并返回
|
2023-12-08 18:38:12 +08:00
|
|
|
|
_ = match.group(1) # language
|
2023-12-08 10:55:48 +08:00
|
|
|
|
markdown_content = match.group(2)
|
|
|
|
|
return markdown_content.strip()
|
|
|
|
|
else:
|
|
|
|
|
# 如果匹配失败,则返回原始内容
|
|
|
|
|
return content
|
|
|
|
|
|
2023-12-08 18:28:36 +08:00
|
|
|
|
|
2024-01-24 21:23:44 +08:00
|
|
|
|
def chat_completion_stream_commit(
|
2024-01-24 17:34:27 +08:00
|
|
|
|
messages: List[Dict], # [{"role": "user", "content": "hello"}]
|
|
|
|
|
llm_config: Dict, # {"model": "...", ...}
|
2024-01-24 21:23:44 +08:00
|
|
|
|
):
|
|
|
|
|
client = openai.OpenAI(
|
|
|
|
|
api_key=os.environ.get("OPENAI_API_KEY", None),
|
|
|
|
|
base_url=os.environ.get("OPENAI_API_BASE", None),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
llm_config["stream"] = True
|
|
|
|
|
llm_config["timeout"] = 60
|
|
|
|
|
return client.chat.completions.create(messages=messages, **llm_config)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def chat_completion_stream_raw(**kwargs):
|
|
|
|
|
client = openai.OpenAI(
|
|
|
|
|
api_key=os.environ.get("OPENAI_API_KEY", None),
|
|
|
|
|
base_url=os.environ.get("OPENAI_API_BASE", None),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
kwargs["stream"] = True
|
|
|
|
|
kwargs["timeout"] = 60
|
|
|
|
|
return client.chat.completions.create(**kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def stream_out_chunk(chunks):
|
|
|
|
|
for chunk in chunks:
|
|
|
|
|
chunk_dict = chunk.dict()
|
|
|
|
|
delta = chunk_dict["choices"][0]["delta"]
|
|
|
|
|
if delta.get("content", None):
|
|
|
|
|
print(delta["content"], end="", flush=True)
|
|
|
|
|
yield chunk
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def retry_timeout(chunks):
|
|
|
|
|
try:
|
|
|
|
|
for chunk in chunks:
|
|
|
|
|
yield chunk
|
|
|
|
|
except (openai.APIConnectionError, openai.APITimeoutError) as err:
|
2024-01-31 16:14:51 +08:00
|
|
|
|
raise RetryException(err) from err
|
2024-01-24 21:23:44 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def chunk_list(chunks):
|
|
|
|
|
return [chunk for chunk in chunks]
|
|
|
|
|
|
2024-01-24 21:26:11 +08:00
|
|
|
|
|
2024-01-24 21:23:44 +08:00
|
|
|
|
def chunks_content(chunks):
|
|
|
|
|
content = None
|
|
|
|
|
for chunk in chunks:
|
|
|
|
|
chunk_dict = chunk.dict()
|
|
|
|
|
delta = chunk_dict["choices"][0]["delta"]
|
|
|
|
|
if delta.get("content", None):
|
|
|
|
|
if content is None:
|
|
|
|
|
content = ""
|
|
|
|
|
content += delta["content"]
|
|
|
|
|
return content
|
|
|
|
|
|
2024-01-24 21:26:11 +08:00
|
|
|
|
|
2024-01-24 21:23:44 +08:00
|
|
|
|
def chunks_call(chunks):
|
|
|
|
|
function_name = None
|
|
|
|
|
parameters = ""
|
2024-01-24 21:26:11 +08:00
|
|
|
|
|
2024-01-24 21:23:44 +08:00
|
|
|
|
for chunk in chunks:
|
|
|
|
|
chunk = chunk.dict()
|
|
|
|
|
delta = chunk["choices"][0]["delta"]
|
|
|
|
|
if "tool_calls" in delta and delta["tool_calls"]:
|
|
|
|
|
tool_call = delta["tool_calls"][0]["function"]
|
|
|
|
|
if tool_call.get("name", None):
|
|
|
|
|
function_name = tool_call["name"]
|
|
|
|
|
if tool_call.get("arguments", None):
|
|
|
|
|
parameters += tool_call["arguments"]
|
|
|
|
|
return {"function_name": function_name, "parameters": parameters}
|
|
|
|
|
|
2024-01-24 21:26:11 +08:00
|
|
|
|
|
2024-01-24 21:23:44 +08:00
|
|
|
|
def content_to_json(content):
|
|
|
|
|
try:
|
|
|
|
|
# json will format as ```json ... ``` in 1106 model
|
|
|
|
|
response_content = _try_remove_markdown_block_flag(content)
|
|
|
|
|
response_obj = json.loads(response_content)
|
|
|
|
|
return response_obj
|
|
|
|
|
except json.JSONDecodeError as err:
|
2024-01-31 16:14:51 +08:00
|
|
|
|
raise RetryException(err) from err
|
2024-01-24 21:23:44 +08:00
|
|
|
|
except Exception as err:
|
|
|
|
|
raise err
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def to_dict_content_and_call(content, function_call):
|
2024-01-24 21:26:11 +08:00
|
|
|
|
return {"content": content, **function_call}
|
2024-01-24 21:23:44 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chat_completion_content = retry(
|
2024-01-24 21:26:11 +08:00
|
|
|
|
pipeline(chat_completion_stream_commit, retry_timeout, chunks_content), times=3
|
2024-01-24 21:23:44 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
chat_completion_stream_content = retry(
|
2024-01-24 21:26:11 +08:00
|
|
|
|
pipeline(chat_completion_stream_commit, retry_timeout, stream_out_chunk, chunks_content),
|
|
|
|
|
times=3,
|
2024-01-24 21:23:44 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
chat_completion_call = retry(
|
2024-01-24 21:26:11 +08:00
|
|
|
|
pipeline(chat_completion_stream_commit, retry_timeout, chunks_call), times=3
|
2024-01-24 21:23:44 +08:00
|
|
|
|
)
|
|
|
|
|
|
2024-01-31 12:50:17 +08:00
|
|
|
|
chat_completion_no_stream_return_json = exception_handle(
|
|
|
|
|
retry(
|
2024-01-31 12:52:45 +08:00
|
|
|
|
pipeline(chat_completion_stream_commit, retry_timeout, chunks_content, content_to_json),
|
|
|
|
|
times=3,
|
2024-01-31 12:50:17 +08:00
|
|
|
|
),
|
2024-01-31 12:52:45 +08:00
|
|
|
|
exception_output_handle(lambda err: None),
|
2024-01-24 21:23:44 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
chat_completion_stream = exception_handle(
|
|
|
|
|
retry(
|
|
|
|
|
pipeline(
|
|
|
|
|
chat_completion_stream_commit,
|
|
|
|
|
retry_timeout,
|
2024-01-24 21:26:11 +08:00
|
|
|
|
parallel(chunks_content, chunks_call),
|
|
|
|
|
to_dict_content_and_call,
|
2024-01-24 21:23:44 +08:00
|
|
|
|
),
|
2024-01-24 21:26:11 +08:00
|
|
|
|
times=3,
|
2024-01-24 21:23:44 +08:00
|
|
|
|
),
|
2024-01-31 12:50:17 +08:00
|
|
|
|
lambda err: {
|
|
|
|
|
"content": None,
|
|
|
|
|
"function_name": None,
|
|
|
|
|
"parameters": "",
|
2024-01-31 12:52:45 +08:00
|
|
|
|
"error": err.type if isinstance(err, openai.APIError) else err,
|
|
|
|
|
},
|
2024-01-24 21:23:44 +08:00
|
|
|
|
)
|
2024-01-31 16:14:51 +08:00
|
|
|
|
|
|
|
|
|
chat_call_completion_stream = exception_handle(
|
|
|
|
|
retry(
|
|
|
|
|
pipeline(
|
|
|
|
|
chat_completion_stream_commit,
|
|
|
|
|
retry_timeout,
|
|
|
|
|
chunk_list,
|
|
|
|
|
parallel(
|
|
|
|
|
chunks_content,
|
|
|
|
|
chunks_call
|
|
|
|
|
),
|
|
|
|
|
to_dict_content_and_call
|
|
|
|
|
),
|
|
|
|
|
times=3
|
|
|
|
|
),
|
|
|
|
|
lambda err: {
|
|
|
|
|
"content": None,
|
|
|
|
|
"function_name": None,
|
|
|
|
|
"parameters": "",
|
|
|
|
|
"error": err.type if isinstance(err, openai.APIError) else err
|
|
|
|
|
}
|
|
|
|
|
)
|