July 16, 2024

GaiaNet. Устанавливаем ноду

CryptoFortochka — гайды, ноды, новости, тестнеты

GaiaNet — это децентрализованная сеть, предлагающая безопасные, устойчивые к цензуре и монетизируемые ИИ-агенты

  • Инвестировали: $10 000 000
  • Инвесторы: Mirana Ventures, Mantle, ByteTrade и другие
  • Арендовать сервер: Xorek, Aeza
  • Характеристики: 4CPU/8RAM/200GB
  • Операционная система: Ubuntu 20.04+
  • Использованные порты: 8080
  • Чат и канал с поддержкой: https://t.me/fortochat / https://t.me/cryptoforto
  • Лучшие прокси: Nodemaven, Proxy-Seller

Более полугода назад мы фармили поинты через ноду, где нужно было взаимодействовать с AI-ботом. Ваши заработанные поинты зависели от частоты общения с этим ботом

И вот недавно проект запустил программу фарма поинтов именно через покупку их доменов, но фармить можно и без них (эта активность идёт уже довольно давно). В гайде вы найдете два варианта запуска ноды — без и с покупкой домена

Под данную ноду подойдет сервера от Aeza и Xorek. Но, некоторые сервера на Хорьке могут не работать

Таймкоды для вашего удобства:

Подходящий сервер можно арендовать на Xorek за $7.31 в месяц + докупить к нему дополнительно 80GiB памяти — и общая стоимость сервера у вас выйдет $9.66 в месяц

Базовые активности. Детальный гайд

  • Переходим по ссылке и коннектим кошелёк EVM
  • Выполняем все социальные задания и получает GaiaPoints
  • Далее нам нужно их конвертировать в поинты GaiaCredits

Установка ноды без домена. Детальный гайд

  • Подключаемся на арендованный сервер через root
  • Выполняем команды по списку
  • Убиваем все процессы на порту 8080
sudo fuser -k 8080/tcp
  • Обновляем систему и устанавливаем необходимые элементы
sudo apt update
sudo apt upgrade -y
sudo apt install -y python3-pip python3-dev python3-venv curl git build-essential
  • Устанавливаем aiohttp и другие зависимости для Python
 pip3 install aiohttp
  • Устанавливаем gaianet и другие зависимости
curl -sSfL 'https://github.com/GaiaNet-AI/gaianet-node/releases/latest/download/install.sh' | bash
source ~/.bashrc
  • Устанавливаем tmux
 apt install tmux
  • Инициализируем ноду с конфигурацией выбранной модели
gaianet init --config https://raw.githubusercontent.com/GaiaNet-AI/node-configs/main/qwen2-0.5b-instruct/config.json  
  • Запускаем ноду
gaianet start  

В результате запуска ноды нам дадут ссылку для общения с нодой. Копируем ее и сохраняем себе.

Регистрация ноды

  • Далее нужно зарегистрировать ноду, для этого переходим по этой ссылке, подключаем свой кошелек и нажимаем на кнопку “CONNECT NEW NODE
  • Вводим данную команду и копируем Node id и Device id
gaianet info
  • Полученные данные вставляем на сайте, нажимаем кнопку “Join” и подписываем транзакцию в кошельке
  • Если всё сделали правильно, то напротив подключенной ноды будет зеленый кружок

Создание и запуск скрипта для автообщения

  • Создаем файл phrases.txt с фразами, которые будут использованы в чате. Копируем фразы ниже и вставляем в наш файл
 nano phrases.txt 
"Explain Einstein's theory of general relativity with mathematical proofs and real-world applications."
"Describe quantum mechanics and its implications for modern technology."
"How does machine learning differ from traditional programming? Provide examples."
"What are the key challenges in building a decentralized autonomous organization (DAO)?"
"Explain the process of photosynthesis in detail, including the chemical reactions involved."
"How do blockchain consensus mechanisms like Proof-of-Work and Proof-of-Stake differ?"
"What are the primary components of a neural network, and how do they interact?"
"Describe the history and evolution of the Internet, including key milestones."
"How does data encryption work, and what are the most secure algorithms available?"
"What are the applications of Fourier transforms in signal processing and image compression?"
"Explain the concept of entropy in thermodynamics with examples."
"What are the ethical implications of artificial intelligence in healthcare?"
"How do you implement a distributed system for real-time data processing?"
"Describe the differences between TCP and UDP protocols."
"What are the key differences between SQL and NoSQL databases?"
"How does genetic engineering work, and what are its implications for society?"
"Explain the difference between classical and quantum computing with examples."
"What are the challenges in creating an AI that can pass the Turing test?"
"How does GPS technology work, and what are its limitations?"
"What are the main challenges in developing fusion power plants?"
"Describe the history of the Roman Empire in detail, including its rise and fall."
"How did the industrial revolution impact global society and economies?"
"What are the key philosophical differences between existentialism and nihilism?"
"Explain the causes and consequences of World War II in detail."
"What was the significance of the Renaissance period in European history?"
"Describe the history of ancient Egypt, including its cultural and political achievements."
"What are the main ethical principles in utilitarianism and deontology?"
"Explain the philosophy of Immanuel Kant and its influence on modern thought."
"How did the Cold War shape the political landscape of the 20th century?"
"What are the origins and evolution of human rights as a concept?"
"Write a detailed tutorial on how to create a blockchain from scratch in Python."
"How does garbage collection work in modern programming languages?"
"Explain the differences between functional and object-oriented programming."
"What are the key principles of RESTful API design?"
"How do you implement a graph traversal algorithm in Python?"
"What are the best practices for securing a web application?"
"How do neural networks use backpropagation for training?"
"Describe the key differences between Docker and Kubernetes."
"What is the role of cryptography in securing blockchain networks?"
"How do you design a scalable microservices architecture?"

