API documentation yuntian-deng/ChatGPT API Recorder 5 API endpoints Choose a language to…
- User
API documentation yuntian-deng/ChatGPT
API Recorder
5 API endpoints
Choose a language to see the code snippets for interacting with the API.
- Install the python client (docs) if you don't already have it installed.
copy $ pip install gradio_client 2. Find the API endpoint below corresponding to your desired function in the app. Copy the code snippet, replacing the placeholder values with your own input data. If this is a private Space, you may need to pass your Hugging Face token as well (read more). Or use the API Recorder
to automatically generate your API requests.
api_name: /enable_inputs copy from gradio_client import Client
client = Client("yuntian-deng/ChatGPT") result = client.predict( api_name="/enable_inputs" ) print(result) Accepts 0 parameters: Returns 1 element api_name: /reset_textbox copy from gradio_client import Client
client = Client("yuntian-deng/ChatGPT") result = client.predict( api_name="/reset_textbox" ) print(result) Accepts 0 parameters: Returns 1 element str
The output value that appears in the "Type an input and press Enter" Textbox component.
api_name: /predict copy from gradio_client import Client
client = Client("yuntian-deng/ChatGPT") 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(str, Any), props: dict(str, Any)) | None, str | dict(file: filepath, alt_text: str | None) | dict(component: str, value: Any, constructor_args: dict(str, Any), props: dict(str, Any)) | None] Default: []
The input value that is provided in the "parameter_4" Chatbot component. null
Returns tuple of 4 elements [0] tuple[str | dict(file: filepath, alt_text: str | None) | dict(component: str, value: Any, constructor_args: dict(str, Any), props: dict(str, Any)) | None, str | dict(file: filepath, alt_text: str | None) | dict(component: str, value: Any, constructor_args: dict(str, Any), props: dict(str, Any)) | 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.
- Assistant
Конечно! Ниже пример простой системы общения с ИИ на Python, использующей API
yuntian-deng/ChatGPTчерезgradio_client. В ней реализовано запоминание истории диалога (чатбота), то есть при каждом запросе история передаётся на сервер, и ответ ИИ формируется с учётом предыдущих сообщений. - User
chat_counter = len(chat_history) // 2 # количество пар сообщений
а зачем делить если в списке типа [ ("hello","hi") ("remember 23", "ok") ]
- Assistant
Отличный вопрос!
В данном случае
chat_history— это список пар (tuple) вида(user_message, bot_reply), например:[ ("hello", "hi"), ("remember 23", "ok"), ]То есть каждый элемент списка — уже полноценная пара "пользователь — бот". Значит, количество пар сообщений и так равно длине списка.
Поэтому вычисление
chat_counter = len(chat_history) // 2лишнее и неправильно, потому что вы заведомо делите количество пар на 2, получая половину нужного значения.
Верное вычисление просто:
chat_counter = len(chat_history)Потому что
len(chat_history)— количество уже существующих пар сообщений.
Итог:
chat_counter = len(chat_history)Именно так, без деления, нужно передавать количество пар сообщений, чтобы API правильно понимал текущий контекст диалога.
- User
null в python
- Assistant
В Python значение, эквивалентное
nullиз других языков (например, JavaScript или JSON), — этоNone.Вот примеры использования:
x = None if x is None: print("x имеет значение None") else: print("x не None")None— это специальный литерал, который обозначает отсутствие значения.- Для проверки используют оператор
isилиis not(не==). - В контексте API или JSON
nullобычно конвертируется в Python какNone.
Если нужно, могу помочь конвертировать JSON с
nullв Python объекты сNoneи обратно. - User
print("\033[31mНе удалось распознать речь\033[0m")
цвета
- Assistant
Ваш код использует ANSI escape sequences для показа текста в цвете в терминале.
Конкретно:
print("\033[31mНе удалось распознать речь\033[0m")\033[— последовательность начала escape-кода.31m— цвет текста красный.- Текст
"Не удалось распознать речь"выводится красным. \033[0m— сброс всех атрибутов, чтобы вернуть текст к обычному формату.
Основные цвета текста по ANSI:
Код Цвет 30 Черный 31 Красный 32