Spaces:
Runtime error
Runtime error
File size: 12,993 Bytes
3bbba47 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
# -*- coding: utf-8 -*-
# Copyright (c) 2024 OSU Natural Language Processing Group
#
# Licensed under the OpenRAIL-S License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.licenses.ai/ai-pubs-open-rails-vz1
#
# 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
import time
import backoff
import openai
from openai import (
APIConnectionError,
APIError,
RateLimitError,
)
import requests
from dotenv import load_dotenv
import litellm
import base64
EMPTY_API_KEY="Your API KEY Here"
def load_openai_api_key():
load_dotenv()
assert (
os.getenv("OPENAI_API_KEY") is not None and
os.getenv("OPENAI_API_KEY") != EMPTY_API_KEY
), "must pass on the api_key or set OPENAI_API_KEY in the environment"
return os.getenv("OPENAI_API_KEY")
def load_gemini_api_key():
load_dotenv()
assert (
os.getenv("GEMINI_API_KEY") is not None and
os.getenv("GEMINI_API_KEY") != EMPTY_API_KEY
), "must pass on the api_key or set GEMINI_API_KEY in the environment"
return os.getenv("GEMINI_API_KEY")
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def engine_factory(api_key=None, model=None, **kwargs):
model = model.lower()
if model in ["gpt-4-vision-preview", "gpt-4-turbo", "gpt-4o"]:
if api_key and api_key != EMPTY_API_KEY:
os.environ["OPENAI_API_KEY"] = api_key
else:
load_openai_api_key()
return OpenAIEngine(model=model, **kwargs)
elif model in ["gemini-1.5-pro-latest", "gemini-1.5-flash"]:
if api_key and api_key != EMPTY_API_KEY:
os.environ["GEMINI_API_KEY"] = api_key
else:
load_gemini_api_key()
model=f"gemini/{model}"
return GeminiEngine(model=model, **kwargs)
elif model == "llava":
model="llava"
return OllamaEngine(model=model, **kwargs)
raise Exception(f"Unsupported model: {model}, currently supported models: \
gpt-4-vision-preview, gpt-4-turbo, gemini-1.5-pro-latest, llava")
class Engine:
def __init__(
self,
stop=["\n\n"],
rate_limit=-1,
model=None,
temperature=0,
**kwargs,
) -> None:
"""
Base class to init an engine
Args:
api_key (_type_, optional): Auth key from OpenAI. Defaults to None.
stop (list, optional): Tokens indicate stop of sequence. Defaults to ["\n"].
rate_limit (int, optional): Max number of requests per minute. Defaults to -1.
model (_type_, optional): Model family. Defaults to None.
"""
self.time_slots = [0]
self.stop = stop
self.temperature = temperature
self.model = model
# convert rate limit to minmum request interval
self.request_interval = 0 if rate_limit == -1 else 60.0 / rate_limit
self.next_avil_time = [0] * len(self.time_slots)
self.current_key_idx = 0
print(f"Initializing model {self.model}")
def tokenize(self, input):
return self.tokenizer(input)
class OllamaEngine(Engine):
def __init__(self, **kwargs) -> None:
"""
Init an Ollama engine
To use Ollama, dowload and install Ollama from https://ollama.com/
After Ollama start, pull llava with command: ollama pull llava
"""
super().__init__(**kwargs)
self.api_url = "http://localhost:11434/api/chat"
def generate(self, prompt: list = None, max_new_tokens=4096, temperature=None, model=None, image_path=None,
ouput_0=None, turn_number=0, **kwargs):
self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots)
start_time = time.time()
if (
self.request_interval > 0
and start_time < self.next_avil_time[self.current_key_idx]
):
wait_time = self.next_avil_time[self.current_key_idx] - start_time
print(f"Wait {wait_time} for rate limitting")
time.sleep(wait_time)
prompt0, prompt1, prompt2 = prompt
base64_image = encode_image(image_path)
if turn_number == 0:
# Assume one turn dialogue
prompt_input = [
{"role": "assistant", "content": prompt0},
{"role": "user", "content": prompt1, "images": [f"{base64_image}"]},
]
elif turn_number == 1:
prompt_input = [
{"role": "assistant", "content": prompt0},
{"role": "user", "content": prompt1, "images": [f"{base64_image}"]},
{"role": "assistant", "content": f"\n\n{ouput_0}"},
{"role": "user", "content": prompt2},
]
options = {"temperature": self.temperature, "num_predict": max_new_tokens}
data = {
"model": self.model,
"messages": prompt_input,
"options": options,
"stream": False,
}
_request = {
"url": f"{self.api_url}",
"json": data,
}
response = requests.post(**_request) # type: ignore
if response.status_code != 200:
raise Exception(f"Ollama API Error: {response.status_code}, {response.text}")
response_json = response.json()
return response_json["message"]["content"]
class GeminiEngine(Engine):
def __init__(self, **kwargs) -> None:
"""
Init a Gemini engine
To use this engine, please provide the GEMINI_API_KEY in the environment
Supported Model Rate Limit
gemini-1.5-pro-latest 2 queries per minute, 1000 queries per day
"""
super().__init__(**kwargs)
def generate(self, prompt: list = None, max_new_tokens=4096, temperature=None, model=None, image_path=None,
ouput_0=None, turn_number=0, **kwargs):
self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots)
start_time = time.time()
if (
self.request_interval > 0
and start_time < self.next_avil_time[self.current_key_idx]
):
wait_time = self.next_avil_time[self.current_key_idx] - start_time
print(f"Wait {wait_time} for rate limitting")
prompt0, prompt1, prompt2 = prompt
litellm.set_verbose=True
base64_image = encode_image(image_path)
if turn_number == 0:
# Assume one turn dialogue
prompt_input = [
{"role": "system", "content": prompt0},
{"role": "user",
"content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url": image_path,
"detail": "high"},
}]},
]
elif turn_number == 1:
prompt_input = [
{"role": "system", "content": prompt0},
{"role": "user",
"content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url": image_path,
"detail": "high"},
}]},
{"role": "assistant", "content": [{"type": "text", "text": f"\n\n{ouput_0}"}]},
{"role": "user", "content": [{"type": "text", "text": prompt2}]},
]
response = litellm.completion(
model=model if model else self.model,
messages=prompt_input,
max_tokens=max_new_tokens if max_new_tokens else 4096,
temperature=temperature if temperature else self.temperature,
**kwargs,
)
return [choice["message"]["content"] for choice in response.choices][0]
class OpenAIEngine(Engine):
def __init__(self, **kwargs) -> None:
"""
Init an OpenAI GPT/Codex engine
To find your OpenAI API key, visit https://platform.openai.com/api-keys
"""
super().__init__(**kwargs)
@backoff.on_exception(
backoff.expo,
(APIError, RateLimitError, APIConnectionError),
)
def generate(self, prompt: list = None, max_new_tokens=4096, temperature=None, model=None, image_path=None,
ouput_0=None, turn_number=0, **kwargs):
self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots)
start_time = time.time()
if (
self.request_interval > 0
and start_time < self.next_avil_time[self.current_key_idx]
):
time.sleep(self.next_avil_time[self.current_key_idx] - start_time)
prompt0, prompt1, prompt2 = prompt
# litellm.set_verbose=True
base64_image = encode_image(image_path)
if turn_number == 0:
# Assume one turn dialogue
prompt_input = [
{"role": "system", "content": [{"type": "text", "text": prompt0}]},
{"role": "user",
"content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url":
f"data:image/jpeg;base64,{base64_image}",
"detail": "high"},
}]},
]
elif turn_number == 1:
prompt_input = [
{"role": "system", "content": [{"type": "text", "text": prompt0}]},
{"role": "user",
"content": [{"type": "text", "text": prompt1}, {"type": "image_url", "image_url": {"url":
f"data:image/jpeg;base64,{base64_image}",
"detail": "high"}, }]},
{"role": "assistant", "content": [{"type": "text", "text": f"\n\n{ouput_0}"}]},
{"role": "user", "content": [{"type": "text", "text": prompt2}]},
]
response = litellm.completion(
model=model if model else self.model,
messages=prompt_input,
max_tokens=max_new_tokens if max_new_tokens else 4096,
temperature=temperature if temperature else self.temperature,
**kwargs,
)
return [choice["message"]["content"] for choice in response.choices][0]
class OpenaiEngine_MindAct(Engine):
def __init__(self, **kwargs) -> None:
"""Init an OpenAI GPT/Codex engine
Args:
api_key (_type_, optional): Auth key from OpenAI. Defaults to None.
stop (list, optional): Tokens indicate stop of sequence. Defaults to ["\n"].
rate_limit (int, optional): Max number of requests per minute. Defaults to -1.
model (_type_, optional): Model family. Defaults to None.
"""
super().__init__(**kwargs)
#
@backoff.on_exception(
backoff.expo,
(APIError, RateLimitError, APIConnectionError),
)
def generate(self, prompt, max_new_tokens=50, temperature=0, model=None, **kwargs):
self.current_key_idx = (self.current_key_idx + 1) % len(self.time_slots)
start_time = time.time()
if (
self.request_interval > 0
and start_time < self.next_avil_time[self.current_key_idx]
):
time.sleep(self.next_avil_time[self.current_key_idx] - start_time)
if isinstance(prompt, str):
# Assume one turn dialogue
prompt = [
{"role": "user", "content": prompt},
]
response = litellm.completion(
model=model if model else self.model,
messages=prompt,
max_tokens=max_new_tokens,
temperature=temperature,
**kwargs,
)
if self.request_interval > 0:
self.next_avil_time[self.current_key_idx] = (
max(start_time, self.next_avil_time[self.current_key_idx])
+ self.request_interval
)
return [choice["message"]["content"] for choice in response["choices"]]
|