Вставляем туда текст фраз и сохраните файл кнопками CTRL+X затем Y и Enter

  • Создаём файл roles.txt с ролями
nano roles.txt   
system
user
assistant
tool

Вставляем туда текст ролей и сохраните файл кнопками CTRL+X затем Y и Enter

  • Создаём скрипт gaia_bot.py
nano gaia_bot.py  

Вставляем в него код скрипта и заменяем на адрес своей ноды (Node ID) в строке URL на тот, который вы сохранили после запуска.

import aiohttp
import asyncio
import random

# URL API
url = "https://АДРЕС_ВАШЕЙ_НОДЫ.gaia.domains/v1/chat/completions"

# Заголовки запроса
headers = {
    "accept": "application/json",
    "Content-Type": "application/json"
}

# Функция для чтения ролей и фраз из файлов
def load_from_file(file_name):
    with open(file_name, "r") as file:
        return [line.strip() for line in file.readlines()]

# Загрузка ролей и фраз
roles = load_from_file("roles.txt")
phrases = load_from_file("phrases.txt")

# Генерация случайного сообщения
def generate_random_message():
    role = random.choice(roles)
    content = random.choice(phrases)
    return {"role": role, "content": content}

# Создание сообщения
def create_message():
    """Создаёт сообщение, гарантируя, что одно из них имеет роль 'user'."""
    user_message = generate_random_message()
    user_message["role"] = "user"  # Гарантируем, что хотя бы одно сообщение — от 'user'
    other_message = generate_random_message()
    return [user_message, other_message]

# Отправка запроса к API
async def chat_loop():
    async with aiohttp.ClientSession() as session:
        while True:
            messages = create_message()
            user_message = next((msg["content"] for msg in messages if msg["role"] == "user"), "No user message found")
            
            # Логируем отправленный вопрос
            print(f"Отправлен вопрос: {user_message}")
            
            data = {"messages": messages}

            try:
                async with session.post(url, json=data, headers=headers, timeout=60) as response:
                    if response.status == 200:
                        result = await response.json()
                        assistant_response = result["choices"][0]["message"]["content"]
                        print(f"Получен ответ: {assistant_response}\n{'-'*50}")
                    else:
                        print(f"Ошибка: {response.status} - {await response.text()}")
            except asyncio.TimeoutError:
                print("Тайм-аут ожидания. Отправляю следующий запрос...")
            except Exception as e:
                print(f"Ошибка: {e}")

            # Небольшая задержка перед отправкой следующего сообщения
            await asyncio.sleep(1)

if __name__ == "__main__":
    asyncio.run(chat_loop())

Сохраняем файл кнопками CTRL+X затем Y и Enter

  • Запускаем сессию tmux и бота
tmux new -s gaia
 python3 gaia_bot.py 

После запуска бот сразу начнет отправлять вопросы и писать их в лог.

Выйти из сесии Tmux, что бы бот работал в фоне - CTRL+B, а затем D

  • Что бы позже вернуться в сессию, введите команду
tmux attach -t gaia

Теперь у вас есть настроенный сервер с нодой, который будет использовать выбранную модель для общения с API и автоматически генерировать вопросы на основе фраз из файла.

Установка ноды c доменом. Детальный гайд

Для работы нод через персональный домен необходимы GaiaCredits.

Способы получения GaiaCredits:

  • Бесплатно – 500 GaiaCredits раз в день.
  • Покупка домена и имени – позволяет получить увеличенное количество GaiaCredits сразу.

Механика бонусов за домен:

  • В зависимости от стоимости домена предоставляется дополнительный бонус на фарм поинтов.
  • Чем выше цена домена, тем больше поинтов можно зарабатывать через него.

