Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local internet = require("internet")
- local json = require("json")
- local tty = require("tty")
- local component = require("component")
- local computer = require("computer")
- local unicode = require("unicode") -- Используем встроенный Unicode API
- tty.clear()
- print("API ключ:")
- local api = io.read()
- tty.clear()
- print("Добро пожаловать в ИИ-чат!\n")
- print("Введите сообщение (или 'exit' для выхода):") -- Печатаем один раз в начале
- -- URL и заголовки
- local url = "https://api.mistral.ai/v1/chat/completions"
- local headers = {
- Authorization = "Bearer " .. api,
- ["Content-Type"] = "application/json"
- }
- -- URL для перевода Google Translate API
- local translate_url = "https://translate.googleapis.com/translate_a/single"
- -- Функция для URL-кодирования строки
- function urlencode(str)
- if (str) then
- str = string.gsub(str, "\n", "\r\n")
- str = string.gsub(str, "([^%w ])", function(c)
- return string.format("%%%02X", string.byte(c))
- end)
- str = string.gsub(str, " ", "+")
- end
- return str
- end
- -- Функция перевода текста через Google Translate
- function translate(text, target_lang)
- local url = translate_url .. "?client=gtx&sl=auto&tl=" .. target_lang .. "&dt=t&q=" .. urlencode(text)
- local response, err = internet.request(url)
- if response then
- local body = ""
- for chunk in response do body = body .. chunk end
- local success, decoded = pcall(json.decode, body)
- if success and decoded and decoded[1] then
- local translated_text = ""
- for _, sentence in ipairs(decoded[1]) do
- if sentence[1] then
- translated_text = translated_text .. sentence[1]
- end
- end
- return translated_text -- Возвращаем весь переведённый текст
- else
- print("Ошибка при декодировании перевода.")
- end
- else
- print("Ошибка при отправке запроса для перевода.")
- end
- return text -- Если ошибка, возвращаем оригинальный текст
- end
- -- Функция для посимвольного вывода текста с поддержкой Unicode
- function print_slowly(text, delay)
- delay = delay or 0.01 -- Задержка между символами (по умолчанию 0.05 секунды)
- -- Итерируем по символам Unicode
- for i = 1, unicode.len(text) do
- local char = unicode.sub(text, i, i) -- Получаем текущий символ
- io.write(char) -- Выводим символ
- io.flush() -- Очищаем буфер вывода, чтобы символы появлялись сразу
- computer.pullSignal(delay) -- Задержка
- end
- print() -- Переход на новую строку после завершения
- end
- -- История сообщений для контекста
- local messages = {
- { content = "You're an assistant who can help with different things, in different industries.", role = "system" }
- }
- -- Основной цикл чата
- while true do
- io.write("\nВы: ") -- Меняем на "Вы: "
- local message = io.read()
- if message == "exit" then
- print("Чат завершён.")
- break
- end
- -- Перевод сообщения пользователя на английский
- local translated_message = translate(message, "en")
- table.insert(messages, { content = translated_message, role = "user" })
- -- Данные для POST-запроса
- local data = {
- messages = messages,
- model = "mistral-large-latest"
- }
- -- Преобразуем данные в JSON
- local jsonData = json.encode(data)
- -- Отправляем запрос в Mistral AI
- local response, err = internet.request(url, jsonData, headers)
- -- Обрабатываем ответ
- if response then
- local body = ""
- for chunk in response do
- body = body .. chunk
- end
- -- Декодируем JSON-ответ
- local success, decodedResponse = pcall(json.decode, body)
- if success and decodedResponse and decodedResponse.choices and decodedResponse.choices[1] then
- local ai_reply = decodedResponse.choices[1].message.content
- -- Переводим ответ ИИ обратно на русский
- local translated_reply = translate(ai_reply, "ru")
- -- Выводим ответ посимвольно
- io.write("\nИИ: ")
- print_slowly(translated_reply)
- -- Добавляем ответ ИИ в историю сообщений
- table.insert(messages, { content = ai_reply, role = "assistant" })
- else
- print("\nОшибка: сервер не вернул корректный ответ.")
- print("Ответ сервера:\n" .. body)
- end
- else
- -- Если произошла ошибка
- print("\nОшибка при отправке запроса:", err)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement