# Data Connectors

#### Overview

In CYNE AI, **Providers** are designed to:

* Supply **real-time data** and **contextual insights**.
* Integrate seamlessly with the **AgentRuntime** framework.
* Format information for conversational templates, actions, and evaluations.
* Ensure consistent access to Solana blockchain and other decentralized data.

***

#### Core Structure

A Provider in CYNE AI adheres to the following interface structure:

```typescript
interface Provider {
    get: (
        runtime: IAgentRuntime,
        message: Memory,
        state?: State
    ) => Promise<string>;
}
```

Providers interact with the agent runtime, message memory, and optional agent state to fetch and process relevant data for users.

***

#### Built-in Providers in CYNE AI

**1. Time Provider**

The **Time Provider** adds temporal context to interactions, ensuring time-sensitive blockchain operations and market trends are accurately conveyed.

```typescript
const timeProvider: Provider = {
    get: async (_runtime: IAgentRuntime, _message: Memory) => {
        const currentDate = new Date();
        const currentTime = currentDate.toLocaleTimeString("en-US");
        const currentDateString = currentDate.toDateString();
        return `Current date and time: ${currentDateString}, ${currentTime}`;
    },
};
```

***

**2. Market Data Provider**

The **Market Data Provider** retrieves real-time token prices, trading volumes, and liquidity statistics from decentralized exchanges.

```typescript
const marketDataProvider: Provider = {
    get: async (runtime: IAgentRuntime, message: Memory) => {
        const token = message.content.text; // Extract token name or symbol
        const marketData = await runtime.getMarketData(token); // Custom runtime function
        return `The current price of ${token} is ${marketData.price} SOL with a trading volume of ${marketData.volume}.`;
    },
};
```

***

**3. Wallet Insights Provider**

The **Wallet Insights Provider** allows users to monitor their wallet balances and transaction histories.

```typescript
const walletInsightsProvider: Provider = {
    get: async (runtime: IAgentRuntime, message: Memory, state?: State) => {
        const walletAddress = state?.userWalletAddress || message.content.text;
        const walletData = await runtime.getWalletData(walletAddress);
        return `Wallet ${walletAddress} has a balance of ${walletData.balance} SOL and holds ${walletData.tokenHoldings.length} tokens.`;
    },
};
```

***

**4. Risk Analysis Provider**

The **Risk Analysis Provider** evaluates potential risks in smart contracts, liquidity pools, or token investments.

```typescript
const riskAnalysisProvider: Provider = {
    get: async (runtime: IAgentRuntime, message: Memory) => {
        const contractAddress = message.content.text;
        const riskScore = await runtime.analyzeRisk(contractAddress);
        return `The contract at ${contractAddress} has a risk score of ${riskScore}, indicating ${riskScore > 70 ? "high risk" : "low risk"}.`;
    },
};
```

***

**5. Whale Tracking Provider**

The **Whale Tracking Provider** monitors large transactions or whale activities on the Solana blockchain, alerting users to significant market movements.

```typescript
runtime.registerContextProvider(marketDataProvider);
```

**Accessing Providers in Runtime**

Providers can be utilized during state composition:

```typescript
const state = await runtime.composeState(message);
```

***

#### Comprehensive Provider Example

This example demonstrates integrating multiple data sources into a single provider for a holistic response:

```typescript
const comprehensiveProvider: Provider = {
    get: async (runtime: IAgentRuntime, message: Memory, state?: State) => {
        try {
            const messages = await runtime.messageManager.getMemories({
                roomId: message.roomId,
                count: 5,
            });

            const walletData = await runtime.getWalletData(state?.userWalletAddress);

            const facts = await runtime.messageManager.getMemories({
                roomId: message.roomId,
                tableName: "facts",
                count: 3,
            });

            return `
# Recent Messages
${messages.map((m) => `- ${m.content.text}`).join("\n")}

# Wallet Information
Balance: ${walletData.balance} SOL
Tokens: ${walletData.tokenHoldings.length}

# Relevant Facts
${facts.map((f) => `- ${f.content.text}`).join("\n")}
            `.trim();
        } catch (error) {
            console.error("Provider error:", error);
            return "Unable to fetch context at the moment.";
        }
    },
};
```

***

#### Troubleshooting

**Stale Data**

* Implement cache invalidation for outdated data:

```typescript
const invalidateCache = async (pattern: string) => {
    const keys = await cache.keys(pattern);
    await Promise.all(keys.map((key) => cache.del(key)));
};
```

**Rate Limiting**

* Use exponential backoff for retries:

```typescript
const backoff = async (attempt: number) => {
    const delay = Math.min(1000 * Math.pow(2, attempt), 10000);
    await new Promise((resolve) => setTimeout(resolve, delay));
};
```

**API Failures**

* Fallback to secondary data sources when primary APIs fail.

***

#### Further Reading

* Agent Runtime Documentation
* Memory System Documentation
* Custom Actions Documentation

With **CYNE AI**, providers bring the power of real-time data and blockchain insights to intelligent, autonomous agents. Start creating your own providers today!


---

# 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://docs.cyne.ai/core-concept/data-connectors.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.