Покупка и настройка домена для работы с нодами

  • Перейдите на сайт Gaia Domain Name, прокрутите немного вниз и выберите домен, который хотите приобрести
  • Введите код R936WX для получения скидки
  • Далее регистрируем имя, после покупки домена оно будет со 100% скидкой
  • После покупки перейдите в раздел управления активами и дождитесь, пока ваше имя появится в списке.
  • Настройка домена:
    • Нажмите кнопку Launch Domain.
    • Введите название, описание и загрузите фото.
    • Нажмите Next Step.
    • Выберите имя и подтвердите выбор.
    • Выберите единственного доступного провайдера и нажмите Далее.
    • Переключайтесь между шагами, пока домен не станет доступным.
  • Выбор модели
    • В разделе 6 выберите Automation и модель Qwen1.5-0.5B-ChatQ5_K_M.
    • Подтвердите все настройки.
  • Домен зарегистрирован и готов к использованию.

Установка ноды

  • Подключаемся на арендованный сервер через root
  • Выполняем команды по списку
  • Убиваем все процессы на порту 8080
sudo fuser -k 8080/tcp
  • Обновляем систему и устанавливаем необходимые элементы
sudo apt update
sudo apt upgrade -y
sudo apt install -y python3-pip python3-dev python3-venv curl git build-essential
  • Устанавливаем aiohttp и другие зависимости для Python
 pip3 install aiohttp
  • Устанавливаем gaianet и другие зависимости
curl -sSfL 'https://github.com/GaiaNet-AI/gaianet-node/releases/latest/download/install.sh' | bash
source ~/.bashrc
  • Устанавливаем tmux
 apt install tmux
  • Инициализируем ноду с конфигурацией выбранной модели
gaianet init --config https://raw.gaianet.ai/qwen-1.5-0.5b-chat/config.json
  • Запускаем ноду
gaianet start  

В результате запуска ноды нам дадут ссылку для общения с нодой. Копируем ее и сохраняем себе.

Регистрация ноды

  • Далее нужно зарегистрировать ноду, для этого переходим по этой ссылке, подключаем свой кошелек и нажимаем на кнопку “CONNECT NEW NODE
  • Вводим данную команду и копируем Node id и Device id
gaianet info
  • Полученные данные вставляем на сайте, нажимаем кнопку “Join” и подписываем транзакцию в кошельке
  • Если всё сделали правильно, то напротив подключенной ноды будет зеленый кружок
  • Найдите свою ноду в списке
  • Нажмите Join Domain, чтобы подключить её к зарегистрированному домену. Найдите в поиске свой домен и подключитесь

Создание и запуск скрипта для автообщения

  • Создание API-ключа
  • Добавление API-ключа в переменные окружения
    • Откройте терминал на сервере.
    • Добавьте API-ключ в переменную окружения
export GAIA_API_KEY="вставьте_свой_ключ"
  • Сделайте переменную постоянной (чтобы она не исчезала после перезапуска сервера)
echo 'export GAIA_API_KEY="ваш_апи_ключ"' >> ~/.bashrc
source ~/.bashrc
  • Создаем файл phrases.txt с фразами, которые будут использованы в чате. Копируем фразы ниже и вставляем в наш файл
 nano phrases.txt 
"Explain Einstein's theory of general relativity with mathematical proofs and real-world applications."
"Describe quantum mechanics and its implications for modern technology."
"How does machine learning differ from traditional programming? Provide examples."
"What are the key challenges in building a decentralized autonomous organization (DAO)?"
"Explain the process of photosynthesis in detail, including the chemical reactions involved."
"How do blockchain consensus mechanisms like Proof-of-Work and Proof-of-Stake differ?"
"What are the primary components of a neural network, and how do they interact?"
"Describe the history and evolution of the Internet, including key milestones."
"How does data encryption work, and what are the most secure algorithms available?"
"What are the applications of Fourier transforms in signal processing and image compression?"
"Explain the concept of entropy in thermodynamics with examples."
"What are the ethical implications of artificial intelligence in healthcare?"
"How do you implement a distributed system for real-time data processing?"
"Describe the differences between TCP and UDP protocols."
"What are the key differences between SQL and NoSQL databases?"
"How does genetic engineering work, and what are its implications for society?"
"Explain the difference between classical and quantum computing with examples."
"What are the challenges in creating an AI that can pass the Turing test?"
"How does GPS technology work, and what are its limitations?"
"What are the main challenges in developing fusion power plants?"
"Describe the history of the Roman Empire in detail, including its rise and fall."
"How did the industrial revolution impact global society and economies?"
"What are the key philosophical differences between existentialism and nihilism?"
"Explain the causes and consequences of World War II in detail."
"What was the significance of the Renaissance period in European history?"
"Describe the history of ancient Egypt, including its cultural and political achievements."
"What are the main ethical principles in utilitarianism and deontology?"
"Explain the philosophy of Immanuel Kant and its influence on modern thought."
"How did the Cold War shape the political landscape of the 20th century?"
"What are the origins and evolution of human rights as a concept?"
"Write a detailed tutorial on how to create a blockchain from scratch in Python."
"How does garbage collection work in modern programming languages?"
"Explain the differences between functional and object-oriented programming."
"What are the key principles of RESTful API design?"
"How do you implement a graph traversal algorithm in Python?"
"What are the best practices for securing a web application?"
"How do neural networks use backpropagation for training?"
"Describe the key differences between Docker and Kubernetes."
"What is the role of cryptography in securing blockchain networks?"
"How do you design a scalable microservices architecture?"

