Merge branch 'main' into manifest

This commit is contained in:
DonDuala
2024-12-31 14:53:50 -04:00
committed by GitHub
50 changed files with 11022 additions and 1483 deletions

1
docs/assets/hierarchy.js Normal file
View File

@@ -0,0 +1 @@
window.hierarchyData = "eJyrVirKzy8pVrKKjtVRKkpNy0lNLsnMzytWsqqurQUAmx4Kpg=="

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 9.5 KiB

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
window.navigationData = "data:application/octet-stream;base64,H4sIAAAAAAAAE42TwU7DMAyG3yXniooJJtTbRFUkGDCN3hCHEFwaNXWixBFMaO+O6BCsLPW45OIv3x/ZzuOHIHgnUYgHayTKxSsg3WgSmXCSWlEIZWQIEPJx/aSl3ohMdBpfRHE6u9hmP6ZLawwo0hZLcMZuesA9n0YC30gFIU+BY/HsfJ4U37uvMxyxflOs0oMk69OiXY27XgGpduW1gjUEZzFA0nSIcdIr/fxmfTfEQy1Dt4Zp9RTMBVxHpwl8bTvAUpJMiv9CnHAZjV0oZSNSCSS1CWw7pnEu5FYj/c72rqrZjEmai1jF3jURlzKiall9kjymriIO7eS2N8Gx2g21/1zCNMrJ1bBUu49fW2v2XtxEHBob8gNobJyfbZ8+AWWuiIJlBAAA"
window.navigationData = "eJyNlMFKw0AQht9lz8Fg0SK5FUMFrVpqbuJhXSfNks3ssjuLFum7S1PRxm6mXnKZb74/DD/7/CkIPkgU4skaiXK2BqQ7TSITTlIjCqGMDAFCPpyfNdQZkYlW45sozidX2+zHdG2NAUXaYgnO2E0HeODTSOBrqSDkKXAonlxOk+JHt/uGE9Zvildirdcjnt2IXfYgyfr09n7Grc+BVLP0WsEKgrMYIGk6xjjpjX59t77t46GSoV3BuHoM5gJuo9MEvrItYClJJsV/IU64iMbOlLIRqQSS2gT2HOM4F3KvkX6L8TCv2IxRmotYxs7VERcyompYfZI8pZ5H7M/JVT/BsdoNNf8sYRrl5Kov1f7VqKw1B39cR+wPG/IjaGicXmxfvgDluqEc"

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html><html class="default" lang="en"><head><meta charset="utf-8"/><meta http-equiv="x-ua-compatible" content="IE=edge"/><title>solana-agent-kit</title><meta name="description" content="Documentation for solana-agent-kit"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="assets/style.css"/><link rel="stylesheet" href="assets/highlight.css"/><script defer src="assets/main.js"></script><script async src="assets/icons.js" id="tsd-icons-script"></script><script async src="assets/search.js" id="tsd-search-script"></script><script async src="assets/navigation.js" id="tsd-nav-script"></script></head><body><script>document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => app?app.showPage():document.body.style.removeProperty("display"),500)</script><header class="tsd-page-toolbar"><div class="tsd-toolbar-contents container"><div class="table-cell" id="tsd-search" data-base="."><div class="field"><label for="tsd-search-field" class="tsd-widget tsd-toolbar-icon search no-caption"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><use href="assets/icons.svg#icon-search"></use></svg></label><input type="text" id="tsd-search-field" aria-label="Search"/></div><div class="field"><div id="tsd-toolbar-links"></div></div><ul class="results"><li class="state loading">Preparing search index...</li><li class="state failure">The search index is not available</li></ul><a href="index.html" class="title">solana-agent-kit</a></div><div class="table-cell" id="tsd-widgets"><a href="#" class="tsd-widget tsd-toolbar-icon menu no-caption" data-toggle="menu" aria-label="Menu"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><use href="assets/icons.svg#icon-menu"></use></svg></a></div></div></header><div class="container container-main"><div class="col-content"><div class="tsd-page-title"><h1>solana-agent-kit</h1></div><div class="tsd-panel tsd-typography"><div align="center">
<a id="md:solana-agent-kit" class="tsd-anchor"></a><h1 class="tsd-anchor-link">Solana Agent Kit<a href="#md:solana-agent-kit" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h1><p><img src="https://github.com/user-attachments/assets/cfa380f6-79d9-474d-9852-3e1976c6de70" alt="Solana Agent Kit Cover 1 (3)"></p>
<!DOCTYPE html><html class="default" lang="en" data-base="."><head><meta charset="utf-8"/><meta http-equiv="x-ua-compatible" content="IE=edge"/><title>solana-agent-kit</title><meta name="description" content="Documentation for solana-agent-kit"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="assets/style.css"/><link rel="stylesheet" href="assets/highlight.css"/><script defer src="assets/main.js"></script><script async src="assets/icons.js" id="tsd-icons-script"></script><script async src="assets/search.js" id="tsd-search-script"></script><script async src="assets/navigation.js" id="tsd-nav-script"></script></head><body><script>document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => app?app.showPage():document.body.style.removeProperty("display"),500)</script><header class="tsd-page-toolbar"><div class="tsd-toolbar-contents container"><div class="table-cell" id="tsd-search"><div class="field"><label for="tsd-search-field" class="tsd-widget tsd-toolbar-icon search no-caption"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><use href="assets/icons.svg#icon-search"></use></svg></label><input type="text" id="tsd-search-field" aria-label="Search"/></div><div class="field"><div id="tsd-toolbar-links"></div></div><ul class="results"><li class="state loading">Preparing search index...</li><li class="state failure">The search index is not available</li></ul><a href="index.html" class="title">solana-agent-kit</a></div><div class="table-cell" id="tsd-widgets"><a href="#" class="tsd-widget tsd-toolbar-icon menu no-caption" data-toggle="menu" aria-label="Menu"><svg width="16" height="16" viewBox="0 0 16 16" fill="none"><use href="assets/icons.svg#icon-menu"></use></svg></a></div></div></header><div class="container container-main"><div class="col-content"><div class="tsd-page-title"><h1>solana-agent-kit</h1></div><div class="tsd-panel tsd-typography"><div align="center">
<a id="solana-agent-kit" class="tsd-anchor"></a><h1 class="tsd-anchor-link">Solana Agent Kit<a href="#solana-agent-kit" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h1><p><img src="https://github.com/user-attachments/assets/cfa380f6-79d9-474d-9852-3e1976c6de70" alt="Solana Agent Kit Cover 1 (3)"></p>
<p><img src="https://img.shields.io/npm/dm/solana-agent-kit?style=for-the-badge" alt="NPM Downloads">
<img src="https://img.shields.io/github/forks/sendaifun/solana-agent-kit?style=for-the-badge" alt="GitHub forks">
<img src="https://img.shields.io/github/license/sendaifun/solana-agent-kit?style=for-the-badge" alt="GitHub License"></p>
@@ -15,11 +15,11 @@
<li>And more...</li>
</ul>
<p>Anyone - whether an SF-based AI researcher or a crypto-native builder - can bring their AI agents trained with any model and seamlessly integrate with Solana.</p>
<p><a href="https://replit.com/@sendaifun/Solana-Agent-Kit" target="_blank" class="external"><img src="https://replit.com/badge/github/sendaifun/solana-agent-kit" alt="Run on Repl.it"></a></p>
<p><a href="https://replit.com/@sendaifun/Solana-Agent-Kit"><img src="https://replit.com/badge/github/sendaifun/solana-agent-kit" alt="Run on Repl.it"></a></p>
<blockquote>
<p>Replit template created by <a href="https://github.com/The-x-35" target="_blank" class="external">Arpit Singh</a></p>
<p>Replit template created by <a href="https://github.com/The-x-35">Arpit Singh</a></p>
</blockquote>
<a id="md:🔧-core-blockchain-features" class="tsd-anchor"></a><h2 class="tsd-anchor-link">🔧 Core Blockchain Features<a href="#md:🔧-core-blockchain-features" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><ul>
<a id="🔧-core-blockchain-features" class="tsd-anchor"></a><h2 class="tsd-anchor-link">🔧 Core Blockchain Features<a href="#🔧-core-blockchain-features" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><ul>
<li>
<p><strong>Token Operations</strong></p>
<ul>
@@ -46,7 +46,7 @@
<li>Launch on Pump via PumpPortal</li>
<li>Raydium pool creation (CPMM, CLMM, AMMv4)</li>
<li>Orca Whirlpool integration</li>
<li>Meteora Dynamic AMM, DLMM Pool, and Alpga Vault</li>
<li>Meteora Dynamic AMM, DLMM Pool, and Alpha Vault</li>
<li>Openbook market creation</li>
<li>Register and Resolve SNS</li>
<li>Jito Bundles</li>
@@ -57,7 +57,7 @@
<li>
<p><strong>Solana Blinks</strong></p>
<ul>
<li>Lending by Lulon (Best APR for USDC)</li>
<li>Lending by Lulo (Best APR for USDC)</li>
<li>Send Arcade Games</li>
<li>JupSOL staking</li>
</ul>
@@ -69,7 +69,7 @@
</ul>
</li>
</ul>
<a id="md:🤖-ai-integration-features" class="tsd-anchor"></a><h2 class="tsd-anchor-link">🤖 AI Integration Features<a href="#md:🤖-ai-integration-features" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><ul>
<a id="🤖-ai-integration-features" class="tsd-anchor"></a><h2 class="tsd-anchor-link">🤖 AI Integration Features<a href="#🤖-ai-integration-features" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><ul>
<li>
<p><strong>LangChain Integration</strong></p>
<ul>
@@ -98,34 +98,34 @@
</ul>
</li>
</ul>
<a id="md:📦-installation" class="tsd-anchor"></a><h2 class="tsd-anchor-link">📦 Installation<a href="#md:📦-installation" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><pre><code class="bash"><span class="hl-0">npm</span><span class="hl-1"> </span><span class="hl-2">install</span><span class="hl-1"> </span><span class="hl-2">solana-agent-kit</span>
<a id="📦-installation" class="tsd-anchor"></a><h2 class="tsd-anchor-link">📦 Installation<a href="#📦-installation" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><pre><code class="bash"><span class="hl-0">npm</span><span class="hl-1"> </span><span class="hl-2">install</span><span class="hl-1"> </span><span class="hl-2">solana-agent-kit</span>
</code><button type="button">Copy</button></pre>
<a id="md:quick-start" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Quick Start<a href="#md:quick-start" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">SolanaAgentKit</span><span class="hl-1">, </span><span class="hl-4">createSolanaTools</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;solana-agent-kit&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-5">// Initialize with private key and optional RPC URL</span><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">agent</span><span class="hl-1"> = </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">SolanaAgentKit</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;your-wallet-private-key-as-base58&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;https://api.mainnet-beta.solana.com&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;your-openai-api-key&quot;</span><br/><span class="hl-1">);</span><br/><br/><span class="hl-5">// Create LangChain tools</span><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">tools</span><span class="hl-1"> = </span><span class="hl-0">createSolanaTools</span><span class="hl-1">(</span><span class="hl-4">agent</span><span class="hl-1">);</span>
<a id="quick-start" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Quick Start<a href="#quick-start" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">SolanaAgentKit</span><span class="hl-1">, </span><span class="hl-4">createSolanaTools</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;solana-agent-kit&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-5">// Initialize with private key and optional RPC URL</span><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">agent</span><span class="hl-1"> = </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">SolanaAgentKit</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;your-wallet-private-key-as-base58&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;https://api.mainnet-beta.solana.com&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;your-openai-api-key&quot;</span><br/><span class="hl-1">);</span><br/><br/><span class="hl-5">// Create LangChain tools</span><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">tools</span><span class="hl-1"> = </span><span class="hl-0">createSolanaTools</span><span class="hl-1">(</span><span class="hl-4">agent</span><span class="hl-1">);</span>
</code><button type="button">Copy</button></pre>
<a id="md:usage-examples" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Usage Examples<a href="#md:usage-examples" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><a id="md:deploy-a-new-token" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Deploy a New Token<a href="#md:deploy-a-new-token" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">result</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">deployToken</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;my ai token&quot;</span><span class="hl-1">, </span><span class="hl-5">// name</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;uri&quot;</span><span class="hl-1">, </span><span class="hl-5">// uri</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;token&quot;</span><span class="hl-1">, </span><span class="hl-5">// symbol</span><br/><span class="hl-1"> </span><span class="hl-8">9</span><span class="hl-1">, </span><span class="hl-5">// decimals</span><br/><span class="hl-1"> </span><span class="hl-8">1000000</span><span class="hl-1"> </span><span class="hl-5">// initial supply</span><br/><span class="hl-1">);</span><br/><br/><span class="hl-4">console</span><span class="hl-1">.</span><span class="hl-0">log</span><span class="hl-1">(</span><span class="hl-2">&quot;Token Mint Address:&quot;</span><span class="hl-1">, </span><span class="hl-4">result</span><span class="hl-1">.</span><span class="hl-4">mint</span><span class="hl-1">.</span><span class="hl-0">toString</span><span class="hl-1">());</span>
<a id="usage-examples" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Usage Examples<a href="#usage-examples" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><a id="deploy-a-new-token" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Deploy a New Token<a href="#deploy-a-new-token" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">result</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">deployToken</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;my ai token&quot;</span><span class="hl-1">, </span><span class="hl-5">// name</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;uri&quot;</span><span class="hl-1">, </span><span class="hl-5">// uri</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;token&quot;</span><span class="hl-1">, </span><span class="hl-5">// symbol</span><br/><span class="hl-1"> </span><span class="hl-8">9</span><span class="hl-1">, </span><span class="hl-5">// decimals</span><br/><span class="hl-1"> </span><span class="hl-8">1000000</span><span class="hl-1"> </span><span class="hl-5">// initial supply</span><br/><span class="hl-1">);</span><br/><br/><span class="hl-4">console</span><span class="hl-1">.</span><span class="hl-0">log</span><span class="hl-1">(</span><span class="hl-2">&quot;Token Mint Address:&quot;</span><span class="hl-1">, </span><span class="hl-4">result</span><span class="hl-1">.</span><span class="hl-4">mint</span><span class="hl-1">.</span><span class="hl-0">toString</span><span class="hl-1">());</span>
</code><button type="button">Copy</button></pre>
<a id="md:create-nft-collection" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Create NFT Collection<a href="#md:create-nft-collection" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">collection</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">deployCollection</span><span class="hl-1">({</span><br/><span class="hl-1"> </span><span class="hl-4">name:</span><span class="hl-1"> </span><span class="hl-2">&quot;My NFT Collection&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-4">uri:</span><span class="hl-1"> </span><span class="hl-2">&quot;https://arweave.net/metadata.json&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-4">royaltyBasisPoints:</span><span class="hl-1"> </span><span class="hl-8">500</span><span class="hl-1">, </span><span class="hl-5">// 5%</span><br/><span class="hl-1"> </span><span class="hl-4">creators:</span><span class="hl-1"> [</span><br/><span class="hl-1"> {</span><br/><span class="hl-1"> </span><span class="hl-4">address:</span><span class="hl-1"> </span><span class="hl-2">&quot;creator-wallet-address&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-4">percentage:</span><span class="hl-1"> </span><span class="hl-8">100</span><span class="hl-1">,</span><br/><span class="hl-1"> },</span><br/><span class="hl-1"> ],</span><br/><span class="hl-1">});</span>
<a id="create-nft-collection" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Create NFT Collection<a href="#create-nft-collection" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">collection</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">deployCollection</span><span class="hl-1">({</span><br/><span class="hl-1"> </span><span class="hl-4">name:</span><span class="hl-1"> </span><span class="hl-2">&quot;My NFT Collection&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-4">uri:</span><span class="hl-1"> </span><span class="hl-2">&quot;https://arweave.net/metadata.json&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-4">royaltyBasisPoints:</span><span class="hl-1"> </span><span class="hl-8">500</span><span class="hl-1">, </span><span class="hl-5">// 5%</span><br/><span class="hl-1"> </span><span class="hl-4">creators:</span><span class="hl-1"> [</span><br/><span class="hl-1"> {</span><br/><span class="hl-1"> </span><span class="hl-4">address:</span><span class="hl-1"> </span><span class="hl-2">&quot;creator-wallet-address&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-4">percentage:</span><span class="hl-1"> </span><span class="hl-8">100</span><span class="hl-1">,</span><br/><span class="hl-1"> },</span><br/><span class="hl-1"> ],</span><br/><span class="hl-1">});</span>
</code><button type="button">Copy</button></pre>
<a id="md:swap-tokens" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Swap Tokens<a href="#md:swap-tokens" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">PublicKey</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;@solana/web3.js&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">trade</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;target-token-mint&quot;</span><span class="hl-1">),</span><br/><span class="hl-1"> </span><span class="hl-8">100</span><span class="hl-1">, </span><span class="hl-5">// amount</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;source-token-mint&quot;</span><span class="hl-1">),</span><br/><span class="hl-1"> </span><span class="hl-8">300</span><span class="hl-1"> </span><span class="hl-5">// 3% slippage</span><br/><span class="hl-1">);</span>
<a id="swap-tokens" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Swap Tokens<a href="#swap-tokens" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">PublicKey</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;@solana/web3.js&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">trade</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;target-token-mint&quot;</span><span class="hl-1">),</span><br/><span class="hl-1"> </span><span class="hl-8">100</span><span class="hl-1">, </span><span class="hl-5">// amount</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;source-token-mint&quot;</span><span class="hl-1">),</span><br/><span class="hl-1"> </span><span class="hl-8">300</span><span class="hl-1"> </span><span class="hl-5">// 3% slippage</span><br/><span class="hl-1">);</span>
</code><button type="button">Copy</button></pre>
<a id="md:lend-tokens" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Lend Tokens<a href="#md:lend-tokens" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">PublicKey</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;@solana/web3.js&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">lendAssets</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-8">100</span><span class="hl-1"> </span><span class="hl-5">// amount of USDC to lend</span><br/><span class="hl-1">);</span>
<a id="lend-tokens" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Lend Tokens<a href="#lend-tokens" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">PublicKey</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;@solana/web3.js&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">lendAssets</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-8">100</span><span class="hl-1"> </span><span class="hl-5">// amount of USDC to lend</span><br/><span class="hl-1">);</span>
</code><button type="button">Copy</button></pre>
<a id="md:stake-sol" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Stake SOL<a href="#md:stake-sol" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">stake</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-8">1</span><span class="hl-1"> </span><span class="hl-5">// amount in SOL to stake</span><br/><span class="hl-1">);</span>
<a id="stake-sol" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Stake SOL<a href="#stake-sol" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">stake</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-8">1</span><span class="hl-1"> </span><span class="hl-5">// amount in SOL to stake</span><br/><span class="hl-1">);</span>
</code><button type="button">Copy</button></pre>
<a id="md:send-an-spl-token-airdrop-via-zk-compression" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Send an SPL Token Airdrop via ZK Compression<a href="#md:send-an-spl-token-airdrop-via-zk-compression" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">PublicKey</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;@solana/web3.js&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-1">(</span><span class="hl-6">async</span><span class="hl-1"> () </span><span class="hl-6">=&gt;</span><span class="hl-1"> {</span><br/><span class="hl-1"> </span><span class="hl-4">console</span><span class="hl-1">.</span><span class="hl-0">log</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;~Airdrop cost estimate:&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-0">getAirdropCostEstimate</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-8">1000</span><span class="hl-1">, </span><span class="hl-5">// recipients</span><br/><span class="hl-1"> </span><span class="hl-8">30_000</span><span class="hl-1"> </span><span class="hl-5">// priority fee in lamports</span><br/><span class="hl-1"> )</span><br/><span class="hl-1"> );</span><br/><br/><span class="hl-1"> </span><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">sendCompressedAirdrop</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN&quot;</span><span class="hl-1">), </span><span class="hl-5">// mint</span><br/><span class="hl-1"> </span><span class="hl-8">42</span><span class="hl-1">, </span><span class="hl-5">// amount per recipient</span><br/><span class="hl-1"> [</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;1nc1nerator11111111111111111111111111111111&quot;</span><span class="hl-1">),</span><br/><span class="hl-1"> </span><span class="hl-5">// ... add more recipients</span><br/><span class="hl-1"> ],</span><br/><span class="hl-1"> </span><span class="hl-8">30_000</span><span class="hl-1"> </span><span class="hl-5">// priority fee in lamports</span><br/><span class="hl-1"> );</span><br/><span class="hl-1">})();</span>
<a id="send-an-spl-token-airdrop-via-zk-compression" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Send an SPL Token Airdrop via ZK Compression<a href="#send-an-spl-token-airdrop-via-zk-compression" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><span class="hl-3">import</span><span class="hl-1"> { </span><span class="hl-4">PublicKey</span><span class="hl-1"> } </span><span class="hl-3">from</span><span class="hl-1"> </span><span class="hl-2">&quot;@solana/web3.js&quot;</span><span class="hl-1">;</span><br/><br/><span class="hl-1">(</span><span class="hl-6">async</span><span class="hl-1"> () </span><span class="hl-6">=&gt;</span><span class="hl-1"> {</span><br/><span class="hl-1"> </span><span class="hl-4">console</span><span class="hl-1">.</span><span class="hl-0">log</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;~Airdrop cost estimate:&quot;</span><span class="hl-1">,</span><br/><span class="hl-1"> </span><span class="hl-0">getAirdropCostEstimate</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-8">1000</span><span class="hl-1">, </span><span class="hl-5">// recipients</span><br/><span class="hl-1"> </span><span class="hl-8">30_000</span><span class="hl-1"> </span><span class="hl-5">// priority fee in lamports</span><br/><span class="hl-1"> )</span><br/><span class="hl-1"> );</span><br/><br/><span class="hl-1"> </span><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">signature</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">sendCompressedAirdrop</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN&quot;</span><span class="hl-1">), </span><span class="hl-5">// mint</span><br/><span class="hl-1"> </span><span class="hl-8">42</span><span class="hl-1">, </span><span class="hl-5">// amount per recipient</span><br/><span class="hl-1"> [</span><br/><span class="hl-1"> </span><span class="hl-6">new</span><span class="hl-1"> </span><span class="hl-0">PublicKey</span><span class="hl-1">(</span><span class="hl-2">&quot;1nc1nerator11111111111111111111111111111111&quot;</span><span class="hl-1">),</span><br/><span class="hl-1"> </span><span class="hl-5">// ... add more recipients</span><br/><span class="hl-1"> ],</span><br/><span class="hl-1"> </span><span class="hl-8">30_000</span><span class="hl-1"> </span><span class="hl-5">// priority fee in lamports</span><br/><span class="hl-1"> );</span><br/><span class="hl-1">})();</span>
</code><button type="button">Copy</button></pre>
<a id="md:fetch-price-data-from-pyth" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Fetch Price Data from Pyth<a href="#md:fetch-price-data-from-pyth" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">price</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">pythFetchPrice</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43&quot;</span><br/><span class="hl-1">);</span><br/><br/><span class="hl-4">console</span><span class="hl-1">.</span><span class="hl-0">log</span><span class="hl-1">(</span><span class="hl-2">&quot;Price in BTC/USD:&quot;</span><span class="hl-1">, </span><span class="hl-4">price</span><span class="hl-1">);</span>
<a id="fetch-price-data-from-pyth" class="tsd-anchor"></a><h3 class="tsd-anchor-link">Fetch Price Data from Pyth<a href="#fetch-price-data-from-pyth" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><pre><code class="typescript"><br/><span class="hl-6">const</span><span class="hl-1"> </span><span class="hl-7">price</span><span class="hl-1"> = </span><span class="hl-3">await</span><span class="hl-1"> </span><span class="hl-4">agent</span><span class="hl-1">.</span><span class="hl-0">pythFetchPrice</span><span class="hl-1">(</span><br/><span class="hl-1"> </span><span class="hl-2">&quot;0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43&quot;</span><br/><span class="hl-1">);</span><br/><br/><span class="hl-4">console</span><span class="hl-1">.</span><span class="hl-0">log</span><span class="hl-1">(</span><span class="hl-2">&quot;Price in BTC/USD:&quot;</span><span class="hl-1">, </span><span class="hl-4">price</span><span class="hl-1">);</span>
</code><button type="button">Copy</button></pre>
<a id="md:examples" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Examples<a href="#md:examples" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><a id="md:langgraph-multi-agent-system" class="tsd-anchor"></a><h3 class="tsd-anchor-link">LangGraph Multi-Agent System<a href="#md:langgraph-multi-agent-system" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><p>The repository includes an advanced example of building a multi-agent system using LangGraph and Solana Agent Kit. Located in <code>examples/agent-kit-langgraph</code>, this example demonstrates:</p>
<a id="examples" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Examples<a href="#examples" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><a id="langgraph-multi-agent-system" class="tsd-anchor"></a><h3 class="tsd-anchor-link">LangGraph Multi-Agent System<a href="#langgraph-multi-agent-system" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h3><p>The repository includes an advanced example of building a multi-agent system using LangGraph and Solana Agent Kit. Located in <code>examples/agent-kit-langgraph</code>, this example demonstrates:</p>
<ul>
<li>Multi-agent architecture using LangGraph's StateGraph</li>
<li>Specialized agents for different tasks:
@@ -140,7 +140,7 @@
<li>Environment-based configuration</li>
</ul>
<p>Check out the <a href="examples/agent-kit-langgraph">LangGraph example</a> for a complete implementation of an advanced Solana agent system.</p>
<a id="md:dependencies" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Dependencies<a href="#md:dependencies" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>The toolkit relies on several key Solana and Metaplex libraries:</p>
<a id="dependencies" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Dependencies<a href="#dependencies" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>The toolkit relies on several key Solana and Metaplex libraries:</p>
<ul>
<li>@solana/web3.js</li>
<li>@solana/spl-token</li>
@@ -151,12 +151,12 @@
<li>@lightprotocol/stateless.js</li>
<li>@pythnetwork/price-service-client</li>
</ul>
<a id="md:contributing" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Contributing<a href="#md:contributing" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>Contributions are welcome! Please feel free to submit a Pull Request.
<a id="contributing" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Contributing<a href="#contributing" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>Contributions are welcome! Please feel free to submit a Pull Request.
Refer to <a href="media/CONTRIBUTING.md">CONTRIBUTING.md</a> for detailed guidelines on how to contribute to this project.</p>
<a id="md:contributors" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Contributors<a href="#md:contributors" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><a href="https://github.com/sendaifun/solana-agent-kit/graphs/contributors">
<a id="contributors" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Contributors<a href="#contributors" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><a href="https://github.com/sendaifun/solana-agent-kit/graphs/contributors">
<img src="https://contrib.rocks/image?repo=sendaifun/solana-agent-kit" />
</a>
<a id="md:star-history" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Star History<a href="#md:star-history" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p><a href="https://star-history.com/#sendaifun/solana-agent-kit&amp;Date" target="_blank" class="external"><img src="https://api.star-history.com/svg?repos=sendaifun/solana-agent-kit&amp;type=Date" alt="Star History Chart"></a></p>
<a id="md:license" class="tsd-anchor"></a><h2 class="tsd-anchor-link">License<a href="#md:license" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>Apache-2 License</p>
<a id="md:security" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Security<a href="#md:security" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>This toolkit handles private keys and transactions. Always ensure you're using it in a secure environment and never share your private keys.</p>
</div></div><div class="col-sidebar"><div class="page-menu"><div class="tsd-navigation settings"><details class="tsd-accordion"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>Settings</h3></summary><div class="tsd-accordion-details"><div class="tsd-filter-visibility"><span class="settings-label">Member Visibility</span><ul id="tsd-filter-options"><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-protected" name="protected"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Protected</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-inherited" name="inherited" checked/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Inherited</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-external" name="external"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>External</span></label></li></ul></div><div class="tsd-theme-toggle"><label class="settings-label" for="tsd-theme">Theme</label><select id="tsd-theme"><option value="os">OS</option><option value="light">Light</option><option value="dark">Dark</option></select></div></div></details></div><details open class="tsd-accordion tsd-page-navigation"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>On This Page</h3></summary><div class="tsd-accordion-details"><a href="#md:solana-agent-kit"><span>Solana <wbr/>Agent <wbr/>Kit</span></a><ul><li><a href="#md:🔧-core-blockchain-features"><span>🔧 <wbr/>Core <wbr/>Blockchain <wbr/>Features</span></a></li><li><a href="#md:🤖-ai-integration-features"><span>🤖 AI <wbr/>Integration <wbr/>Features</span></a></li><li><a href="#md:📦-installation"><span>📦 <wbr/>Installation</span></a></li><li><a href="#md:quick-start"><span>Quick <wbr/>Start</span></a></li><li><a href="#md:usage-examples"><span>Usage <wbr/>Examples</span></a></li><li><ul><li><a href="#md:deploy-a-new-token"><span>Deploy a <wbr/>New <wbr/>Token</span></a></li><li><a href="#md:create-nft-collection"><span>Create NFT <wbr/>Collection</span></a></li><li><a href="#md:swap-tokens"><span>Swap <wbr/>Tokens</span></a></li><li><a href="#md:lend-tokens"><span>Lend <wbr/>Tokens</span></a></li><li><a href="#md:stake-sol"><span>Stake SOL</span></a></li><li><a href="#md:send-an-spl-token-airdrop-via-zk-compression"><span>Send an SPL <wbr/>Token <wbr/>Airdrop via ZK <wbr/>Compression</span></a></li><li><a href="#md:fetch-price-data-from-pyth"><span>Fetch <wbr/>Price <wbr/>Data from <wbr/>Pyth</span></a></li></ul></li><li><a href="#md:examples"><span>Examples</span></a></li><li><ul><li><a href="#md:langgraph-multi-agent-system"><span>Lang<wbr/>Graph <wbr/>Multi-<wbr/>Agent <wbr/>System</span></a></li></ul></li><li><a href="#md:dependencies"><span>Dependencies</span></a></li><li><a href="#md:contributing"><span>Contributing</span></a></li><li><a href="#md:contributors"><span>Contributors</span></a></li><li><a href="#md:star-history"><span>Star <wbr/>History</span></a></li><li><a href="#md:license"><span>License</span></a></li><li><a href="#md:security"><span>Security</span></a></li></ul></div></details></div><div class="site-menu"><nav class="tsd-navigation"><a href="modules.html" class="current"><svg class="tsd-kind-icon" viewBox="0 0 24 24"><use href="assets/icons.svg#icon-1"></use></svg><span>solana-agent-kit</span></a><ul class="tsd-small-nested-navigation" id="tsd-nav-container" data-base="."><li>Loading...</li></ul></nav></div></div></div><footer><p class="tsd-generator">Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p></footer><div class="overlay"></div></body></html>
<a id="star-history" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Star History<a href="#star-history" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p><a href="https://star-history.com/#sendaifun/solana-agent-kit&amp;Date"><img src="https://api.star-history.com/svg?repos=sendaifun/solana-agent-kit&amp;type=Date" alt="Star History Chart"></a></p>
<a id="license" class="tsd-anchor"></a><h2 class="tsd-anchor-link">License<a href="#license" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>Apache-2 License</p>
<a id="security" class="tsd-anchor"></a><h2 class="tsd-anchor-link">Security<a href="#security" aria-label="Permalink" class="tsd-anchor-icon"><svg viewBox="0 0 24 24"><use href="assets/icons.svg#icon-anchor"></use></svg></a></h2><p>This toolkit handles private keys and transactions. Always ensure you're using it in a secure environment and never share your private keys.</p>
</div></div><div class="col-sidebar"><div class="page-menu"><div class="tsd-navigation settings"><details class="tsd-accordion"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>Settings</h3></summary><div class="tsd-accordion-details"><div class="tsd-filter-visibility"><span class="settings-label">Member Visibility</span><ul id="tsd-filter-options"><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-protected" name="protected"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Protected</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-inherited" name="inherited" checked/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>Inherited</span></label></li><li class="tsd-filter-item"><label class="tsd-filter-input"><input type="checkbox" id="tsd-filter-external" name="external"/><svg width="32" height="32" viewBox="0 0 32 32" aria-hidden="true"><rect class="tsd-checkbox-background" width="30" height="30" x="1" y="1" rx="6" fill="none"></rect><path class="tsd-checkbox-checkmark" d="M8.35422 16.8214L13.2143 21.75L24.6458 10.25" stroke="none" stroke-width="3.5" stroke-linejoin="round" fill="none"></path></svg><span>External</span></label></li></ul></div><div class="tsd-theme-toggle"><label class="settings-label" for="tsd-theme">Theme</label><select id="tsd-theme"><option value="os">OS</option><option value="light">Light</option><option value="dark">Dark</option></select></div></div></details></div><details open class="tsd-accordion tsd-page-navigation"><summary class="tsd-accordion-summary"><h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none"><use href="assets/icons.svg#icon-chevronDown"></use></svg>On This Page</h3></summary><div class="tsd-accordion-details"><a href="#solana-agent-kit"><span>Solana <wbr/>Agent <wbr/>Kit</span></a><ul><li><a href="#🔧-core-blockchain-features"><span>🔧 <wbr/>Core <wbr/>Blockchain <wbr/>Features</span></a></li><li><a href="#🤖-ai-integration-features"><span>🤖 AI <wbr/>Integration <wbr/>Features</span></a></li><li><a href="#📦-installation"><span>📦 <wbr/>Installation</span></a></li><li><a href="#quick-start"><span>Quick <wbr/>Start</span></a></li><li><a href="#usage-examples"><span>Usage <wbr/>Examples</span></a></li><li><ul><li><a href="#deploy-a-new-token"><span>Deploy a <wbr/>New <wbr/>Token</span></a></li><li><a href="#create-nft-collection"><span>Create NFT <wbr/>Collection</span></a></li><li><a href="#swap-tokens"><span>Swap <wbr/>Tokens</span></a></li><li><a href="#lend-tokens"><span>Lend <wbr/>Tokens</span></a></li><li><a href="#stake-sol"><span>Stake SOL</span></a></li><li><a href="#send-an-spl-token-airdrop-via-zk-compression"><span>Send an SPL <wbr/>Token <wbr/>Airdrop via ZK <wbr/>Compression</span></a></li><li><a href="#fetch-price-data-from-pyth"><span>Fetch <wbr/>Price <wbr/>Data from <wbr/>Pyth</span></a></li></ul></li><li><a href="#examples"><span>Examples</span></a></li><li><ul><li><a href="#langgraph-multi-agent-system"><span>Lang<wbr/>Graph <wbr/>Multi-<wbr/>Agent <wbr/>System</span></a></li></ul></li><li><a href="#dependencies"><span>Dependencies</span></a></li><li><a href="#contributing"><span>Contributing</span></a></li><li><a href="#contributors"><span>Contributors</span></a></li><li><a href="#star-history"><span>Star <wbr/>History</span></a></li><li><a href="#license"><span>License</span></a></li><li><a href="#security"><span>Security</span></a></li></ul></div></details></div><div class="site-menu"><nav class="tsd-navigation"><a href="modules.html">solana-agent-kit</a><ul class="tsd-small-nested-navigation" id="tsd-nav-container"><li>Loading...</li></ul></nav></div></div></div><footer><p class="tsd-generator">Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p></footer><div class="overlay"></div></body></html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
LANGCHAIN_CALLBACKS_BACKGROUND=false
OPENAI_API_KEY=
RPC_URL=
SOLANA_PRIVATE_KEY=

View File

@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}

View File

@@ -0,0 +1,43 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
.env

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 LangChain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,56 @@
# SolanaAgentKit 🦜️🔗 LangChain + Next.js Starter Template
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/michaelessiet/solana-agent-nextjs-starter-langchain)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsendaifun%2Fsolana-agent-kit%2Ftree%2Fmain%2Fexamples%2Fagent-kit-nextjs-langchain&env=OPENAI_API_KEY,RPC_URL,SOLANA_PRIVATE_KEY&project-name=solana-agent-kit&repository-name=sak-yourprojectname)
This template scaffolds a SolanaAgentKit + LangChain.js + Next.js starter app.
The agent uses [LangGraph.js](https://langchain-ai.github.io/langgraphjs/), LangChain's framework for building agentic workflows. They use preconfigured helper functions to minimize boilerplate, but you can replace them with custom graphs as desired.
![Demo GIF](/public/images/agent-convo.gif)
It's free-tier friendly too! Check out the [bundle size stats below](#-bundle-size).
## 🚀 Getting Started
First, clone this repo and download it locally.
Next, you'll need to set up environment variables in your repo's `.env.local` file. Copy the `.env.example` file to `.env.local`.
To start, you'll just need to add your OpenAI API key, Solana RPC URL and wallet private key in base 58 string form.
Next, install the required packages using your preferred package manager (e.g. `pnpm`).
```bash
pnpm install
```
Now you're ready to run the development server:
```bash
pnpm dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result! Ask the bot something and you'll see a streamed response:
![A streaming conversation between the user and the AI](/public/images/chat-conversation.png)
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
Backend logic lives in `app/api/chat/route.ts`. From here, you can change the prompt and model, or add other modules and logic.
## 📚 Learn More
To learn more about what you can do with SolanaAgentKit and LangChain.js, check out the docs here:
- https://github.com/sendaifun/solana-agent-kit
- https://js.langchain.com/docs/
## ▲ Deploy on Vercel
When ready, you can deploy your app on the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme).
Check out the [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
## Thank You!
Thanks for reading! If you have any questions or comments, please drop an issue on this repo or reach out to us on [X](https://x.com/sendaifun)

View File

@@ -0,0 +1,71 @@
import { NextRequest, NextResponse } from "next/server";
import { ChatOpenAI } from "@langchain/openai";
import { MemorySaver } from "@langchain/langgraph";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { SolanaAgentKit, createSolanaTools } from "solana-agent-kit";
const llm = new ChatOpenAI({
temperature: 0.7,
model: "gpt-4o-mini",
});
const solanaAgent = new SolanaAgentKit(
process.env.SOLANA_PRIVATE_KEY!,
process.env.RPC_URL,
process.env.OPENAI_API_KEY!,
);
const tools = createSolanaTools(solanaAgent);
const memory = new MemorySaver();
const agent = createReactAgent({
llm,
tools,
checkpointSaver: memory,
messageModifier: `
You are a helpful agent that can interact onchain using the Solana Agent Kit. You are
empowered to interact onchain using your tools. If you ever need funds, you can request them from the
faucet. If not, you can provide your wallet details and request funds from the user. If there is a 5XX
(internal) HTTP error code, ask the user to try again later. If someone asks you to do something you
can't do with your currently available tools, you must say so, and encourage them to implement it
themselves using the Solana Agent Kit, recommend they go to https://www.solanaagentkit.xyz for more information. Be
concise and helpful with your responses. Refrain from restating your tools' descriptions unless it is explicitly requested.
`,
});
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const messages = body.messages ?? [];
const eventStream = agent.streamEvents(
{
messages,
},
{
version: "v2",
configurable: {
thread_id: "Solana Agent Kit!",
},
},
);
const textEncoder = new TextEncoder();
const transformStream = new ReadableStream({
async start(controller) {
for await (const { event, data } of eventStream) {
if (event === "on_chat_model_stream") {
if (!!data.chunk.content) {
controller.enqueue(textEncoder.encode(data.chunk.content));
}
}
}
controller.close();
},
});
return new Response(transformStream);
} catch (e: any) {
return NextResponse.json({ error: e.message }, { status: e.status ?? 500 });
}
}

View File

@@ -0,0 +1,33 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
color: #f8f8f8;
background: #131318;
}
body input,
body textarea {
color: black;
}
a {
color: #2d7bd4;
}
a:hover {
border-bottom: 1px solid;
}
p {
margin: 8px 0;
}
code {
color: #ffa500;
}
li {
padding: 4px;
}

View File

@@ -0,0 +1,45 @@
import "./globals.css";
import { Public_Sans } from "next/font/google";
const publicSans = Public_Sans({ subsets: ["latin"] });
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<head>
<title>SolanaAgentKit + LangChain + Next.js Template</title>
<link rel="shortcut icon" href="/images/favicon.ico" />
<meta
name="description"
content="Starter template showing how to use SolanaAgentKit with Langchain in Next.js projects."
/>
<meta
property="og:title"
content="SolanaAgentKit + LangChain + Next.js Template"
/>
<meta
property="og:description"
content="Starter template showing how to use SolanaAgentKit with LangChain in Next.js projects."
/>
<meta property="og:image" content="/images/title-card.png" />
<meta name="twitter:card" content="summary_large_image" />
<meta
name="twitter:title"
content="SolanaAgentKit + LangChain + Next.js Template"
/>
<meta
name="twitter:description"
content="Starter template showing how to use SolanaAgentKit with LangChain in Next.js projects."
/>
<meta name="twitter:image" content="/images/title-card.png" />
</head>
<body className={publicSans.className}>
<div className="flex flex-col p-4 md:p-12 h-[100vh]">{children}</div>
</body>
</html>
);
}

View File

@@ -0,0 +1,75 @@
import { ChatWindow } from "@/components/ChatWindow";
export default function Home() {
const InfoCard = (
<div className="p-4 md:p-8 rounded bg-[#25252d] w-full max-h-[85%] overflow-hidden">
<h1 className="text-3xl md:text-4xl mb-4">
SolanaAgentKit + LangChain.js 🦜🔗 + Next.js
</h1>
<ul>
<li className="text-l">
🤝
<span className="ml-2">
This template showcases a simple agent chatbot using{" "}
<a href="https://https://www.solanaagentkit.xyz/">SolanaAgentKit</a>
{", "}
<a href="https://js.langchain.com/" target="_blank">
LangChain.js
</a>{" "}
and the Vercel{" "}
<a href="https://sdk.vercel.ai/docs" target="_blank">
AI SDK
</a>{" "}
in a{" "}
<a href="https://nextjs.org/" target="_blank">
Next.js
</a>{" "}
project.
</span>
</li>
<li className="hidden text-l md:block">
💻
<span className="ml-2">
You can find the prompt and model logic for this use-case in{" "}
<code>app/api/chat/route.ts</code>.
</span>
</li>
<li className="hidden text-l md:block">
🎨
<span className="ml-2">
The main frontend logic is found in <code>app/page.tsx</code>.
</span>
</li>
<li className="text-l">
🐙
<span className="ml-2">
This template is open source - you can see the source code and
deploy your own version{" "}
<a
href="https://github.com/michaelessiet/solana-agent-nextjs-starter-langchain"
target="_blank"
>
from the GitHub repo
</a>
!
</span>
</li>
<li className="text-l">
👇
<span className="ml-2">
Try asking e.g. <code>What is my wallet address?</code> below!
</span>
</li>
</ul>
</div>
);
return (
<ChatWindow
endpoint="api/chat"
emoji="🤖"
titleText="Solana agent"
placeholder="I'm your friendly Solana agent! Ask me anything..."
emptyStateComponent={InfoCard}
></ChatWindow>
);
}

View File

@@ -0,0 +1,58 @@
import markdownToHtml from "@/utils/markdownToHTML";
import type { Message } from "ai/react";
import { useMemo } from "react";
export function ChatMessageBubble(props: {
message: Message;
aiEmoji?: string;
sources: any[];
}) {
const colorClassName =
props.message.role === "user" ? "bg-sky-600" : "bg-slate-50 text-black";
const alignmentClassName =
props.message.role === "user" ? "ml-auto" : "mr-auto";
const prefix = props.message.role === "user" ? "🧑" : props.aiEmoji;
const content = useMemo(() => {
return markdownToHtml(props.message.content);
}, [props.message.content]);
return (
<div
className={`${alignmentClassName} ${colorClassName} rounded px-4 py-2 max-w-[80%] mb-8 flex`}
>
<div className="mr-2">{prefix}</div>
<div className="flex flex-col">
<div
className="prose prose-lg max-w-none"
dangerouslySetInnerHTML={{ __html: content }}
></div>
{props.sources && props.sources.length ? (
<>
<code className="mt-4 mr-auto bg-slate-600 px-2 py-1 rounded">
<h2>🔍 Sources:</h2>
</code>
<code className="mt-1 mr-2 bg-slate-600 px-2 py-1 rounded text-xs">
{props.sources?.map((source, i) => (
<div className="mt-2" key={"source:" + i}>
{i + 1}. &quot;{source.pageContent}&quot;
{source.metadata?.loc?.lines !== undefined ? (
<div>
<br />
Lines {source.metadata?.loc?.lines?.from} to{" "}
{source.metadata?.loc?.lines?.to}
</div>
) : (
""
)}
</div>
))}
</code>
</>
) : (
""
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,248 @@
"use client";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { Message } from "ai";
import { useChat } from "ai/react";
import { useRef, useState, ReactElement } from "react";
import type { FormEvent } from "react";
import { ChatMessageBubble } from "@/components/ChatMessageBubble";
import { IntermediateStep } from "./IntermediateStep";
export function ChatWindow(props: {
endpoint: string;
emptyStateComponent: ReactElement;
placeholder?: string;
titleText?: string;
emoji?: string;
showIntermediateStepsToggle?: boolean;
}) {
const messageContainerRef = useRef<HTMLDivElement | null>(null);
const {
endpoint,
emptyStateComponent,
placeholder,
titleText = "An LLM",
showIntermediateStepsToggle,
emoji,
} = props;
const [showIntermediateSteps, setShowIntermediateSteps] = useState(false);
const [intermediateStepsLoading, setIntermediateStepsLoading] =
useState(false);
const intemediateStepsToggle = showIntermediateStepsToggle && (
<div>
<input
type="checkbox"
id="show_intermediate_steps"
name="show_intermediate_steps"
checked={showIntermediateSteps}
onChange={(e) => setShowIntermediateSteps(e.target.checked)}
></input>
<label htmlFor="show_intermediate_steps"> Show intermediate steps</label>
</div>
);
const [sourcesForMessages, setSourcesForMessages] = useState<
Record<string, any>
>({});
const {
messages,
input,
setInput,
handleInputChange,
handleSubmit,
isLoading: chatEndpointIsLoading,
setMessages,
} = useChat({
api: endpoint,
onResponse(response) {
const sourcesHeader = response.headers.get("x-sources");
const sources = sourcesHeader
? JSON.parse(Buffer.from(sourcesHeader, "base64").toString("utf8"))
: [];
const messageIndexHeader = response.headers.get("x-message-index");
if (sources.length && messageIndexHeader !== null) {
setSourcesForMessages({
...sourcesForMessages,
[messageIndexHeader]: sources,
});
}
},
streamMode: "text",
onError: (e) => {
toast(e.message, {
theme: "dark",
});
},
});
async function sendMessage(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (messageContainerRef.current) {
messageContainerRef.current.classList.add("grow");
}
if (!messages.length) {
await new Promise((resolve) => setTimeout(resolve, 300));
}
if (chatEndpointIsLoading ?? intermediateStepsLoading) {
return;
}
if (!showIntermediateSteps) {
handleSubmit(e);
// Some extra work to show intermediate steps properly
} else {
setIntermediateStepsLoading(true);
setInput("");
const messagesWithUserReply = messages.concat({
id: messages.length.toString(),
content: input,
role: "user",
});
setMessages(messagesWithUserReply);
const response = await fetch(endpoint, {
method: "POST",
body: JSON.stringify({
messages: messagesWithUserReply,
show_intermediate_steps: true,
}),
});
const json = await response.json();
setIntermediateStepsLoading(false);
if (response.status === 200) {
const responseMessages: Message[] = json.messages;
// Represent intermediate steps as system messages for display purposes
// TODO: Add proper support for tool messages
const toolCallMessages = responseMessages.filter(
(responseMessage: Message) => {
return (
(responseMessage.role === "assistant" &&
!!responseMessage.tool_calls?.length) ||
responseMessage.role === "tool"
);
},
);
const intermediateStepMessages = [];
for (let i = 0; i < toolCallMessages.length; i += 2) {
const aiMessage = toolCallMessages[i];
const toolMessage = toolCallMessages[i + 1];
intermediateStepMessages.push({
id: (messagesWithUserReply.length + i / 2).toString(),
role: "system" as const,
content: JSON.stringify({
action: aiMessage.tool_calls?.[0],
observation: toolMessage.content,
}),
});
}
const newMessages = messagesWithUserReply;
for (const message of intermediateStepMessages) {
newMessages.push(message);
setMessages([...newMessages]);
await new Promise((resolve) =>
setTimeout(resolve, 1000 + Math.random() * 1000),
);
}
setMessages([
...newMessages,
{
id: newMessages.length.toString(),
content: responseMessages[responseMessages.length - 1].content,
role: "assistant",
},
]);
} else {
if (json.error) {
toast(json.error, {
theme: "dark",
});
throw new Error(json.error);
}
}
}
}
return (
<div
className={`flex flex-col items-center p-4 md:p-8 rounded grow overflow-hidden ${messages.length > 0 ? "border" : ""}`}
>
<h2 className={`${messages.length > 0 ? "" : "hidden"} text-2xl`}>
{emoji} {titleText}
</h2>
{messages.length === 0 ? emptyStateComponent : ""}
<div
className="flex flex-col-reverse w-full mb-4 overflow-auto transition-[flex-grow] ease-in-out"
ref={messageContainerRef}
>
{messages.length > 0
? [...messages].reverse().map((m, i) => {
const sourceKey = (messages.length - 1 - i).toString();
return m.role === "system" ? (
<IntermediateStep key={m.id} message={m}></IntermediateStep>
) : (
<ChatMessageBubble
key={m.id}
message={m}
aiEmoji={emoji}
sources={sourcesForMessages[sourceKey]}
></ChatMessageBubble>
);
})
: ""}
</div>
<form onSubmit={sendMessage} className="flex w-full flex-col">
<div className="flex">{intemediateStepsToggle}</div>
<div className="flex w-full mt-4">
<input
className="grow mr-8 p-4 rounded"
value={input}
placeholder={placeholder ?? "What's it like to be a pirate?"}
onChange={handleInputChange}
/>
<button
type="submit"
className="shrink-0 px-8 py-4 bg-sky-600 rounded w-28"
>
<div
role="status"
className={`${chatEndpointIsLoading || intermediateStepsLoading ? "" : "hidden"} flex justify-center`}
>
<svg
aria-hidden="true"
className="w-6 h-6 text-white animate-spin dark:text-white fill-sky-800"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
<span
className={
chatEndpointIsLoading || intermediateStepsLoading
? "hidden"
: ""
}
>
Send
</span>
</button>
</div>
</form>
<ToastContainer />
</div>
);
}

View File

@@ -0,0 +1,50 @@
import { useState } from "react";
import type { Message } from "ai/react";
export function IntermediateStep(props: { message: Message }) {
const parsedInput = JSON.parse(props.message.content);
const action = parsedInput.action;
const observation = parsedInput.observation;
const [expanded, setExpanded] = useState(false);
return (
<div
className={`ml-auto bg-green-600 rounded px-4 py-2 max-w-[80%] mb-8 whitespace-pre-wrap flex flex-col cursor-pointer`}
>
<div
className={`text-right ${expanded ? "w-full" : ""}`}
onClick={(e) => setExpanded(!expanded)}
>
<code className="mr-2 bg-slate-600 px-2 py-1 rounded hover:text-blue-600">
🛠 <b>{action.name}</b>
</code>
<span className={expanded ? "hidden" : ""}>🔽</span>
<span className={expanded ? "" : "hidden"}>🔼</span>
</div>
<div
className={`overflow-hidden max-h-[0px] transition-[max-height] ease-in-out ${expanded ? "max-h-[360px]" : ""}`}
>
<div
className={`bg-slate-600 rounded p-4 mt-1 max-w-0 ${expanded ? "max-w-full" : "transition-[max-width] delay-100"}`}
>
<code
className={`opacity-0 max-h-[100px] overflow-auto transition ease-in-out delay-150 ${expanded ? "opacity-100" : ""}`}
>
Tool Input:
<br></br>
<br></br>
{JSON.stringify(action.args)}
</code>
</div>
<div
className={`bg-slate-600 rounded p-4 mt-1 max-w-0 ${expanded ? "max-w-full" : "transition-[max-width] delay-100"}`}
>
<code
className={`opacity-0 max-h-[260px] overflow-auto transition ease-in-out delay-150 ${expanded ? "opacity-100" : ""}`}
>
{observation}
</code>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,540 @@
export default `# QA and Chat over Documents
Chat and Question-Answering (QA) over \`data\` are popular LLM use-cases.
\`data\` can include many things, including:
* \`Unstructured data\` (e.g., PDFs)
* \`Structured data\` (e.g., SQL)
* \`Code\` (e.g., Python)
Below we will review Chat and QA on \`Unstructured data\`.
![intro.png](/img/qa_intro.png)
\`Unstructured data\` can be loaded from many sources.
Check out the [document loader integrations here](/docs/modules/data_connection/document_loaders/) to browse the set of supported loaders.
Each loader returns data as a LangChain \`Document\`.
\`Documents\` are turned into a Chat or QA app following the general steps below:
* \`Splitting\`: [Text splitters](/docs/modules/data_connection/document_transformers/) break \`Documents\` into splits of specified size
* \`Storage\`: Storage (e.g., often a [vectorstore](/docs/modules/data_connection/vectorstores/)) will house [and often embed](https://www.pinecone.io/learn/vector-embeddings/) the splits
* \`Retrieval\`: The app retrieves splits from storage (e.g., often [with similar embeddings](https://www.pinecone.io/learn/k-nearest-neighbor/) to the input question)
* \`Output\`: An [LLM](/docs/modules/model_io/models/llms/) produces an answer using a prompt that includes the question and the retrieved splits
![flow.jpeg](/img/qa_flow.jpeg)
## Quickstart
Let's load this [blog post](https://lilianweng.github.io/posts/2023-06-23-agent/) on agents as an example \`Document\`.
We'll have a QA app in a few lines of code.
First, set environment variables and install packages required for the guide:
\`\`\`shell
> yarn add cheerio
# Or load env vars in your preferred way:
> export OPENAI_API_KEY="..."
\`\`\`
## 1. Loading, Splitting, Storage
### 1.1 Getting started
Specify a \`Document\` loader.
\`\`\`typescript
// Document loader
import { CheerioWebBaseLoader } from "langchain/document_loaders/web/cheerio";
const loader = new CheerioWebBaseLoader(
"https://lilianweng.github.io/posts/2023-06-23-agent/"
);
const data = await loader.load();
\`\`\`
Split the \`Document\` into chunks for embedding and vector storage.
\`\`\`typescript
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
const textSplitter = new RecursiveCharacterTextSplitter({
chunkSize: 500,
chunkOverlap: 0,
});
const splitDocs = await textSplitter.splitDocuments(data);
\`\`\`
Embed and store the splits in a vector database (for demo purposes we use an unoptimized, in-memory example but you can [browse integrations here](/docs/modules/data_connection/vectorstores/integrations/)):
\`\`\`typescript
import { OpenAIEmbeddings } from "langchain/embeddings/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
const embeddings = new OpenAIEmbeddings();
const vectorStore = await MemoryVectorStore.fromDocuments(splitDocs, embeddings);
\`\`\`
Here are the three pieces together:
![lc.png](/img/qa_data_load.png)
### 1.2 Going Deeper
#### 1.2.1 Integrations
\`Document Loaders\`
* Browse document loader integrations [here](/docs/modules/data_connection/document_loaders/).
* See further documentation on loaders [here](/docs/modules/data_connection/document_loaders/).
\`Document Transformers\`
* All can ingest loaded \`Documents\` and process them (e.g., split).
* See further documentation on transformers [here](/docs/modules/data_connection/document_transformers/).
\`Vectorstores\`
* Browse vectorstore integrations [here](/docs/modules/data_connection/vectorstores/integrations/).
* See further documentation on vectorstores [here](/docs/modules/data_connection/vectorstores/).
## 2. Retrieval
### 2.1 Getting started
Retrieve [relevant splits](https://www.pinecone.io/learn/what-is-similarity-search/) for any question using \`similarity_search\`.
\`\`\`typescript
const relevantDocs = await vectorStore.similaritySearch("What is task decomposition?");
console.log(relevantDocs.length);
// 4
\`\`\`
### 2.2 Going Deeper
#### 2.2.1 Retrieval
Vectorstores are commonly used for retrieval.
But, they are not the only option.
For example, SVMs (see thread [here](https://twitter.com/karpathy/status/1647025230546886658?s=20)) can also be used.
LangChain [has many retrievers and retrieval methods](/docs/modules/data_connection/retrievers/) including, but not limited to, vectorstores.
All retrievers implement some common methods, such as \`getRelevantDocuments()\`.
## 3. QA
### 3.1 Getting started
Distill the retrieved documents into an answer using an LLM (e.g., \`gpt-3.5-turbo\`) with \`RetrievalQA\` chain.
\`\`\`typescript
import { RetrievalQAChain } from "langchain/chains";
import { ChatOpenAI } from "langchain/chat_models/openai";
const model = new ChatOpenAI({ model: "gpt-3.5-turbo" });
const chain = RetrievalQAChain.fromLLM(model, vectorstore.asRetriever());
const response = await chain.call({
query: "What is task decomposition?"
});
console.log(response);
/*
{
text: 'Task decomposition refers to the process of breaking down a larger task into smaller, more manageable subgoals. By decomposing a task, it becomes easier for an agent or system to handle complex tasks efficiently. Task decomposition can be done through various methods such as using prompting or task-specific instructions, or through human inputs. It helps in planning and organizing the steps required to complete a task effectively.'
}
*/
\`\`\`
### 3.2 Going Deeper
#### 3.2.1 Integrations
\`LLMs\`
* Browse LLM integrations and further documentation [here](/docs/modules/model_io/models/).
#### 3.2.2 Customizing the prompt
The prompt in \`RetrievalQA\` chain can be customized as follows.
\`\`\`typescript
import { RetrievalQAChain } from "langchain/chains";
import { ChatOpenAI } from "langchain/chat_models/openai";
import { PromptTemplate } from "langchain/prompts";
const model = new ChatOpenAI({ model: "gpt-3.5-turbo" });
const template = \`Use the following pieces of context to answer the question at the end.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
Use three sentences maximum and keep the answer as concise as possible.
Always say "thanks for asking!" at the end of the answer.
{context}
Question: {question}
Helpful Answer:\`;
const chain = RetrievalQAChain.fromLLM(model, vectorstore.asRetriever(), {
prompt: PromptTemplate.fromTemplate(template),
});
const response = await chain.call({
query: "What is task decomposition?"
});
console.log(response);
/*
{
text: 'Task decomposition is the process of breaking down a large task into smaller, more manageable subgoals. This allows for efficient handling of complex tasks and aids in planning and organizing the steps needed to achieve the overall goal. Thanks for asking!'
}
*/
\`\`\`
#### 3.2.3 Returning source documents
The full set of retrieved documents used for answer distillation can be returned using \`return_source_documents=True\`.
\`\`\`typescript
import { RetrievalQAChain } from "langchain/chains";
import { ChatOpenAI } from "langchain/chat_models/openai";
const model = new ChatOpenAI({ model: "gpt-3.5-turbo" });
const chain = RetrievalQAChain.fromLLM(model, vectorstore.asRetriever(), {
returnSourceDocuments: true
});
const response = await chain.call({
query: "What is task decomposition?"
});
console.log(response.sourceDocuments[0]);
/*
Document {
pageContent: 'Task decomposition can be done (1) by LLM with simple prompting like "Steps for XYZ.\\n1.", "What are the subgoals for achieving XYZ?", (2) by using task-specific instructions; e.g. "Write a story outline." for writing a novel, or (3) with human inputs.',
metadata: [Object]
}
*/
\`\`\`
#### 3.2.4 Customizing retrieved docs in the LLM prompt
Retrieved documents can be fed to an LLM for answer distillation in a few different ways.
\`stuff\`, \`refine\`, and \`map-reduce\` chains for passing documents to an LLM prompt are well summarized [here](/docs/modules/chains/document/).
\`stuff\` is commonly used because it simply "stuffs" all retrieved documents into the prompt.
The [loadQAChain](/docs/modules/chains/document/) methods are easy ways to pass documents to an LLM using these various approaches.
\`\`\`typescript
import { loadQAStuffChain } from "langchain/chains";
const stuffChain = loadQAStuffChain(model);
const stuffResult = await stuffChain.call({
input_documents: relevantDocs,
question: "What is task decomposition
});
console.log(stuffResult);
/*
{
text: 'Task decomposition is the process of breaking down a large task into smaller, more manageable subgoals or steps. This allows for efficient handling of complex tasks by focusing on one subgoal at a time. Task decomposition can be done through various methods such as using simple prompting, task-specific instructions, or human inputs.'
}
*/
\`\`\`
## 4. Chat
### 4.1 Getting started
To keep chat history, we use a variant of the previous chain called a \`ConversationalRetrievalQAChain\`.
First, specify a \`Memory buffer\` to track the conversation inputs / outputs.
\`\`\`typescript
import { ConversationalRetrievalQAChain } from "langchain/chains";
import { BufferMemory } from "langchain/memory";
import { ChatOpenAI } from "langchain/chat_models/openai";
const memory = new BufferMemory({
memoryKey: "chat_history",
returnMessages: true,
});
\`\`\`
Next, we initialize and call the chain:
\`\`\`typescript
const model = new ChatOpenAI({ model: "gpt-3.5-turbo" });
const chain = ConversationalRetrievalQAChain.fromLLM(model, vectorstore.asRetriever(), {
memory
});
const result = await chain.call({
question: "What are some of the main ideas in self-reflection?"
});
console.log(result);
/*
{
text: 'Some main ideas in self-reflection include:\n' +
'\n' +
'1. Iterative Improvement: Self-reflection allows autonomous agents to improve by continuously refining past action decisions and correcting mistakes.\n' +
'\n' +
'2. Trial and Error: Self-reflection plays a crucial role in real-world tasks where trial and error are inevitable. It helps agents learn from failed trajectories and make adjustments for future actions.\n' +
'\n' +
'3. Constructive Criticism: Agents engage in constructive self-criticism of their big-picture behavior to identify areas for improvement.\n' +
'\n' +
'4. Decision and Strategy Refinement: Reflection on past decisions and strategies enables agents to refine their approach and make more informed choices.\n' +
'\n' +
'5. Efficiency and Optimization: Self-reflection encourages agents to be smart and efficient in their actions, aiming to complete tasks in the least number of steps.\n' +
'\n' +
'These ideas highlight the importance of self-reflection in enhancing performance and guiding future actions.'
}
*/
\`\`\`
The \`Memory buffer\` has context to resolve \`"it"\` ("self-reflection") in the below question.
\`\`\`typescript
const followupResult = await chain.call({
question: "How does the Reflexion paper handle it?"
});
console.log(followupResult);
/*
{
text: "The Reflexion paper introduces a framework that equips agents with dynamic memory and self-reflection capabilities to improve their reasoning skills. The approach involves showing the agent two-shot examples, where each example consists of a failed trajectory and an ideal reflection on how to guide future changes in the agent's plan. These reflections are then added to the agent's working memory as context for querying a language model. The agent uses this self-reflection information to make decisions on whether to start a new trial or continue with the current plan."
}
*/
\`\`\`
### 4.2 Going deeper
The [documentation](/docs/modules/chains/popular/chat_vector_db) on \`ConversationalRetrievalQAChain\` offers a few extensions, such as streaming and source documents.
# Conversational Retrieval Agents
This is an agent specifically optimized for doing retrieval when necessary while holding a conversation and being able
to answer questions based on previous dialogue in the conversation.
To start, we will set up the retriever we want to use, then turn it into a retriever tool. Next, we will use the high-level constructor for this type of agent.
Finally, we will walk through how to construct a conversational retrieval agent from components.
## The Retriever
To start, we need a retriever to use! The code here is mostly just example code. Feel free to use your own retriever and skip to the next section on creating a retriever tool.
\`\`\`typescript
import { FaissStore } from "langchain/vectorstores/faiss";
import { OpenAIEmbeddings } from "langchain/embeddings/openai";
import { TextLoader } from "langchain/document_loaders/fs/text";
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
const loader = new TextLoader("state_of_the_union.txt");
const docs = await loader.load();
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 0
});
const texts = await splitter.splitDocuments(docs);
const vectorStore = await FaissStore.fromDocuments(texts, new OpenAIEmbeddings());
const retriever = vectorStore.asRetriever();
\`\`\`
## Retriever Tool
Now we need to create a tool for our retriever. The main things we need to pass in are a \`name\` for the retriever as well as a \`description\`. These will both be used by the language model, so they should be informative.
\`\`\`typescript
import { createRetrieverTool } from "langchain/agents/toolkits";
const tool = createRetrieverTool(retriever, {
name: "search_state_of_union",
description: "Searches and returns documents regarding the state-of-the-union.",
});
\`\`\`
## Agent Constructor
Here, we will use the high level \`create_conversational_retrieval_agent\` API to construct the agent.
Notice that beside the list of tools, the only thing we need to pass in is a language model to use.
Under the hood, this agent is using the OpenAIFunctionsAgent, so we need to use an ChatOpenAI model.
\`\`\`typescript
import { createConversationalRetrievalAgent } from "langchain/agents/toolkits";
import { ChatOpenAI } from "langchain/chat_models/openai";
const model = new ChatOpenAI({
temperature: 0,
});
const executor = await createConversationalRetrievalAgent(model, [tool], {
verbose: true,
});
\`\`\`
We can now try it out!
\`\`\`typescript
const result = await executor.call({
input: "Hi, I'm Bob!"
});
console.log(result);
/*
{
output: 'Hello Bob! How can I assist you today?',
intermediateSteps: []
}
*/
const result2 = await executor.call({
input: "What's my name?"
});
console.log(result2);
/*
{ output: 'Your name is Bob.', intermediateSteps: [] }
*/
const result3 = await executor.call({
input: "What did the president say about Ketanji Brown Jackson in the most recent state of the union?"
});
console.log(result3);
/*
{
output: "In the most recent state of the union, President Biden mentioned Ketanji Brown Jackson. He nominated her as a Circuit Court of Appeals judge and described her as one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. He mentioned that she has received a broad range of support, including from the Fraternal Order of Police and former judges appointed by Democrats and Republicans.",
intermediateSteps: [
{...}
]
}
*/
const result4 = await executor.call({
input: "How long ago did he nominate her?"
});
console.log(result4);
/*
{
output: 'President Biden nominated Ketanji Brown Jackson four days before the most recent state of the union address.',
intermediateSteps: []
}
*/
\`\`\`
Note that for the final call, the agent used previously retrieved information to answer the query and did not need to call the tool again!
Here's a trace showing how the agent fetches documents to answer the question with the retrieval tool:
https://smith.langchain.com/public/1e2b1887-ca44-4210-913b-a69c1b8a8e7e/r
## Creating from components
What actually is going on underneath the hood? Let's take a look so we can understand how to modify things going forward.
### Memory
In this example, we want the agent to remember not only previous conversations, but also previous intermediate steps.
For that, we can use \`OpenAIAgentTokenBufferMemory\`. Note that if you want to change whether the agent remembers intermediate steps,
how the long the retained buffer is, or anything like that you should change this part.
\`\`\`typescript
import { OpenAIAgentTokenBufferMemory } from "langchain/agents/toolkits";
const memory = new OpenAIAgentTokenBufferMemory({
llm: model,
memoryKey: "chat_history",
outputKey: "output"
});
\`\`\`
You should make sure \`memoryKey\` is set to \`"chat_history"\` and \`outputKey\` is set to \`"output"\` for the OpenAI functions agent.
This memory also has \`returnMessages\` set to \`true\` by default.
You can also load messages from prior conversations into this memory by initializing it with a pre-loaded chat history:
\`\`\`typescript
import { ChatOpenAI } from "langchain/chat_models/openai";
import { OpenAIAgentTokenBufferMemory } from "langchain/agents/toolkits";
import { HumanMessage, AIMessage } from "langchain/schema";
import { ChatMessageHistory } from "langchain/memory";
const previousMessages = [
new HumanMessage("My name is Bob"),
new AIMessage("Nice to meet you, Bob!"),
];
const chatHistory = new ChatMessageHistory(previousMessages);
const memory = new OpenAIAgentTokenBufferMemory({
llm: new ChatOpenAI({}),
memoryKey: "chat_history",
outputKey: "output",
chatHistory,
});
\`\`\`
### Agent executor
We can recreate the agent executor directly with the \`initializeAgentExecutorWithOptions\` method.
This allows us to customize the agent's system message by passing in a \`prefix\` into \`agentArgs\`.
Importantly, we must pass in \`return_intermediate_steps: true\` since we are recording that with our memory object.
\`\`\`typescript
import { initializeAgentExecutorWithOptions } from "langchain/agents";
const executor = await initializeAgentExecutorWithOptions(tools, llm, {
agentType: "openai-functions",
memory,
returnIntermediateSteps: true,
agentArgs: {
prefix:
prefix ??
\`Do your best to answer the questions. Feel free to use any tools available to look up relevant information, only if necessary.\`,
},
});
\`\`\`
`;

View File

@@ -0,0 +1,4 @@
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer({})

View File

@@ -0,0 +1,47 @@
{
"name": "langchain-nextjs-template",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"format": "prettier --write \"app\""
},
"engines": {
"node": ">=18"
},
"dependencies": {
"@langchain/community": "^0.3.11",
"@langchain/core": "^0.3.17",
"@langchain/langgraph": "^0.2.20",
"@langchain/openai": "^0.3.11",
"@next/bundle-analyzer": "^13.4.19",
"@supabase/supabase-js": "^2.32.0",
"@tailwindcss/typography": "^0.5.15",
"@types/node": "20.12.12",
"@types/react": "18.3.2",
"@types/react-dom": "18.3.0",
"ai": "^3.1.12",
"autoprefixer": "10.4.14",
"eslint": "8.46.0",
"eslint-config-next": "13.4.12",
"isomorphic-dompurify": "^2.19.0",
"langchain": "^0.3.5",
"marked": "^15.0.4",
"next": "^14.2.3",
"postcss": "8.4.27",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-toastify": "^9.1.3",
"solana-agent-kit": "^1.3.0",
"tailwindcss": "3.3.3",
"typescript": "5.1.6",
"zod": "^3.22.3",
"zod-to-json-schema": "^3.21.4"
},
"devDependencies": {
"prettier": "3.0.0"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

View File

@@ -0,0 +1,18 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [require("@tailwindcss/typography")],
};

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

View File

@@ -0,0 +1,30 @@
import { marked } from "marked";
import DOMPurify from "isomorphic-dompurify";
interface MarkedOptions {
gfm: boolean;
breaks: boolean;
headerIds: boolean;
mangle: false;
highlight?: (code: string, lang: string) => string;
}
// Configure marked options
const markedOptions: MarkedOptions = {
gfm: true, // GitHub Flavored Markdown
breaks: true, // Convert \n to <br>
headerIds: true, // Add ids to headers
mangle: false, // Don't escape HTML
highlight: function (code: string, lang: string): string {
// You can add syntax highlighting here if needed
return code;
},
};
marked.setOptions(markedOptions);
// Basic markdown to HTML conversion with sanitization
export default function markdownToHtml(markdown: string) {
const rawHtml = marked.parse(markdown);
return DOMPurify.sanitize(rawHtml as string);
}

View File

@@ -1,6 +1,6 @@
{
"name": "solana-agent-kit",
"version": "1.3.1",
"version": "1.3.2",
"description": "connect any ai agents to solana protocols",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View File

@@ -71,6 +71,7 @@ import { BN } from "@coral-xyz/anchor";
* @property {Connection} connection - Solana RPC connection
* @property {Keypair} wallet - Wallet keypair for signing transactions
* @property {PublicKey} wallet_address - Public key of the wallet
* @property {Config} config - Configuration object
*/
export class SolanaAgentKit {
public connection: Connection;
@@ -78,15 +79,31 @@ export class SolanaAgentKit {
public wallet_address: PublicKey;
public config: Config;
/**
* @deprecated Using openai_api_key directly in constructor is deprecated.
* Please use the new constructor with Config object instead:
* @example
* const agent = new SolanaAgentKit(privateKey, rpcUrl, {
* OPENAI_API_KEY: 'your-key'
* });
*/
constructor(private_key: string, rpc_url: string, openai_api_key: string | null);
constructor(private_key: string, rpc_url: string, config: Config);
constructor(
private_key: string,
rpc_url = "https://api.mainnet-beta.solana.com",
config: Config,
rpc_url: string,
configOrKey: Config | string | null,
) {
this.connection = new Connection(rpc_url);
this.connection = new Connection(rpc_url || "https://api.mainnet-beta.solana.com");
this.wallet = Keypair.fromSecretKey(bs58.decode(private_key));
this.wallet_address = this.wallet.publicKey;
this.config = config;
// Handle both old and new patterns
if (typeof configOrKey === 'string' || configOrKey === null) {
this.config = { OPENAI_API_KEY: configOrKey || '' };
} else {
this.config = configOrKey;
}
}
// Tool methods

View File

@@ -52,7 +52,7 @@ async function initializeAgent() {
const solanaAgent = new SolanaAgentKit(
process.env.SOLANA_PRIVATE_KEY!,
process.env.RPC_URL,
process.env.RPC_URL!,
{
OPENAI_API_KEY: process.env.OPENAI_API_KEY!,
},