> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Build onchain AI agents

> Build AI agents that hold a wallet and transact on Solana with Solana Agent Kit, Eliza, GOAT, LangChain, and Rust trading agents.

This page is about building AI agents that hold their own wallet and send
transactions onchain. To use a coding assistant such as Cursor or Claude Code to
write Solana code, see
[Build with AI agents](/developers/docs/intro/coding-with-agents) instead. A
[video walkthrough](https://www.youtube.com/watch?v=O6tKgtYQZDY) accompanies
this page.

## Working with LLMs and Agents on Solana

Before diving into specific tools, let's understand the key components in the AI
development stack:

## Understanding the AI Stack

1. **Large Language Models (LLMs)**
   - The foundational AI models (like GPT-4, Claude, or Llama)
   - Process and generate natural language
   - Provide raw intelligence and reasoning capabilities
   - Examples: OpenAI's GPT-4, Anthropic's Claude, Meta's Llama

2. **Agent Frameworks (like Eliza)**
   - Built on top of LLMs to create autonomous agents
   - Manage agent personalities and behaviors
   - Handle memory and context
   - Provide multi-platform integration
   - Examples: Eliza, LangChain, AutoGPT, Vercel AI

3. **Domain-Specific Agent Kits (like Solana Agent Kit)**
   - Built for specific use cases (e.g., onchain operations)
   - Provide pre-built tools and integrations
   - Abstract away technical complexity
   - Ready-to-use onchain actions
   - Examples: Solana Agent Kit, GOAT Toolkit

Think of it like this:

- LLMs are the "brain" that can understand and generate language
- Agent frameworks are the "operating system" that manages the AI's behavior
- Domain-specific kits are the "apps" that give the AI specific capabilities

## Building AI Agents for Solana

This guide will show you how to:

- Build a basic AI agent using SendAI's Solana Agent Kit
- Create a Twitter bot with Eliza Framework
- Understand onchain AI integration options
- Options on how to build advanced trading bots

## Introduction to AI Agents on Solana

AI agents on Solana are autonomous programs that can interact with
Solana using natural language processing and machine learning. They can:

- Execute transactions
- Monitor onchain activity
- Interact with smart contracts
- Provide user assistance
- Automate complex workflows

## Available Frameworks

Several frameworks are available for building AI agents on Solana:

1. **SendAI's Solana Agent Kit**

- A collection of tools for building agents on Solana
- Compatible with Eliza, Langchain, and Vercel AI SDK
- Built-in Solana tools and utilities
- Natural language processing capabilities
- [Solana Agent Kit](https://github.com/sendaifun/solana-agent-kit)
- [Documentation](https://docs.sendai.fun/)

2. **Eliza Framework**

- Combines datalayer, llm, and agents and has a dedicated Solana plugin
- Extensible agent architecture
- Easy integration with existing projects and can be used for example for
  Twitter (X), telegram, or discord bots
- [GitHub Repository](https://github.com/elizaOS/eliza)

3. **GOAT Toolkit**

- Comprehensive development toolkit
- Cross-chain compatibility
- [GitHub Repository](https://github.com/goat-sdk/goat)

4. **Rig Framework**

- Native Rust implementation
- Good for high performance trading bots
- Can be combined with the Listen.rs toolkit for Solana integration transaction
  monitoring and sending transactions using Jito bundles for example
- [GitHub Repository](https://github.com/0xPlaygrounds/rig)
- [Listen.rs Repository](https://github.com/piotrostr/listen)

If you are building an AI framework feel free to open a PR to add your framework
to the list

## Getting Started with SendAI

Let's start by setting up a basic AI agent using SendAI's Solana Agent Kit that
can perform actions on Solana and that we can chat with:

<Steps titleSize="h3">
<Step title="Install dependencies">
A modern IDE is recommended for this guide. We will use
[Cursor](https://www.cursor.com/) for this example which has integrated AI
features and can help you with any errors you may encounter.

You need [Node.js](https://nodejs.org/en/download/) 22 or later, the minimum
`solana-agent-kit` declares in its `engines` field. Open an empty folder using
VS Code or Cursor and run the following command in the terminal:

<Warning>
  This guide requires Node.js 22 or later. Install it using [nvm](https://github.com/nvm-sh/nvm):

```shell
node --version  # Check current version
nvm install 22  # Install Node.js 22 if needed
nvm use 22      # Switch to Node.js 22
```

</Warning>

```bash
npm install solana-agent-kit @solana-agent-kit/plugin-token @solana-agent-kit/plugin-nft @solana/web3.js@1 dotenv
npm install @langchain/core@0.3 @langchain/openai@0.5 @langchain/langgraph@0.2
```

Solana Agent Kit 2.x adds its actions through plugins (`plugin-token`,
`plugin-nft`, and others) and is built against `@langchain/core` 0.3, so the
LangChain packages are pinned to matching versions.

`@solana-agent-kit/plugin-nft` 2.0.7 pins its own copy of `solana-agent-kit`
2.0.8, while the rest of the project uses 2.0.10. The two copies make
`.use(NFTPlugin)` fail type-checking. Add an npm override so every package
shares the root version, then reinstall:

```bash
npm pkg set 'overrides.solana-agent-kit=$solana-agent-kit'
npm install
```

Your `package.json` should look like this:

```json package.json
{
  "dependencies": {
    "@langchain/core": "^0.3.80",
    "@langchain/langgraph": "^0.2.74",
    "@langchain/openai": "^0.5.18",
    "@solana-agent-kit/plugin-nft": "^2.0.7",
    "@solana-agent-kit/plugin-token": "^2.0.9",
    "@solana/web3.js": "^1.99.0",
    "dotenv": "^18.0.8",
    "solana-agent-kit": "^2.0.10"
  },
  "overrides": {
    "solana-agent-kit": "$solana-agent-kit"
  }
}
```

</Step>

<Step title="Configure environment">
Create a `.env` file in the root of the project and add the following:

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

`SOLANA_PRIVATE_KEY` is the secret key as a JSON byte array, for example
`[34,2,34,...]`. The script turns it into a keypair.

You can create a key using the following command:

```bash
solana-keygen grind --starts-with ai:1
```

And copy the contents into your `.env` file for `SOLANA_PRIVATE_KEY`.

The OPENAI_API_KEY is the key for the OpenAI API and you can find it in the
[OpenAI platform](https://platform.openai.com/api-keys)

The RPC url we just leave at devnet for now.

</Step>

<Step title="Create the agent script">
Create a new file called `agent.ts` with the following content:

```typescript agent.ts
import {
  SolanaAgentKit,
  KeypairWallet,
  createLangchainTools
} from "solana-agent-kit";
import TokenPlugin from "@solana-agent-kit/plugin-token";
import NFTPlugin from "@solana-agent-kit/plugin-nft";
import { Keypair } from "@solana/web3.js";
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 * as readline from "readline";

dotenv.config();

async function initializeAgent() {
  const llm = new ChatOpenAI({
    model: "gpt-4o-mini",
    temperature: 0.7
  });

  // Parse the JSON byte array into a keypair
  const keypair = Keypair.fromSecretKey(
    Uint8Array.from(JSON.parse(process.env.SOLANA_PRIVATE_KEY!))
  );
  const wallet = new KeypairWallet(keypair, process.env.RPC_URL!);

  const solanaKit = new SolanaAgentKit(wallet, process.env.RPC_URL!, {
    OPENAI_API_KEY: process.env.OPENAI_API_KEY!
  })
    .use(TokenPlugin)
    .use(NFTPlugin);

  const tools = createLangchainTools(solanaKit, solanaKit.actions);
  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
    });
  };
}

runInteractiveChat().catch(console.error);
```

</Step>

<Step title="Run the agent">
You can run this script using the following command:

```bash
npx tsx agent.ts
```

This will start a simple chat with the agent.

</Step>

<Step title="Test basic functionality">
You can now ask it to show you your solana balance and ask it to request some
devnet sol:

```bash
Please show me my wallet address and request some devnet sol
```

If the devnet faucet is empty you can use the
[web faucet](https://faucet.solana.com) instead and paste in your solana
address.

</Step>

<Step title="Create an NFT collection">
Next ask the agent:

```bash
Please create me a NFT collection called trains with symbol TRN using this uri: https://scarlet-fancy-minnow-617.mypinata.cloud/ipfs/bafkreif43sp62yuy3sznrvqesk23tfnhpdck4npqowdwrhrzhsrgf5ao2e
```

</Step>

<Step title="Mint an NFT">
After the collection is created, mint an NFT:

```bash
Please mint me an NFT into that collection using the name: Train1 and using this URI: https://scarlet-fancy-minnow-617.mypinata.cloud/ipfs/bafkreif43sp62yuy3sznrvqesk23tfnhpdck4npqowdwrhrzhsrgf5ao2e
```

This will mint you an NFT with the name Train1 and an image of a train.

You can also use any different metadata for your NFT which you can upload using
[pinata](https://app.pinata.cloud/) or any other storage provider. You should
end up with something like this
[devnet train nft](https://explorer.solana.com/address/6dTVGn2M8LdAB6vrxzt7X8fm8HiP1QxN9j8jeh1dbyv8?cluster=devnet)

</Step>
</Steps>

Where to go from here?

- You can now for example import the private key into your browser extension
  wallet to see the NFT.
- You can ask the agent to show you all your NFTs. You will notice you will get
  an error for this action. This is because the default action to request assets
  uses the Helius Asset api to request assets so for that you would need to add
  a [Helius API key](https://www.helius.dev/) to your `.env` file and pass it
  into the agent.

```ts agent.ts
const solanaKit = new SolanaAgentKit(wallet, process.env.RPC_URL!, {
  OPENAI_API_KEY: process.env.OPENAI_API_KEY!,
  HELIUS_API_KEY: process.env.HELIUS_API_KEY!
})
  .use(TokenPlugin)
  .use(NFTPlugin);
```

- You can now start writing your own actions following the
  [Contribution guide](https://github.com/sendaifun/solana-agent-kit/blob/main/CONTRIBUTING.md)

There is also an
[example of a web chat](https://github.com/sendaifun/solana-agent-kit/tree/main/examples/agent-kit-nextjs-langchain)
for your agent using React that you can for example deploy to Vercel.

Not all actions are working 100% yet, like the request balance for example
sometimes fails, but you can see the progress in the
[Solana agent kit repo](https://github.com/sendaifun/solana-agent-kit) and also
contribute your own actions to be used by everyone.

## Building with Eliza Framework

[elizaOS](https://github.com/elizaOS/eliza) is a TypeScript framework for
autonomous agents. You define an agent as a character (its name, bio, style, and
the plugins it loads). Plugins add model providers, clients such as Discord,
Telegram, and X, and onchain actions. The
[Solana plugin](https://docs.elizaos.ai/plugin-registry/defi/solana)
(`@elizaos/plugin-solana`) gives the agent a Solana wallet and actions to
transfer and swap tokens.

The steps below were tested with elizaOS CLI 1.7.2 and `@elizaos/plugin-solana`
1.2.6 on devnet.

<Note>
  elizaOS requires [Bun](https://bun.sh/), so this section uses `bun` and `bunx`
  instead of the npm commands used elsewhere in these docs.
</Note>

<Steps titleSize="h3">

<Step title="Install the prerequisites">
  The [elizaOS installation guide](https://docs.elizaos.ai/installation) requires
  Bun and Node.js 23.3 or later:

  ```bash
  curl -fsSL https://bun.sh/install | bash
  bun --version
  node --version
  ```
</Step>

<Step title="Create a project">
  Create a project with the elizaOS CLI:

  ```bash
  bunx @elizaos/cli@latest create solana-agent
  cd solana-agent
  ```

  The CLI asks which database to use (choose `pglite` for a local file-based
  database) and which model provider to use, then writes a `.env` file, installs
  dependencies, and builds the project. The agent's character is in
  `src/character.ts`.
</Step>

<Step title="Add the Solana plugin">
  Install the plugin:

  ```bash
  bun add @elizaos/plugin-solana
  ```

  The elizaOS docs also show `elizaos plugins add solana`. In CLI 1.7.2 that
  command fails with `Failed to fetch plugin registry`, so install the package
  with `bun add` instead.

  Then add the plugin to the `plugins` array in `src/character.ts`, before
  `@elizaos/plugin-bootstrap`:

  ```ts src/character.ts
  plugins: [
    '@elizaos/plugin-sql',
    // ...model and client plugins
    '@elizaos/plugin-solana',
    ...(!process.env.IGNORE_BOOTSTRAP ? ['@elizaos/plugin-bootstrap'] : []),
  ],
  ```
</Step>

<Step title="Create a devnet wallet">
  The plugin reads the wallet's secret key as a base58 string. Generate a new
  keypair for the agent from the project folder (`@solana/web3.js` and `bs58`
  are installed with the plugin):

  ```bash
  bun -e 'import { Keypair } from "@solana/web3.js"; import bs58 from "bs58"; const k = Keypair.generate(); console.log("SOLANA_PUBLIC_KEY=" + k.publicKey.toBase58()); console.log("SOLANA_PRIVATE_KEY=" + bs58.encode(k.secretKey));'
  ```

  Use a new keypair that only holds devnet SOL. Then fund the address with
  [devnet SOL](/developers/cookbook/development/airdrops-and-faucets).
</Step>

<Step title="Configure the environment">
  Add the wallet and RPC settings to `.env`:

  ```ini .env
  SOLANA_RPC_URL=https://api.devnet.solana.com
  SOLANA_PUBLIC_KEY=your_agent_address
  SOLANA_PRIVATE_KEY=your_base58_secret_key
  ```

  - `SOLANA_RPC_URL` is required. If it is not set, the plugin skips its setup
    and registers no Solana actions.
  - `SOLANA_PRIVATE_KEY` also accepts a base64-encoded key. To give the agent a
    read-only wallet, set only `SOLANA_PUBLIC_KEY`.
  - `BIRDEYE_API_KEY` (optional) adds token prices and USD values to the
    wallet balances the agent sees.
  - The model provider key you chose during `create`, for example
    `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`, must be set for the agent to reply.
    `src/character.ts` loads each model plugin only when its key is set.

  The generated `.env` does not end with a newline. If you append to it from the
  shell, check that each variable is on its own line.
</Step>

<Step title="Start the agent">
  ```bash
  bunx elizaos start
  ```

  When the agent is running, the log shows
  `AgentServer is listening on port 3000` and `Started agents (count=1)`. Open
  [http://localhost:3000](http://localhost:3000) to chat with the agent. Use
  `bunx elizaos dev` instead to rebuild on file changes, and `--port` to use a
  different port.

  If no model provider key is set, the agent still starts with the Solana plugin
  loaded, but each message fails with
  `No handler found for delegate type: TEXT_LARGE`.
</Step>

<Step title="Use the agent onchain">
  With a funded wallet and a model provider key, the agent can:

  - Transfer SOL and SPL tokens (`TRANSFER_SOLANA`), for example
    `Send 0.1 SOL to <address>`.
  - Swap tokens through Jupiter (`SWAP_SOLANA`). Jupiter only routes mainnet
    liquidity, so swaps do not work on devnet.
  - Report its wallet address and balances through the wallet provider.

  Set `SOLANA_NO_ACTIONS=true` to keep the wallet provider but disable transfers
  and swaps. To connect the agent to Discord, Telegram, or X, set that client's
  variables in `.env`; `src/character.ts` loads the matching plugin when they are
  present.

  For more, see the
  [elizaOS quickstart](https://docs.elizaos.ai/quickstart), the
  [CLI reference](https://docs.elizaos.ai/cli-reference/overview), and the
  [Solana plugin examples](https://docs.elizaos.ai/plugin-registry/defi/solana/examples).
</Step>

</Steps>

## Using GOAT Toolkit

[GOAT](https://github.com/goat-sdk/goat) is similar to Solana Agent Kit a
collection of many different onchain 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](https://github.com/goat-sdk/goat/tree/main/typescript/examples/by-use-case/solana-purchase-on-amazon)
shows you how you can use [Crossmint](https://www.crossmint.com/) directly in
[Windsurf code editor](https://codeium.com/windsurf) to buy Items on Amazon.
There is also a
[demo video](https://x.com/windsurf_ai/status/1903118960633188485) available.

## Onchain 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:

[Onchain program LLM interaction](https://github.com/GabrielePicco/super-smart-contracts)

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:

```rust
// 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
}
```

This demonstrates how to combine AI capabilities with onchain token mechanics to
create interactive onchain experiences.

## Advanced Rust agents for algorithmic trading

If you want to write your agents in Rust you can use the
[Rig framework](https://github.com/0xPlaygrounds/rig) and the
[Listen.rs](https://github.com/piotrostr/listen) 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.
- Hold an agent's keys the way you would hold any other authority, in signing
  infrastructure you can audit and recover; see
  [authority custody](/developers/docs/tools/security#authority-custody).
- Use a paid [RPC endpoints](https://solana.com/rpc). 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 can automate onchain actions and interact with programs on
your behalf. 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.