Вставляем туда текст фраз и сохраните файл кнопками CTRL+X затем Y и Enter

  • Создаём файл roles.txt с ролями
nano roles.txt   
system
user
assistant

Вставляем туда текст ролей и сохраните файл кнопками CTRL+X затем Y и Enter

  • Создаём скрипт gaia_bot.py
nano gaia_bot.py  

Вставляем в него код скрипта и заменяем на название вашего домена

import aiohttp
import asyncio
import random
import os

# URL API Gaia
API_URL = "https://ВАШЕ_НАЗВАНИЕ_ДОМЕНА.gaia.domains/v1/chat/completions"
GAIA_API_KEY = os.getenv("GAIA_API_KEY")

# Заголовки запроса
HEADERS = {
    "Authorization": f"Bearer {GAIA_API_KEY}",
    "Accept": "application/json",
    "Content-Type": "application/json"
}

# Функция для чтения фраз и ролей из файлов
def load_from_file(file_name):
    with open(file_name, "r") as file:
        return [line.strip() for line in file.readlines()]

# Загрузка ролей и фраз
roles = load_from_file("roles.txt")
phrases = load_from_file("phrases.txt")

# Генерация случайного сообщения
def generate_random_message():
    role = random.choice(roles)
    content = random.choice(phrases)
    return {"role": role, "content": content}

# Создание сообщения
def create_message():
    user_message = generate_random_message()
    user_message["role"] = "user"
    other_message = generate_random_message()
    return [user_message, other_message]

# Функция для одного потока общения с API
async def chat_worker(worker_id):
    async with aiohttp.ClientSession() as session:
        while True:
            messages = create_message()
            user_message = next((msg["content"] for msg in messages if msg["role"] == "user"), "No user message found")
            print(f"[Worker {worker_id}] Отправлен вопрос: {user_message}")

            data = {"messages": messages}
            try:
                async with session.post(API_URL, json=data, headers=HEADERS, timeout=300) as response:
                    if response.status == 200:
                        result = await response.json()
                        assistant_response = result["choices"][0]["message"]["content"]
                        print(f"[Worker {worker_id}] Получен ответ: {assistant_response}\n{'-'*50}")
                    else:
                        print(f"[Worker {worker_id}] Ошибка: {response.status} {await response.text()}")
            except asyncio.TimeoutError:
                print(f"[Worker {worker_id}] Тайм-аут ожидания. Отправляю следующий запрос...")
            except Exception as e:
                print(f"[Worker {worker_id}] Ошибка: {e}")

            await asyncio.sleep(3)

# Главная функция: запускает несколько потоков
async def main(num_workers):
    tasks = [chat_worker(i) for i in range(num_workers)]
    await asyncio.gather(*tasks)

# Запрос количества потоков у пользователя
if __name__ == "__main__":
    while True:
        try:
            num_threads = int(input("Введите количество потоков (сколько нод подключено): ").strip())
            if num_threads > 0:
                break
            else:
                print("Число потоков должно быть больше 0!")
        except ValueError:
            print("Ошибка! Введите число.")

    print(f"Запускаем {num_threads} потоков...")
    asyncio.run(main(num_threads))

Сохраняем файл кнопками CTRL+X затем Y и Enter

  • Запускаем бота и указываем количество потоков (равное количеству подключенных нод)
tmux new -s gaia
 python3 gaia_bot.py 

После этого бот будет автоматически отправлять запросы на ваш домен, балансируя нагрузку между подключенными нодами.

Выйти из сессии Tmux, что бы бот работал в фоне — CTRL+B, а затем D

  • Что бы позже вернуться в сессию, введите команду
tmux attach -t gaia

Бот работает, пока не закончатся API-запросы.

Если GaiaCredits заканчиваются, бот автоматически прекращает работу.

Если вы будете подключать много нод, то бота нужно запускать только на одном сервере и указать количество потоков (нод) при запуске.

Данная статья была написана каналом Crypto Fortochka