# 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.

{% code lineNumbers="true" %}

```typescript
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 };
};
```

{% endcode %}

**`applyCosts`**

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

{% code lineNumbers="true" %}

```typescript
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 };
};
```

{% endcode %}

**`runNaturalFunction`**

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

{% code lineNumbers="true" %}

```typescript
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 });
    }
};
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://documentation.skynet.io/skynet/build-your-project-on-skynet/integrate-ai-agent-tools/core-functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
