LLM
/
Azure-OpenAI
copied
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Readme
Files and versions
83 lines
3.1 KiB
83 lines
3.1 KiB
# Copyright 2021 Zilliz. All rights reserved.
|
|
#
|
|
# 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 os
|
|
from typing import List
|
|
|
|
import openai
|
|
from towhee.operator.base import PyOperator
|
|
|
|
class AzureOpenaiChat(PyOperator):
|
|
'''Wrapper of OpenAI Chat API'''
|
|
def __init__(self,
|
|
deployment_name: str = 'gpt-3.5-turbo',
|
|
api_type: str = 'azure',
|
|
api_version: str = '2023-07-01-preview',
|
|
api_key: str = None,
|
|
api_base = None,
|
|
**kwargs
|
|
):
|
|
|
|
self._api_key = api_key or os.getenv('OPENAI_API_KEY')
|
|
self._api_base = api_base or os.getenv('OPENAI_API_BASE')
|
|
self._api_type = api_type
|
|
self._api_version = api_version
|
|
|
|
self._deployment = deployment_name
|
|
self.stream = kwargs.pop('stream') if 'stream' in kwargs else False
|
|
self.kwargs = kwargs
|
|
|
|
def __call__(self, messages: List[dict]):
|
|
messages = self.parse_inputs(messages)
|
|
response = openai.ChatCompletion.create(
|
|
engine=self._deployment,
|
|
messages=messages,
|
|
n=1,
|
|
stream=self.stream,
|
|
api_key = self._api_key,
|
|
api_type = self._api_type,
|
|
api_base = self._api_base,
|
|
api_version = self._api_version,
|
|
**self.kwargs
|
|
)
|
|
if self.stream:
|
|
return self.stream_output(response)
|
|
else:
|
|
answer = response['choices'][0]['message']['content']
|
|
return answer
|
|
|
|
def parse_inputs(self, messages: List[dict]):
|
|
assert isinstance(messages, list), \
|
|
'Inputs must be a list of dictionaries with keys from ["system", "question", "answer"].'
|
|
new_messages = []
|
|
for m in messages:
|
|
if ('role' and 'content' in m) and (m['role'] in ['system', 'assistant', 'user']):
|
|
new_messages.append(m)
|
|
else:
|
|
for k, v in m.items():
|
|
if k == 'question':
|
|
new_m = {'role': 'user', 'content': v}
|
|
elif k == 'answer':
|
|
new_m = {'role': 'assistant', 'content': v}
|
|
elif k == 'system':
|
|
new_m = {'role': 'system', 'content': v}
|
|
else:
|
|
raise KeyError('Invalid message key: only accept key value from ["system", "question", "answer"].')
|
|
new_messages.append(new_m)
|
|
return new_messages
|
|
|
|
def stream_output(self, response):
|
|
for resp in response:
|
|
yield resp['choices'][0]['delta']
|
|
|