Перепиши этот код под использование данной апи [code] main.py [code]
- User
Перепиши этот код под использование данной апи
api_name: /predict copy from gradio_client import Client client = Client("yuntian-deng/o1") result = client.predict( inputs="Hello!!", top_p=1, temperature=1, chat_counter=0, chatbot=[], api_name="/predict" ) print(result) Accepts 5 parameters: inputs str Required The input value that is provided in the "Type an input and press Enter" Textbox component. top_p float Default: 1 The input value that is provided in the "Top-p (nucleus sampling)" Slider component. temperature float Default: 1 The input value that is provided in the "Temperature" Slider component. chat_counter float Default: 0 The input value that is provided in the "parameter_16" Number component. chatbot Tuple[str | Dict(file: filepath, alt_text: str | None) | Dict(component: str, value: Any, constructor_args: Dict(), props: Dict()) | None, str | Dict(file: filepath, alt_text: str | None) | Dict(component: str, value: Any, constructor_args: Dict(), props: Dict()) | None] Default: [] The input value that is provided in the "parameter_4" Chatbot component. Returns tuple of 4 elements [0] Tuple[str | Dict(file: filepath, alt_text: str | None) | Dict(component: str, value: Any, constructor_args: Dict(), props: Dict()) | None, str | Dict(file: filepath, alt_text: str | None) | Dict(component: str, value: Any, constructor_args: Dict(), props: Dict()) | None] The output value that appears in the "value_4" Chatbot component. [1] float The output value that appears in the "value_16" Number component. [2] str The output value that appears in the "Status code from OpenAI server" Textbox component. [3] str The output value that appears in the "Type an input and press Enter" Textbox component.main.py
import gradio as gr import os import sys import json import copy import requests import random import timeout_decorator from tenacity import retry, wait_fixed, stop_after_attempt MODEL = "o1-preview" API_URL = os.getenv("API_URL") DISABLED = os.getenv("DISABLED") == 'True' OPENAI_API_KEYS = os.getenv("OPENAI_API_KEYS").split(',') print (API_URL) print (OPENAI_API_KEYS) NUM_THREADS = int(os.getenv("NUM_THREADS")) print (NUM_THREADS) #@timeout_decorator.timeout(120) @retry(stop=stop_after_attempt(5), wait=wait_fixed(2)) def call_openai_api(payload, headers): response = requests.post(API_URL, headers=headers, json=payload, stream=True) response.raise_for_status() return response def exception_handler(exception_type, exception, traceback): print("%s: %s" % (exception_type.__name__, exception)) sys.excepthook = exception_handler sys.tracebacklimit = 0 def predict(inputs, top_p, temperature, chat_counter, chatbot, history, request:gr.Request): orig_history = copy.deepcopy(history) orig_chat_counter = chat_counter payload = { "model": MODEL, "messages": [{"role": "user", "content": f"{inputs}"}], "temperature" : 1.0, "top_p":1.0, "n" : 1, "stream": True, "presence_penalty":0, "frequency_penalty":0, } OPENAI_API_KEY = random.choice(OPENAI_API_KEYS) print (OPENAI_API_KEY) headers_dict = {key.decode('utf-8'): value.decode('utf-8') for key, value in request.headers.raw} headers = { "Content-Type": "application/json", "Authorization": f"Bearer {OPENAI_API_KEY}", "Headers": f"{headers_dict}" } # print(f"chat_counter - {chat_counter}") if chat_counter != 0 : messages = [] for i, data in enumerate(history): if i % 2 == 0: role = 'user' else: role = 'assistant' message = {} message["role"] = role message["content"] = data messages.append(message) message = {} message["role"] = "user" message["content"] = inputs messages.append(message) payload = { "model": MODEL, "messages": messages, "temperature" : temperature, "top_p": top_p, "n" : 1, "stream": True, "presence_penalty":0, "frequency_penalty":0, } chat_counter += 1 history.append(inputs) token_counter = 0 partial_words = "" counter = 0 try: # make a POST request to the API endpoint using the requests.post method, passing in stream=True response = call_openai_api(payload, headers) #requests.post(API_URL, headers=headers, json=payload, stream=True) response_code = f"{response}" #if response_code.strip() != "<Response [200]>": # #print(f"response code - {response}") # raise Exception(f"Sorry, hitting rate limit. Please try again later. {response}") for chunk in response.iter_lines(): #print (chunk) #sys.stdout.flush() #Skipping first chunk if counter == 0: counter += 1 continue #counter+=1 # check whether each line is non-empty if chunk.decode() : chunk = chunk.decode() # decode each line as response data is in bytes if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']: partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"] if token_counter == 0: history.append(" " + partial_words) else: history[-1] = partial_words token_counter += 1 yield [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=False), gr.update(interactive=False) # resembles {chatbot: chat, state: history} except Exception as e: print (f'error found: {e}') return [(orig_history[i], orig_history[i + 1]) for i in range(0, len(orig_history) - 1, 2) ], orig_history, orig_chat_counter, 'Error! Please try again', gr.update(interactive=True), gr.update(interactive=True) yield [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=True), gr.update(interactive=True) print(json.dumps({"chat_counter": chat_counter, "payload": payload, "partial_words": partial_words, "token_counter": token_counter, "counter": counter})) def reset_textbox(): return gr.update(value='', interactive=False), gr.update(interactive=False) title = """<h1 align="center">OpenAI-O1-Preview: Research Preview (Short-Term Availability)</h1>""" if DISABLED: title = """<h1 align="center" style="color:red">This app has reached OpenAI's usage limit. Please check back tomorrow.</h1>""" description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form: - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.