Advertisement
Ewgeniy

ai-_oc

Jan 27th, 2025 (edited)
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 5.11 KB | None | 0 0
  1. local internet = require("internet")
  2. local json = require("json")
  3. local tty = require("tty")
  4. local component = require("component")
  5. local computer = require("computer")
  6. local unicode = require("unicode")  -- Используем встроенный Unicode API
  7.  
  8. tty.clear()
  9. print("API ключ:")
  10. local api = io.read()
  11. tty.clear()
  12. print("Добро пожаловать в ИИ-чат!\n")
  13. print("Введите сообщение (или 'exit' для выхода):") -- Печатаем один раз в начале
  14.  
  15. -- URL и заголовки
  16. local url = "https://api.mistral.ai/v1/chat/completions"
  17. local headers = {
  18.   Authorization = "Bearer " .. api,
  19.   ["Content-Type"] = "application/json"
  20. }
  21.  
  22. -- URL для перевода Google Translate API
  23. local translate_url = "https://translate.googleapis.com/translate_a/single"
  24.  
  25. -- Функция для URL-кодирования строки
  26. function urlencode(str)
  27.    if (str) then
  28.       str = string.gsub(str, "\n", "\r\n")
  29.       str = string.gsub(str, "([^%w ])", function(c)
  30.          return string.format("%%%02X", string.byte(c))
  31.       end)
  32.       str = string.gsub(str, " ", "+")
  33.    end
  34.    return str    
  35. end
  36.  
  37. -- Функция перевода текста через Google Translate
  38. function translate(text, target_lang)
  39.   local url = translate_url .. "?client=gtx&sl=auto&tl=" .. target_lang .. "&dt=t&q=" .. urlencode(text)
  40.   local response, err = internet.request(url)
  41.  
  42.   if response then
  43.     local body = ""
  44.     for chunk in response do body = body .. chunk end
  45.     local success, decoded = pcall(json.decode, body)
  46.  
  47.     if success and decoded and decoded[1] then
  48.       local translated_text = ""
  49.       for _, sentence in ipairs(decoded[1]) do
  50.         if sentence[1] then
  51.           translated_text = translated_text .. sentence[1]
  52.         end
  53.       end
  54.       return translated_text  -- Возвращаем весь переведённый текст
  55.     else
  56.       print("Ошибка при декодировании перевода.")
  57.     end
  58.   else
  59.     print("Ошибка при отправке запроса для перевода.")
  60.   end
  61.  
  62.   return text  -- Если ошибка, возвращаем оригинальный текст
  63. end
  64.  
  65. -- Функция для посимвольного вывода текста с поддержкой Unicode
  66. function print_slowly(text, delay)
  67.   delay = delay or 0.01  -- Задержка между символами (по умолчанию 0.05 секунды)
  68.  
  69.   -- Итерируем по символам Unicode
  70.   for i = 1, unicode.len(text) do
  71.     local char = unicode.sub(text, i, i)  -- Получаем текущий символ
  72.     io.write(char)  -- Выводим символ
  73.     io.flush()  -- Очищаем буфер вывода, чтобы символы появлялись сразу
  74.     computer.pullSignal(delay)  -- Задержка
  75.   end
  76.   print()  -- Переход на новую строку после завершения
  77. end
  78.  
  79. -- История сообщений для контекста
  80. local messages = {
  81.   { content = "You're an assistant who can help with different things, in different industries.", role = "system" }
  82. }
  83.  
  84. -- Основной цикл чата
  85. while true do
  86.   io.write("\nВы: ")  -- Меняем на "Вы: "
  87.   local message = io.read()
  88.  
  89.   if message == "exit" then
  90.     print("Чат завершён.")
  91.     break
  92.   end
  93.  
  94.   -- Перевод сообщения пользователя на английский
  95.   local translated_message = translate(message, "en")
  96.   table.insert(messages, { content = translated_message, role = "user" })
  97.  
  98.   -- Данные для POST-запроса
  99.   local data = {
  100.     messages = messages,
  101.     model = "mistral-large-latest"
  102.   }
  103.  
  104.   -- Преобразуем данные в JSON
  105.   local jsonData = json.encode(data)
  106.  
  107.   -- Отправляем запрос в Mistral AI
  108.   local response, err = internet.request(url, jsonData, headers)
  109.  
  110.   -- Обрабатываем ответ
  111.   if response then
  112.     local body = ""
  113.     for chunk in response do
  114.       body = body .. chunk
  115.     end
  116.  
  117.     -- Декодируем JSON-ответ
  118.     local success, decodedResponse = pcall(json.decode, body)
  119.  
  120.     if success and decodedResponse and decodedResponse.choices and decodedResponse.choices[1] then
  121.       local ai_reply = decodedResponse.choices[1].message.content
  122.  
  123.       -- Переводим ответ ИИ обратно на русский
  124.       local translated_reply = translate(ai_reply, "ru")
  125.  
  126.       -- Выводим ответ посимвольно
  127.       io.write("\nИИ: ")
  128.       print_slowly(translated_reply)
  129.  
  130.       -- Добавляем ответ ИИ в историю сообщений
  131.       table.insert(messages, { content = ai_reply, role = "assistant" })
  132.     else
  133.       print("\nОшибка: сервер не вернул корректный ответ.")
  134.       print("Ответ сервера:\n" .. body)
  135.     end
  136.   else
  137.     -- Если произошла ошибка
  138.     print("\nОшибка при отправке запроса:", err)
  139.   end
  140. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement