LangChain

Integrate AiMo Network with LangChain for building AI workflows

Integrate AiMo Network with LangChain for building complex AI workflows, chains, and agents using decentralized AI models.

Authentication Update: AiMo Network uses wallet-based SIWx authentication. You have three options:

  1. AiMo CLI (simplest) - See AI Agent Guide
  2. AiMo TypeScript SDK with Vercel AI SDK (recommended for LangChain.js) - See below
  3. Manual SIWx (advanced) - See advanced setup section below

For most LangChain use cases, the CLI provides the simplest integration:

# Install CLI
curl -fsSL https://aimo-cli-releases.s3.ap-northeast-1.amazonaws.com/install.sh | sh

# Generate keypair
aimo keygen

# Use with any model
aimo chat --model deepseek/deepseek-v3.2 --message "Hello, AI!"

Alternative: Use AiMo SDK with Vercel AI SDK

For LangChain.js applications, you can use the AiMo provider with Vercel AI SDK:

npm install @aimo.network/client @aimo.network/svm @aimo.network/provider ai langchain
import { ChatLanguageModel } from "@langchain/core/language_models/chat_models";
import { AIMessage, BaseMessage, HumanMessage } from "@langchain/core/messages";
import { aimoNetwork } from "@aimo.network/provider";
import { SvmClientSigner, SOLANA_MAINNET_CHAIN_ID } from "@aimo.network/svm";
import { createKeyPairSignerFromBytes } from "@solana/kit";
import { streamText } from "ai";
import bs58 from "bs58";
import fs from "fs";

// Load keypair
const keypairData = JSON.parse(
  fs.readFileSync(process.env.HOME + "/.config/aimo/keypair.json", "utf-8")
);

const privateKeyBytes = new Uint8Array(keypairData);
const keypairSigner = await createKeyPairSignerFromBytes(privateKeyBytes);

// Create signer
const signer = new SvmClientSigner({
  signer: keypairSigner,
  chainId: SOLANA_MAINNET_CHAIN_ID,
});

// Create AiMo provider
const aimo = aimoNetwork({
  signer,
  baseURL: "https://beta.aimo.network",
});

// Use with Vercel AI SDK
const result = await streamText({
  model: aimo.chat("deepseek/deepseek-v3.2"),
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "What is AiMo Network?" }
  ],
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}

See the SDK Reference for complete documentation.

Installation

For programmatic LangChain usage:

pip install langchain-openai langchain-core
npm install @langchain/openai @langchain/core

Advanced Setup

LangChain with AiMo requires custom SIWx authentication:

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
import json
import base64
from datetime import datetime, timedelta
from nacl.signing import SigningKey

# Load keypair and generate SIWx signature (see AI Agent Guide)
def generate_siwx_header(keypair_path, domain="beta.aimo.network"):
    with open(keypair_path) as f:
        keypair_data = json.load(f)
        secret_key = bytes(keypair_data[:32])
        signing_key = SigningKey(secret_key)
    
    issued_at = datetime.utcnow().isoformat() + "Z"
    expiration_time = (datetime.utcnow() + timedelta(minutes=5)).isoformat() + "Z"
    
    chain_id = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
    address = signing_key.verify_key.encode().hex()
    
    message = f"""{domain} wants you to sign in with your account:
{chain_id}:{address}

URI: https://{domain}
Version: 1
Chain ID: {chain_id}
Nonce: {int(datetime.utcnow().timestamp())}
Issued At: {issued_at}
Expiration Time: {expiration_time}"""
    
    signature = signing_key.sign(message.encode()).signature
    
    payload = {
        "message": message,
        "signature": base64.b58encode(signature).decode()
    }
    
    return base64.b64encode(json.dumps(payload).encode()).decode()

# Configure for AiMo Network
llm = ChatOpenAI(
    api_key="not-used",
    base_url="https://beta.aimo.network/api/v1",
    model="deepseek/deepseek-v3.2",
    default_headers={
        "Sign-In-With-X": generate_siwx_header("~/.config/aimo/keypair.json")
    }
)

# Simple chat
messages = [
    SystemMessage(content="You are a helpful assistant."),
    HumanMessage(content="Hello, how are you?")
]

response = llm.invoke(messages)
print(response.content)
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import * as ed25519 from "@noble/ed25519";
import * as fs from "fs";

// Load keypair and generate SIWx signature (see AI Agent Guide)
async function generateSiwxHeader(keypairPath, domain = "beta.aimo.network") {
  const keypairData = JSON.parse(fs.readFileSync(keypairPath, "utf-8"));
  const secretKey = new Uint8Array(keypairData.slice(0, 32));
  const publicKey = await ed25519.getPublicKeyAsync(secretKey);
  
  const issuedAt = new Date().toISOString();
  const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();
  
  const chainId = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
  const address = Buffer.from(publicKey).toString("hex");
  
  const message = `${domain} wants you to sign in with your account:
${chainId}:${address}

URI: https://${domain}
Version: 1
Chain ID: ${chainId}
Nonce: ${Math.floor(Date.now() / 1000)}
Issued At: ${issuedAt}
Expiration Time: ${expirationTime}`;
  
  const signature = await ed25519.signAsync(Buffer.from(message), secretKey);
  
  const payload = {
    message,
    signature: Buffer.from(signature).toString("base64")
  };
  
  return Buffer.from(JSON.stringify(payload)).toString("base64");
}

// Configure for AiMo Network
const siwxHeader = await generateSiwxHeader("~/.config/aimo/keypair.json");

const llm = new ChatOpenAI({
  apiKey: "not-used",
  model: "deepseek/deepseek-v3.2",
  configuration: {
    baseURL: "https://beta.aimo.network/api/v1",
    defaultHeaders: {
      "Sign-In-With-X": siwxHeader
    }
  }
});

// Simple chat
const messages = [
  new SystemMessage("You are a helpful assistant."),
  new HumanMessage("Hello, how are you?")
];

const response = await llm.invoke(messages);
console.log(response.content);

Chains and Prompts

from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain

# Create a prompt template
template = """Question: {question}
Answer: Let's think step by step."""

prompt = PromptTemplate(
    template=template,
    input_variables=["question"]
)

# Create chain
chain = LLMChain(prompt=prompt, llm=llm)

# Use the chain
question = "What are the benefits of decentralized AI?"
result = chain.run(question)
print(result)
import { PromptTemplate } from "@langchain/core/prompts";
import { LLMChain } from "langchain/chains";

// Create a prompt template
const template = `Question: {question}
Answer: Let's think step by step.`;

const prompt = new PromptTemplate({
  template: template,
  inputVariables: ["question"]
});

// Create chain
const chain = new LLMChain({ llm: llm, prompt: prompt });

// Use the chain
const question = "What are the benefits of decentralized AI?";
const result = await chain.call({ question: question });
console.log(result.text);

Streaming Responses

# Streaming with LangChain
for chunk in llm.stream(messages):
    print(chunk.content, end="", flush=True)
// Streaming with LangChain
const stream = await llm.stream(messages);
for await (const chunk of stream) {
  process.stdout.write(chunk.content);
}

Advanced Usage

Building Complex Chains

LangChain allows you to build sophisticated AI workflows by chaining multiple operations together. With AiMo Network, you can leverage decentralized models in these chains.

Agent Integration

LangChain agents can use AiMo Network models as their reasoning engine, enabling decentralized AI-powered decision making.

Memory and Context

LangChain's memory capabilities work seamlessly with AiMo Network models, allowing you to maintain conversation context across multiple interactions.

On this page