DEV Community

Derlys
Derlys

Posted on

Cómo empezar a utilizar herramientas de IA en Solana

Esta guía va acompañada de un
vídeo tutorial.

Parte 1: Desarrollo asistido por IA con Solana MCP (Machine Conversation Protocol)


Uso de herramientas de IA con Solana MCP


Una de las formas más potentes de aprovechar la IA para el desarrollo de Solana es a través del Solana Developer MCP (Machine Conversation Protocol). Esta integración lleva el conocimiento especializado de Solana directamente a
tu IDE, lo que hace que tus agentes estén más al día sobre la documentación actualizada de Solana. Esto hace que el desarrollo de Solana sea más rápido y eficiente.

¿Qué es Solana MCP?

Solana MCP (Machine Conversation Protocol) es un asistente de IA especializado que se integra directamente en entornos de desarrollo integrados (IDE) compatibles con IA, como Cursor y Windsurf. Cuando haces preguntas específicas sobre Solana, consulta automáticamente el servidor MCP para proporcionar información precisa y actualizada. La herramienta MCP está entrenada con recursos exhaustivos de Solana, entre los que se incluyen:

Ejemplos de casos de uso

Puedes utilizar MCP para:

  • Preguntar sobre conceptos de Solana
  • Depurar errores de programación
  • Obtener recomendaciones sobre buenas prácticas
  • Aprender de ejemplos de expertos
  • O simplemente desarrollar más rápido con la ayuda de un experto

Configuración de Solana MCP

Encuentra una guía detallada de configuración y primeros pasos en la página web de Solana MCP.

Parte 2: Trabajar con LLM y agentes en Solana

Antes de profundizar en herramientas específicas, veamos los componentes clave de la pila de desarrollo de IA:

  1. Modelos de lenguaje a gran escala (LLM)

    • Los modelos de IA fundamentales (como GPT-4, Claude o Llama)
    • Procesan y generan lenguaje natural
    • Proporcionan inteligencia básica y capacidades de razonamiento
    • Ejemplos: GPT-4 de OpenAI, Claude de Anthropic, Llama de Meta
  2. Marcos de agentes (como Eliza)

    • Construidos sobre los LLM para crear agentes autónomos
    • Gestionan las personalidades y los comportamientos de los agentes
    • Manejan la memoria y el contexto
    • Proporcionan integración multiplataforma
    • Ejemplos: Eliza, LangChain, AutoGPT, Vercel AI
  3. Kits de agentes específicos para cada dominio (como Solana Agent Kit)

  • Diseñados para casos de uso específicos (por ejemplo, operaciones de blockchain)
  • Proporcionan herramientas e integraciones pre configuradas
  • Abstraen la complejidad técnica
  • Funciones de blockchain listas para usar
  • Ejemplos: Solana Agent Kit, GOAT Toolkit

Piénsalo de esta manera:

  • Los modelos de lenguaje grande (LLM) son el «cerebro» capaz de comprender y generar lenguaje.
  • Los marcos de agentes son el «sistema operativo» que gestiona el comportamiento de la IA.
  • Los kits específicos de dominio son las «aplicaciones» que dotan a la IA de capacidades concretas.

Creación de agentes de IA para Solana

Esta guía te mostrará cómo:

  • Crear un agente de IA básico utilizando el kit de agentes de Solana de SendAI
  • Crear un bot de Twitter con el marco Eliza
  • Comprender las opciones de integración de IA en cadena
  • Opciones para crear bots de trading avanzados

Introducción a los agentes de IA en Solana

Los agentes de IA en Solana son programas autónomos capaces de interactuar con la cadena de bloques mediante el procesamiento del lenguaje natural y el aprendizaje automático. Pueden:

  • Ejecutar transacciones
  • Supervisar la actividad de la cadena de bloques
  • Interactuar con contratos inteligentes
  • Proporcionar asistencia al usuario
  • Automatizar flujos de trabajo complejos

Marcos disponibles

