2023-08-27 18:07:33 -07:00
|
|
|
import openai
|
2023-11-13 16:07:33 -08:00
|
|
|
from openai import AsyncOpenAI
|
2023-08-27 18:07:33 -07:00
|
|
|
import os
|
|
|
|
|
import asyncio
|
|
|
|
|
from asyncio import Queue
|
|
|
|
|
import logging
|
2023-09-19 21:36:56 -07:00
|
|
|
import json
|
2023-11-05 15:21:27 -08:00
|
|
|
import aiohttp
|
2023-11-17 12:01:16 +08:00
|
|
|
import base64
|
|
|
|
|
import requests
|
2023-08-27 18:07:33 -07:00
|
|
|
|
2023-09-26 22:50:50 -07:00
|
|
|
from .compute_task import ComputeTask, ComputeTaskResult, ComputeTaskState, ComputeTaskType,ComputeTaskResultCode
|
2023-08-23 11:19:16 -07:00
|
|
|
from .compute_node import ComputeNode
|
2023-09-17 18:18:54 -07:00
|
|
|
from .storage import AIStorage,UserConfig
|
2023-08-20 22:53:35 -07:00
|
|
|
|
2023-11-05 15:21:27 -08:00
|
|
|
|
2023-08-27 18:07:33 -07:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2023-09-07 12:50:13 +08:00
|
|
|
|
2023-08-23 11:19:16 -07:00
|
|
|
class OpenAI_ComputeNode(ComputeNode):
|
2023-08-27 18:07:33 -07:00
|
|
|
_instance = None
|
2023-09-16 11:41:59 -07:00
|
|
|
@classmethod
|
|
|
|
|
def get_instance(cls):
|
2023-08-27 18:07:33 -07:00
|
|
|
if cls._instance is None:
|
2023-09-16 11:41:59 -07:00
|
|
|
cls._instance = OpenAI_ComputeNode()
|
2023-08-27 18:07:33 -07:00
|
|
|
return cls._instance
|
2023-09-22 00:09:21 +08:00
|
|
|
|
2023-09-17 18:18:54 -07:00
|
|
|
@classmethod
|
|
|
|
|
def declare_user_config(cls):
|
|
|
|
|
if os.getenv("OPENAI_API_KEY_") is None:
|
|
|
|
|
user_config = AIStorage.get_instance().get_user_config()
|
|
|
|
|
user_config.add_user_config("openai_api_key","openai api key",False,None)
|
2023-09-07 12:50:13 +08:00
|
|
|
|
2023-08-27 18:07:33 -07:00
|
|
|
def __init__(self) -> None:
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
2023-09-16 11:41:59 -07:00
|
|
|
self.is_start = False
|
2023-09-07 12:50:13 +08:00
|
|
|
# openai.organization = "org-AoKrOtF2myemvfiFfnsSU8rF" #buckycloud
|
2023-09-17 18:18:54 -07:00
|
|
|
self.openai_api_key = None
|
2023-08-27 18:07:33 -07:00
|
|
|
self.node_id = "openai_node"
|
|
|
|
|
self.task_queue = Queue()
|
|
|
|
|
|
2023-09-17 18:18:54 -07:00
|
|
|
|
|
|
|
|
async def initial(self):
|
2023-09-07 12:50:13 +08:00
|
|
|
if os.getenv("OPENAI_API_KEY") is not None:
|
2023-09-17 18:18:54 -07:00
|
|
|
self.openai_api_key = os.getenv("OPENAI_API_KEY")
|
2023-08-27 18:07:33 -07:00
|
|
|
else:
|
2023-09-19 00:53:13 -07:00
|
|
|
self.openai_api_key = AIStorage.get_instance().get_user_config().get_value("openai_api_key")
|
2023-09-07 12:50:13 +08:00
|
|
|
|
2023-09-17 18:18:54 -07:00
|
|
|
if self.openai_api_key is None:
|
|
|
|
|
logger.error("openai_api_key is None!")
|
|
|
|
|
return False
|
2023-09-22 00:09:21 +08:00
|
|
|
|
2023-09-17 18:18:54 -07:00
|
|
|
openai.api_key = self.openai_api_key
|
2023-08-27 18:07:33 -07:00
|
|
|
self.start()
|
2023-09-17 18:18:54 -07:00
|
|
|
return True
|
2023-09-07 12:50:13 +08:00
|
|
|
|
|
|
|
|
async def push_task(self, task: ComputeTask, proiority: int = 0):
|
2023-08-27 18:07:33 -07:00
|
|
|
logger.info(f"openai_node push task: {task.display()}")
|
|
|
|
|
self.task_queue.put_nowait(task)
|
2023-08-31 15:45:02 +08:00
|
|
|
|
2023-09-07 12:50:13 +08:00
|
|
|
async def remove_task(self, task_id: str):
|
2023-08-27 18:07:33 -07:00
|
|
|
pass
|
2023-08-31 16:32:20 +08:00
|
|
|
|
2023-11-13 16:07:33 -08:00
|
|
|
def message_to_dict(self, message)->dict:
|
|
|
|
|
result = message.dict()
|
|
|
|
|
# result_msg = {}
|
|
|
|
|
# #message.json()
|
|
|
|
|
# if message.content:
|
|
|
|
|
# result_msg["content"] = message.content
|
|
|
|
|
# result_msg["role"] = message.role
|
|
|
|
|
# if message.function_call:
|
|
|
|
|
# function_call = {}
|
|
|
|
|
# function_call["arguments"] = message.function_call.arguments
|
|
|
|
|
# function_call["name"] = message.function_call.name
|
|
|
|
|
# result_msg["function_call"] = function_call
|
|
|
|
|
|
|
|
|
|
# if message.tool_calls:
|
|
|
|
|
# tool_calls = []
|
|
|
|
|
# for tool_call in message.tool_calls:
|
|
|
|
|
# tool_call_dict = {}
|
|
|
|
|
# tool_call_dict["id"] = tool_call.id
|
|
|
|
|
# tool_call_dict["type"] = tool_call.type
|
|
|
|
|
# func_call_dict = {}
|
|
|
|
|
# func_call_dict["name"] = tool_call.function.name
|
|
|
|
|
# func_call_dict["arguments"] = tool_call.function.arguments
|
|
|
|
|
# tool_call_dict["function"] = func_call_dict
|
|
|
|
|
|
|
|
|
|
# tool_calls.append(tool_call_dict)
|
|
|
|
|
# result_msg["tool_calls"] = message.tool_calls
|
|
|
|
|
|
|
|
|
|
# result["message"] = result_msg
|
|
|
|
|
return result
|
2023-11-17 12:01:16 +08:00
|
|
|
|
|
|
|
|
def _image_2_text(self, task: ComputeTask):
|
|
|
|
|
logger.info('openai image_2_text')
|
|
|
|
|
# 本地图片处理
|
|
|
|
|
def encode_image(image_path):
|
|
|
|
|
with open(image_path, "rb") as image_file:
|
|
|
|
|
return base64.b64encode(image_file.read()).decode('utf-8')
|
|
|
|
|
headers = {
|
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
|
"Authorization": f"Bearer {self.openai_api_key }"
|
|
|
|
|
}
|
|
|
|
|
model_name = task.params["model_name"]
|
|
|
|
|
base64_image = encode_image(task.params["image_path"])
|
|
|
|
|
payload = {
|
|
|
|
|
"model": model_name,
|
|
|
|
|
"messages": [
|
|
|
|
|
{
|
|
|
|
|
"role": "user",
|
|
|
|
|
"content": [
|
|
|
|
|
{
|
|
|
|
|
"type": "text",
|
|
|
|
|
"text": task.params["prompt"]
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
"type": "image_url",
|
|
|
|
|
"image_url": {
|
|
|
|
|
"url": f"data:image/jpeg;base64,{base64_image}"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
}
|
|
|
|
|
],
|
|
|
|
|
"max_tokens": 300
|
|
|
|
|
}
|
|
|
|
|
logger.info('openai send image_2_text request ')
|
|
|
|
|
# openai 的库的Vision只支持传图片的url地址。本地图片得用request
|
|
|
|
|
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
|
|
|
|
|
if response.status_code == 200:
|
|
|
|
|
logger.info('openai image_2_text success')
|
|
|
|
|
return response.json()
|
|
|
|
|
else:
|
|
|
|
|
logger.error('openai image_2_text error')
|
|
|
|
|
logger.error(response.json())
|
|
|
|
|
return None
|
2023-11-05 15:21:27 -08:00
|
|
|
|
|
|
|
|
async def _run_task(self, task: ComputeTask):
|
2023-08-27 18:07:33 -07:00
|
|
|
task.state = ComputeTaskState.RUNNING
|
2023-09-26 22:50:50 -07:00
|
|
|
|
|
|
|
|
result = ComputeTaskResult()
|
|
|
|
|
result.result_code = ComputeTaskResultCode.ERROR
|
|
|
|
|
result.set_from_task(task)
|
|
|
|
|
|
2023-09-18 11:41:16 -07:00
|
|
|
match task.task_type:
|
|
|
|
|
case ComputeTaskType.TEXT_EMBEDDING:
|
|
|
|
|
model_name = task.params["model_name"]
|
|
|
|
|
input = task.params["input"]
|
|
|
|
|
logger.info(f"call openai {model_name} input: {input}")
|
2023-09-26 22:50:50 -07:00
|
|
|
try:
|
|
|
|
|
resp = openai.Embedding.create(model=model_name,
|
2023-09-18 11:41:16 -07:00
|
|
|
input=input)
|
2023-09-26 22:50:50 -07:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"openai run TEXT_EMBEDDING task error: {e}")
|
|
|
|
|
task.state = ComputeTaskState.ERROR
|
|
|
|
|
task.error_str = str(e)
|
|
|
|
|
result.error_str = str(e)
|
|
|
|
|
return result
|
|
|
|
|
|
2023-09-18 11:41:16 -07:00
|
|
|
# resp = {
|
|
|
|
|
# "object": "list",
|
|
|
|
|
# "data": [
|
|
|
|
|
# {
|
|
|
|
|
# "object": "embedding",
|
|
|
|
|
# "index": 0,
|
|
|
|
|
# "embedding": [
|
|
|
|
|
# -0.00930514745414257,
|
|
|
|
|
# 0.00765434792265296,
|
|
|
|
|
# -0.007167573552578688,
|
|
|
|
|
# -0.012373941019177437,
|
|
|
|
|
# -0.04884673282504082
|
|
|
|
|
# ]}]
|
|
|
|
|
# }
|
|
|
|
|
|
|
|
|
|
logger.info(f"openai response: {resp}")
|
2023-09-26 22:50:50 -07:00
|
|
|
task.state = ComputeTaskState.DONE
|
|
|
|
|
result.result_code = ComputeTaskResultCode.OK
|
2023-09-18 11:41:16 -07:00
|
|
|
result.worker_id = self.node_id
|
2023-09-27 17:24:00 +08:00
|
|
|
result.result_str = resp["data"][0]["embedding"]
|
2023-09-18 11:41:16 -07:00
|
|
|
|
2023-11-17 12:01:16 +08:00
|
|
|
return result
|
|
|
|
|
case ComputeTaskType.IMAGE_2_TEXT:
|
|
|
|
|
result.result_code = ComputeTaskResultCode.OK
|
|
|
|
|
result.worker_id = self.node_id
|
|
|
|
|
# result.result_str = resp["data"][0]["image_2_text"]
|
|
|
|
|
result.result["message"] = self._image_2_text(task)
|
2023-09-18 11:41:16 -07:00
|
|
|
return result
|
|
|
|
|
case ComputeTaskType.LLM_COMPLETION:
|
|
|
|
|
mode_name = task.params["model_name"]
|
|
|
|
|
prompts = task.params["prompts"]
|
2023-11-13 16:07:33 -08:00
|
|
|
resp_mode = task.params["resp_mode"]
|
|
|
|
|
if resp_mode == "json":
|
|
|
|
|
response_format = { "type": "json_object" }
|
|
|
|
|
else:
|
|
|
|
|
response_format = None
|
2023-09-18 11:41:16 -07:00
|
|
|
max_token_size = task.params.get("max_token_size")
|
2023-09-19 00:23:19 -07:00
|
|
|
llm_inner_functions = task.params.get("inner_functions")
|
2023-09-18 11:41:16 -07:00
|
|
|
if max_token_size is None:
|
|
|
|
|
max_token_size = 4000
|
2023-09-20 14:45:54 -07:00
|
|
|
|
2023-09-22 00:09:21 +08:00
|
|
|
result_token = max_token_size
|
2023-11-13 16:07:33 -08:00
|
|
|
client = AsyncOpenAI()
|
2023-09-26 22:50:50 -07:00
|
|
|
try:
|
|
|
|
|
if llm_inner_functions is None:
|
|
|
|
|
logger.info(f"call openai {mode_name} prompts: {prompts}")
|
2023-11-13 16:07:33 -08:00
|
|
|
resp = await client.chat.completions.create(model=mode_name,
|
2023-09-18 11:41:16 -07:00
|
|
|
messages=prompts,
|
2023-11-13 16:07:33 -08:00
|
|
|
response_format = response_format,
|
2023-09-23 13:19:18 +08:00
|
|
|
#max_tokens=result_token,
|
2023-11-13 16:07:33 -08:00
|
|
|
)
|
2023-09-26 22:50:50 -07:00
|
|
|
else:
|
2023-10-18 11:19:11 -07:00
|
|
|
logger.info(f"call openai {mode_name} prompts: \n\t {prompts} \nfunctions: \n\t{json.dumps(llm_inner_functions)}")
|
2023-11-13 16:07:33 -08:00
|
|
|
resp = await client.chat.completions.create(model=mode_name,
|
2023-09-26 22:50:50 -07:00
|
|
|
messages=prompts,
|
2023-11-13 16:07:33 -08:00
|
|
|
response_format = response_format,
|
2023-09-26 22:50:50 -07:00
|
|
|
functions=llm_inner_functions,
|
|
|
|
|
#max_tokens=result_token,
|
2023-11-13 16:07:33 -08:00
|
|
|
) # TODO: add temperature to task params?
|
2023-09-26 22:50:50 -07:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"openai run LLM_COMPLETION task error: {e}")
|
|
|
|
|
task.state = ComputeTaskState.ERROR
|
|
|
|
|
task.error_str = str(e)
|
|
|
|
|
result.error_str = str(e)
|
|
|
|
|
return result
|
2023-09-22 00:09:21 +08:00
|
|
|
|
2023-11-13 16:07:33 -08:00
|
|
|
logger.info(f"openai response: {resp}")
|
|
|
|
|
status_code = resp.choices[0].finish_reason
|
|
|
|
|
token_usage = resp.usage
|
2023-09-18 11:41:16 -07:00
|
|
|
|
|
|
|
|
match status_code:
|
|
|
|
|
case "function_call":
|
|
|
|
|
task.state = ComputeTaskState.DONE
|
|
|
|
|
case "stop":
|
|
|
|
|
task.state = ComputeTaskState.DONE
|
|
|
|
|
case _:
|
|
|
|
|
task.state = ComputeTaskState.ERROR
|
|
|
|
|
task.error_str = f"The status code was {status_code}."
|
2023-09-26 22:50:50 -07:00
|
|
|
result.error_str = f"The status code was {status_code}."
|
|
|
|
|
result.result_code = ComputeTaskResultCode.ERROR
|
|
|
|
|
return result
|
2023-09-18 11:41:16 -07:00
|
|
|
|
2023-09-26 22:50:50 -07:00
|
|
|
result.result_code = ComputeTaskResultCode.OK
|
2023-09-18 11:41:16 -07:00
|
|
|
result.worker_id = self.node_id
|
2023-11-13 16:07:33 -08:00
|
|
|
result.result_str = resp.choices[0].message.content
|
|
|
|
|
|
|
|
|
|
result.result["message"] = self.message_to_dict(resp.choices[0].message)
|
2023-09-28 14:03:52 -07:00
|
|
|
|
2023-09-20 14:45:54 -07:00
|
|
|
if token_usage:
|
|
|
|
|
result.result_refers["token_usage"] = token_usage
|
2023-09-22 00:09:21 +08:00
|
|
|
logger.info(f"openai success response: {result.result_str}")
|
2023-09-18 11:41:16 -07:00
|
|
|
return result
|
|
|
|
|
case _:
|
|
|
|
|
task.state = ComputeTaskState.ERROR
|
2023-09-26 22:50:50 -07:00
|
|
|
task.error_str = f"ComputeTask's TaskType : {task.task_type} not support!"
|
|
|
|
|
result.error_str = f"ComputeTask's TaskType : {task.task_type} not support!"
|
2023-09-18 11:41:16 -07:00
|
|
|
return None
|
2023-09-18 00:37:41 -07:00
|
|
|
|
2023-08-27 18:07:33 -07:00
|
|
|
def start(self):
|
2023-09-16 11:41:59 -07:00
|
|
|
if self.is_start is True:
|
|
|
|
|
return
|
|
|
|
|
self.is_start = True
|
2023-09-22 00:09:21 +08:00
|
|
|
|
2023-08-27 18:07:33 -07:00
|
|
|
async def _run_task_loop():
|
|
|
|
|
while True:
|
|
|
|
|
task = await self.task_queue.get()
|
|
|
|
|
logger.info(f"openai_node get task: {task.display()}")
|
2023-11-05 15:21:27 -08:00
|
|
|
result = await self._run_task(task)
|
2023-08-27 18:07:33 -07:00
|
|
|
if result is not None:
|
|
|
|
|
task.state = ComputeTaskState.DONE
|
|
|
|
|
task.result = result
|
2023-09-07 12:50:13 +08:00
|
|
|
|
2023-08-27 18:07:33 -07:00
|
|
|
asyncio.create_task(_run_task_loop())
|
|
|
|
|
|
2023-08-20 22:53:35 -07:00
|
|
|
def display(self) -> str:
|
2023-08-27 18:07:33 -07:00
|
|
|
return f"OpenAI_ComputeNode: {self.node_id}"
|
|
|
|
|
|
2023-09-07 12:50:13 +08:00
|
|
|
def get_task_state(self, task_id: str):
|
|
|
|
|
pass
|
2023-08-27 18:07:33 -07:00
|
|
|
|
|
|
|
|
def get_capacity(self):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2023-08-31 16:32:20 +08:00
|
|
|
def is_support(self, task: ComputeTask) -> bool:
|
2023-09-22 00:09:21 +08:00
|
|
|
if task.task_type == ComputeTaskType.LLM_COMPLETION:
|
2023-09-20 02:23:46 -07:00
|
|
|
if not task.params["model_name"]:
|
2023-09-18 00:37:41 -07:00
|
|
|
return True
|
2023-09-20 02:23:46 -07:00
|
|
|
model_name : str = task.params["model_name"]
|
|
|
|
|
if model_name.startswith("gpt-"):
|
|
|
|
|
return True
|
2023-09-28 19:14:52 -07:00
|
|
|
|
2023-11-17 12:01:16 +08:00
|
|
|
if task.task_type == ComputeTaskType.IMAGE_2_TEXT:
|
|
|
|
|
model_name : str = task.params["model_name"]
|
|
|
|
|
if model_name.startswith("gpt-4"):
|
|
|
|
|
return True
|
2023-09-28 19:14:52 -07:00
|
|
|
#if task.task_type == ComputeTaskType.TEXT_EMBEDDING:
|
|
|
|
|
# if task.params["model_name"] == "text-embedding-ada-002":
|
|
|
|
|
# return True
|
2023-08-31 16:32:20 +08:00
|
|
|
return False
|
2023-08-27 18:07:33 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_local(self) -> bool:
|
|
|
|
|
return False
|