Skynet
Visit SkynetBlogUse-casesDiscord
  • Getting Started
    • Introduction to Skynet
    • Why Skynet?
    • Features
      • Skynet Intelligence
      • Skynet Orchestration
      • Data Security
      • Memory
      • Skynet Chain
      • Payments
      • AI Tools
    • Skynet Interoperability
  • Agent Studio
    • Studio Overview
    • Dashboard
    • Workflow
  • Skynet Ecosystem
  • Skynet Protocol
    • SkyIDs
    • Role Based Access Control (RBAC)
    • Organizational Services
    • Add AI Agent tools
    • Payment Rails
      • Fiat/Crypto On-ramp
      • Settlement With Tooling Providers
      • Subscriptions vs on-demand Pay-per-second
      • How AI Agents Spend
    • Subnet
      • Types of Subnet
      • Subnet fault-tolerance and security
      • Provider Subnet
      • Provider Subnet functions
      • Tool fees
    • Smart Access Points
  • FAQ
  • Tutorials
  • Concepts
    • Glossary
  • Technical Support
  • Build your Project on Skynet
    • Interact with AI service to create an Agent
      • Prerequisites
      • SDK Initialization
      • Adding Balance to a Subnet
        • Best Practices
        • Common Errors and Solutions
      • Authentication
      • userAuthPayload
      • Service Endpoints
    • Integrate AI agent tools
      • Installation
      • Configuration
      • Initialization and Setup
      • Core Functions
      • Endpoint Summary
  • Developer Portal
Powered by GitBook
On this page
  1. Build your Project on Skynet
  2. Integrate AI agent tools

Core Functions

Here’s an overview of the main functions required for initAIAccessPoint:

checkBalanceCondition

This function halts any active services associated with a given NFT ID. It identifies ongoing services and attempts to stop them, helping manage resources effectively.

import { NFTCosts } from '@decloudlabs/Skynet-SmartAccessPoint /lib/types/types';
import { APICallReturn } from '@decloudlabs/sky-cluster-operator/lib/types/types';
import { stopService } from './clients/runpod'; // Assuming `stopService` stops a specific service

const checkBalanceCondition = async (nftCosts: NFTCosts): Promise<APICallReturn<boolean>> => {
    console.log(`Checking running services for NFT ID: ${nftCosts.nftID}`);
    
    const runningServices = await getRunningServices(nftCosts.nftID); // Implement `getRunningServices` to fetch services

    const stoppedServices = [];
    for (const service of runningServices) {
        try {
            console.log(`Stopping service: ${service.id}`);
            const result = await stopService(service.id);
            if (result.success) {
                stoppedServices.push(service.id);
            } else {
                console.error(`Failed to stop service ${service.id}:`, result.error);
            }
        } catch (err) {
            console.error(`Error stopping service ${service.id}:`, err);
        }
    }

    console.log(`Stopped services: ${stoppedServices}`);
    return { success: true, data: true };
};

applyCosts

Calculates and applies the usage costs based on request parameters, which helps manage the user’s balance effectively.

import { NFTCosts } from '@decloudlabs/Skynet-SmartAccessPoint /lib/types/types';
import { ethers } from 'ethers';

const applyCosts = async (nftCosts: NFTCosts): Promise<APICallReturn<NFTCosts>> => {
    const additionalCost = ethers.BigNumber.from("10000000000000000"); // Cost in wei
    const updatedCosts = {
        ...nftCosts,
        costs: ethers.BigNumber.from(nftCosts.costs).add(additionalCost).toString()
    };
    
    return { success: true, data: updatedCosts };
};

runNaturalFunction

Processes natural language requests, interprets parameters with OpenAI, and executes operations based on the extracted information.

import { Request, Response } from 'express';
import OpenAI from 'openai';
import BalanceRunMain from '@decloudlabs/Skynet-SmartAccessPoint /lib/balanceRunMain';

const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
});

const runNaturalFunction = async (req: Request, res: Response, runMain: BalanceRunMain): Promise<void> => {
    try {
        const { prompt, nftId } = req.body;

        const completion = await openai.chat.completions.create({
            messages: [
                {
                    role: "system",
                    content: "Extract necessary parameters for requested operations and return as JSON."
                },
                { role: "user", content: prompt }
            ],
            model: "gpt-3.5-turbo",
            response_format: { type: "json_object" },
        });

        const params = JSON.parse(completion.choices[0].message.content || '{}');

        if (params.question) {
            res.send({ question: params.question });
            return;
        }

        // Perform the operation based on extracted `params.action`
        const response = await /* logic to execute action, e.g., create, start, stop */;
        res.json(response);
    } catch (error: any) {
        res.status(400).json({ error: error.message });
    }
};
PreviousInitialization and SetupNextEndpoint Summary

Last updated 5 months ago