Existen varios marcos disponibles para crear agentes de IA en Solana:

  1. Kit de agente de Solana de SendAI
  • Una colección de herramientas para crear agentes en Solana.
  • Compatible con Eliza, Langchain y el SDK de IA de Vercel.
  • Herramientas y utilidades de Solana integradas
  • Capacidades de procesamiento del lenguaje natural
  • Kit de agentes de Solana
  • [Documentación](https://docs.solanaa
  1. Eliza Framework
  • Combina la capa de datos, el modelo de lenguaje grande (LLM) y los agentes, y cuenta con un complemento específico para Solana
  • Arquitectura de agentes extensible
  • Fácil integración con proyectos existentes y se puede utilizar, por ejemplo, para bots de Twitter (X), Telegram o Discord
  • Repositorio de GitHub
  1. GOAT Toolkit
  1. Rig Framework
  • Implementación nativa en Rust
  • Ideal para bots de trading de alto rendimiento
  • Se puede combinar con el kit de herramientas Listen.rs para la integración con Solana, la supervisión de transacciones y el envío de transacciones utilizando, por ejemplo, paquetes Jito
  • Repositorio de GitHub
  • Repositorio de Listen.rs

Si estás desarrollando un marco de IA, no dudes en enviar una solicitud de incorporación de cambios para añadir tu marco a la lista.

Primeros pasos con SendAI

Empecemos por configurar un agente de IA básico utilizando el Solana Agent Kit de SendAI, que
puede realizar acciones en la cadena de bloques de Solana y con el que podemos chatear:

Instalar las dependencias

Para esta guía se recomienda utilizar un IDE moderno. En este ejemplo utilizaremos Cursor, que cuenta con funciones de IA integradas y puede ayudarte a resolver cualquier error que te puedas encontrar.

Deberás tener instalado node en su versión
23.x.x. Abre una carpeta vacía con VSCode o Cursor y ejecuta el siguiente comando en el terminal:


Esta guía requiere la versión 23.x.x de Node.js. Instálala con nvm:

node --version  # Comprobar la versión actual
nvm install 23  # Instalar Node.js 23 si es necesario
nvm use 23      # Cambiar a Node.js 23
Enter fullscreen mode Exit fullscreen mode
pnpm install solana-agent-kit
pnpm add@langchain/core@langchain/openai@langchain/langgraphv  bs58
Enter fullscreen mode Exit fullscreen mode

Tu IDE debería crear el archivo package.json automáticamente. Si no es así, este es el aspecto
que debería tener:

```json filename=package.json
{
"dependencies": {
"@langchain/core": "^0.3.33",
"@langchain/langgraph": "^0.2.41",
"@langchain/openai": "^0.3.17",
"bs58": "^6.0.0",
"dotenv": "^16.4.7",
"solana-agent-kit": "^1.4.3"
}
}




</Step>

<Step>
### Configurar el entorno

Crea un archivo `.env` en el directorio raíz del proyecto y añade lo siguiente:



```ini
OPENAI_API_KEY=your_openai_api_key
RPC_URL=https://api.devnet.solana.com
SOLANA_PRIVATE_KEY=your_private_key
Enter fullscreen mode Exit fullscreen mode

Ten en cuenta que codificamos la clave privada en base58 antes de pasarla al constructor del agente de Solana en el script, por lo que aquí, en el archivo de entorno, basta con introducir la matriz de bytes [34,2,34...]

Puedes crear una clave con el siguiente comando:

solana-keygen grind --starts-with ai:1
Enter fullscreen mode Exit fullscreen mode

Y copia el contenido en tu archivo .env en la entrada SOLANA_PRIVATE_KEY.

La clave OPENAI_API_KEY es la clave de la API de OpenAI y la puedes encontrar en la
plataforma de OpenAI

Por ahora, dejamos la URL de RPC en devnet.

Crear el script del agente

Crea un nuevo archivo llamado agent.ts con el siguiente contenido:

```typescript filename=agent.ts
import { SolanaAgentKit, createSolanaTools } from "solana-agent-kit";
import { HumanMessage } from "@langchain/core/messages";
import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { MemorySaver } from "@langchain/langgraph";
import * as dotenv from "dotenv";
import bs58 from "bs58";
import * as readline from "readline";

dotenv.config();

async function initializeAgent() {
const llm = new ChatOpenAI({
modelName: "gpt-4-turbo-preview",
temperature: 0.7
});

// Convert array string to actual array, then to Uint8Array, then to base58
const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY!);
const privateKeyUint8 = new Uint8Array(privateKeyArray);
const privateKeyBase58 = bs58.encode(privateKeyUint8);

const solanaKit = new SolanaAgentKit(privateKeyBase58, process.env.RPC_URL!, {
OPENAI_API_KEY: process.env.OPENAI_API_KEY!
});

const tools = createSolanaTools(solanaKit);
const memory = new MemorySaver();

return createReactAgent({
llm,
tools,
checkpointSaver: memory
});
}

async function runInteractiveChat() {
const agent = await initializeAgent();
const config = { configurable: { thread_id: "Solana Agent Kit!" } };
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

// Clear console and start chat with a small delay
setTimeout(() => {
console.clear(); // Clear any initialization messages
console.log("Chat with Solana Agent (type 'exit' to quit)");
console.log("--------------------------------------------");
askQuestion();
}, 100);

const askQuestion = () => {
rl.question("You: ", async (input) => {
if (input.toLowerCase() === "exit") {
rl.close();
return;
}

  const stream = await agent.stream(
    {
      messages: [new HumanMessage(input)]
    },
    config
  );

  process.stdout.write("Agent: ");
  for await (const chunk of stream) {
    if ("agent" in chunk) {
      process.stdout.write(chunk.agent.messages[0].content);
    } else if ("tools" in chunk) {
      process.stdout.write(chunk.tools.messages[0].content);
    }
  }
  console.log("\n--------------------------------------------");

  askQuestion(); // Continue the conversation
});
Enter fullscreen mode Exit fullscreen mode

};
}

runInteractiveChat().catch(console.error);




</Step>

<Step>
### Ejecutar el agente

Puedes ejecutar este script con el siguiente comando:



```bash
npx tsx agent.ts
Enter fullscreen mode Exit fullscreen mode

Esto iniciará una conversación sencilla con el agente.

Probar las funciones básicas

Ahora puedes pedirle que te muestre tu saldo de Solana y que solicite algo de Solana de la red de desarrollo:

Puedes decirselo en Ingles

Please show me my wallet address and request some devnet sol
Enter fullscreen mode Exit fullscreen mode

o español 😉

Por favor, muéstrame la dirección de mi monedero y solicita un poco de SOL de la red de desarrollo.
Enter fullscreen mode Exit fullscreen mode

Si el grifo de devnet está vacío, puedes utilizar en su lugar el grifo web y pegar tu dirección de Solana.

Crear una colección de NFT

A continuación, pregúntale al agente:

Por favor, crea una colección NFT llamada «trains» con el símbolo TRN utilizando esta URL: https://scarlet-fancy-minnow-617.mypinata.cloud/ipfs/bafkreif43sp62yuy3sznrvqesk23tfnhpdck4npqowdwrhrzhsrgf5ao2e
Enter fullscreen mode Exit fullscreen mode

Acuñar un NFT

Una vez creada la colección, acuña un NFT:

Por favor, acuña un NFT para mí en esa colección con el nombre: Train1 y utilizando este URI: https://scarlet-fancy-minnow-617.mypinata.cloud/ipfs/bafkreif43sp62yuy3sznrvqesk23tfnhpdck4npqowdwrhrzhsrgf5ao2e
Enter fullscreen mode Exit fullscreen mode

Esto generará un NFT con el nombre «Train1» y la imagen de un tren.

También puedes utilizar cualquier otro metadato para tu NFT, que puedes subir a través de
pinata o cualquier otro proveedor de almacenamiento. El resultado debería ser algo como esto[devnet train nft(https://explorer.solana.com/address/6dTVGn2M8LdAB6vrxzt7X8fm8HiP1QxN9j8jeh1dbyv8?cluster=devnet)

¿Y ahora qué?

  • Ahora puedes, por ejemplo, importar la clave privada a la cartera de tu extensión de navegador para ver el NFT.
  • Puedes pedirle al agente que te muestre todos tus NFT. Verás que aparece un error al realizar esta acción. Esto se debe a que la acción predeterminada para solicitar activos utiliza la API de Helius Asset, por lo que para ello tendrás que añadir una clave API de Helius a tu archivo .env y pasarla al agente.

```ts filename=agent.ts
const solanaKit = new SolanaAgentKit(privateKeyBase58, process.env.RPC_URL!, {
OPENAI_API_KEY: process.env.OPENAI_API_KEY!,
HELIUS_API_KEY: process.env.HELIUS_API_KEY!
});




- Ahora puedes empezar a escribir tus propias acciones siguiendo la [Guía de contribución](https://github.com/sendaifun/solana-agent-kit/blob/main/CONTRIBUTING.md)

También hay un[ejemplo de chat web(https://github.com/sendaifun/solana-agent-kit/tree/main/examples/agent-kit-nextjs-langchain)
para tu agente que utiliza React y que puedes, por ejemplo, implementar en Vercel.

Todavía no todas las acciones funcionan al 100 %, como por ejemplo la solicitud de saldo,que a veces falla, pero puedes ver los avances en el [repositorio del kit de agente de Solana(https://github.com/sendaifun/solana-agent-kit) y también contribuir con tus propias acciones para que las utilicen todos.

## Building with Eliza Framework

The [ElizaOS](https://github.com/elizaOS/eliza) (formerly known as Ai16z) is an
AI framework. That means it combines multiple applications into one and
organizes their interactions. It combines:

1. Different LLMs to understand the user
2. Blockchain agents with different actions (like minting an NFT for example)
3. Datalayers to store the characters state between actions using for example
   Redis, PostgreSQL DB or local storage
4. Different clients like X, telegram, discord. etc.

Its takes all these things and puts them together in a way that you can create a
"Character" that can interact with users or autonomously. These Characters are
defined in a JSON file, which defines which actions it can perform, which LLM it
should use and different prompts that define the behaviour of the character.

### Building a Twitter (X) bot that can mint NFTs on request

What we will build now is a helpful solana developer assistant that can help
developers on the platform X to get started with solana and it will also be able
to mint NFTs to the users on demand.

<Steps>

### Clone the repository

First clone the Eliza repository:



```bash
git clone https://github.com/elizaOS/eliza.git
Enter fullscreen mode Exit fullscreen mode

Set up the environment


This guide requires Node.js version 23.x.x. Install it using nvm:

node --version  # Check current version
nvm install 23  # Install Node.js 23 if needed
nvm use 23      # Switch to Node.js 23
Enter fullscreen mode Exit fullscreen mode

Then install the dependencies:

pnpm install --no-frozen-lockfile
pnpm build
Enter fullscreen mode Exit fullscreen mode

Configure environment variables

Create your environment file:

cp .env.example .env
Enter fullscreen mode Exit fullscreen mode

What we are interested in for this guide is:

TWITTER_USERNAME=               # Account username
TWITTER_PASSWORD=               # Account password
TWITTER_EMAIL=
OPENAI_API_KEY=                 # Get this from: https://platform.openai.com/api-keys
SOLANA_RPC_URL=https://api.devnet.solana.com # Lets work on devnet for now
SOLANA_PRIVATE_KEY=             # Get this from: https://solana.com/wallet
SOLANA_PUBLIC_KEY=
SOLANA_CLUSTER=devnet # Default: devnet. Solana Cluster: 'devnet' | 'testnet' | 'mainnet-beta'
SOLANA_ADMIN_PRIVATE_KEY=       # This wallet is used to verify NFTs (you can use the same as the SOLANA_PRIVATE_KEY for now)
SOLANA_ADMIN_PUBLIC_KEY=        # This wallet is used to verify NFTs (you can use the same as the SOLANA_PUBLIC_KEY for now)
Enter fullscreen mode Exit fullscreen mode

Make sure you have some
devnet sol
in your wallet before you start the agent.

Encode private key (if needed)

If you have your private key in hex format you can base58 encode your private
key using the following js snippet:

```ts filename=encode58.ts
const bs58 = require('bs58');
console.log(bs58.encode(new Uint8Array([213,29,143,...])));




And run it using



```bash
npx tsx encode58.ts
Enter fullscreen mode Exit fullscreen mode

Create character configuration

To create a new character we need to create a character.json file. You can find
the preset characters in the characters folder of the Eliza project. To create a
new character you can copy and change one of the already existing characters or
you can use the
composer feature in Cursor and tell
it what kind of character you want to create.

```json filename=characters/sol.character.json
{
"name": "Sol",
"clients": ["twitter"],
"modelProvider": "openai",
"settings": {
"voice": {
"model": "en_US-neural"
},
...




The important part here are the clients and the modelProvider. In our case we
want to use twitter as a client and openai as the model provider because this is
what we also set our secrets for in the `.env` file.

### Run the agent

Now that the configuration is done we can run our character:



```bash
pnpm start --character="characters/sol.character.json"
Enter fullscreen mode Exit fullscreen mode

This will start the agent and you can now interact with it on twitter. The
character will automatically start posting tweets every few hours and when we
interact with him it will be able to perform solana actions like minting NFTs
for example.

Here you can see the
character in action.

You can also interact with the character locally using the following command:
You may need to free your port 3000 and start your character with the --host
flag.

pnpm start --character="characters/sol.character.json" --host
pnpm start:client
Enter fullscreen mode Exit fullscreen mode

If your client does not connect make sure you run your agent with the --host
flag and that your port 3000 is not in use when you start the client.

For more information follow the
official eliza documentation

Disclaimer: The Solana integration and actions are not perfect yet but they are
in constant development and are moving fast. There will be a direct integration
of the SendAI agent kit into Eliza soon.

Using GOAT Toolkit

GOAT is similar to Solana Agent Kit a
collection of many different blockchain tools that also supports different
Solana actions and other chains. It can also be integrated into the Eliza
framework for example and supports many different wallets, frameworks and block
chains. This
example
shows you how you can use Crossmint directly in
Windsurf code editor to buy Items on Amazon.
There is also a
demo video available.

On chain program agent integration

If you want to use an agents reply within a solana program you need to use an
oracle that writes the reply data into an account that your program can read.
You can find an example of an LLM which will transfer tokens to any user that
answers questions correctly here:

On chain program LLM interaction

This is an example of an onchain program that integrates with an LLM (AI) oracle
to create an interactive token-dispensing agent named "Mar1o".

Key Features

  1. AI Agent Interaction

    • Users can chat with Mar1o to try to earn tokens
    • Agent evaluates user's Solana knowledge to decide token amounts
    • Responses are in JSON format with reply text and token amount
  2. Token Management

    • Creates MAR1O tokens with metadata
    • Can mint between 0-10,000 tokens based on AI response
    • Uses PDAs for token management

Program flow explained

Here's how this program works:

// Initialize the AI agent with personality
const AGENT_DESC: &str = "You are an AI agent called Mar1o which can dispense MAR1O tokens...";

// User interaction flow:
// 1. User sends message to agent
// 2. Oracle processes with LLM
// 3. Agent responds with JSON containing reply and amount
// 4. If amount > 0, tokens are minted to user

// Example response:
{
    "reply": "Great answer! Here's a reward.",
    "amount": 1000
}
Enter fullscreen mode Exit fullscreen mode

This demonstrates how to combine AI capabilities with onchain token mechanics to
create interactive blockchain experiences. Here is a
live example where you can try to convince the Agent to
transfer you some tokens.

Advanced Rust agents for algorithmic trading

If you want to write your agents in Rust you can use the
Rig framework and the
Listen.rs library.

These two work nicely together. While the Rig framework gives you an easy way to
connect to LLMs the Listen.rs toolkit provides you the Solana integration
including Transaction monitoring and sending transactions using Jito bundles for
example.

Best Practices

  • Know that your agent has a private key and thus can access the funds in your wallet. If someone can chat with your agent and it has a transfer action for example users can probably get it to transfer them your funds.
  • Use a paid RPC endpoints. The public endpoints usually get rate limited
  • Monitor agent activities and make sure they are not doing anything malicious or get tricked into it by users interacting with them
  • Implement priority fees and transaction retries to your agent actions so that they also land when there is congestion on the network
  • If possible test on devnet first before you deploy to mainnet. Most agents just take the RPC url as an input and you can use a devnet one until your are ready for mainnet. Not all actions maybe possible to do on devnet though.
  • When writing your own actions add integration tests for them so that the frameworks can monitor which actions are failing due to changed programs or APIs

Conclusion

AI agents on Solana open up new possibilities for automation and interaction
with the blockchain. While not all integrations are perfect yet they are
developed fast and offer lots of opportunity for contributions and are very
flexible of adding your own integrations.

Top comments (0)