NEAR AI TS is a TypeScript implementation of the NEAR AI Agent Platform, consisting of a CLI package (@jutsuai/nearai-ts-cli) and a Core SDK (@jutsuai/nearai-ts-core) for building intelligent agents.
- Installation
- CLI Commands
- Creating Your First Agent
- Building a RAG System
- Agent SDK Reference
- Running Agents
- Authentication
- Advanced Usage
- Node.js (v16 or later)
- npm (v7 or later)
To install the NEAR AI TS CLI globally:
# Install globally
npm install -g @jutsuai/nearai-ts-cli
# The CLI is available as the command 'nearai-ts'
nearai-ts --versionThe NEAR AI TS CLI provides several commands:
# Create a new agent
nearai-ts create <agent-name>
# Run an agent
nearai-ts run <agent-path> [config-json]
# Upload an agent to NEAR AI platform
nearai-ts upload <agent-path>
# Login to NEAR AI platform
nearai-ts login
# Display help information
nearai-ts help# Create a new agent project
nearai-ts create my-agent
# Navigate to the agent directory
cd my-agentThis creates a project structure with the basic agent implementation.
A minimal agent in TypeScript looks like this:
import { Agent, AgentConfig } from '@jutsuai/nearai-ts-core';
export default async function myAgent(agent: Agent, agentConfig: AgentConfig) {
// Get user message
const userMessage = await agent.messages().lastUser();
// Build chain of messages
return await agent
.system("You are a helpful assistant.")
.user(userMessage)
.run({ model: "llama-v3p1-70b-instruct" });
}Every generated agent folder contains a metadata.json file.
The NEAR AI platform reads this file when you upload or publish an agent, so keeping it accurate is important.
Example (the one generated by the CLI template):
{
"name": "example-agent-ts",
"version": "0.0.1",
"description": "This is a basic agent configuration template for TypeScript.",
"category": "agent",
"tags": [],
"details": {
"agent": {
"framework": "ts",
"defaults": {
"model": "llama-v3p1-70b-instruct",
"model_provider": "fireworks",
"model_temperature": 1.0,
"model_max_tokens": 16384
}
}
},
"show_entry": true
}| Field | Purpose |
|---|---|
name |
Unique slug for your agent in the Hub. |
version |
SemVer string. The CLI auto‑increments patch when you run nearai-ts upload. |
description |
Short summary visible in listings. |
category |
Usually "agent"; could be "tool" or others in future. |
tags |
Search keywords, e.g. ["rag","typescript"]. |
details.agent.framework |
Must be "ts" for TypeScript agents. |
details.agent.defaults.* |
Default model settings the runtime should use if your code doesn’t override them. |
show_entry |
If false, the agent remains private / hidden in public catalogs. |
- Rename
nameto avoid collisions on upload. - Bump
versionwhen you make breaking updates (CLI handles patch bumps automatically). - Add
tagsto improve discoverability. - Adjust
defaultsif you prefer a different model or token budget.
NEAR AI TS can rapidly help with building RAGs that run on NEAR AI's platform.
Here's the template RAG implementation from the codebase:
import { Agent, AgentConfig } from '@jutsuai/nearai-ts-core';
export default async function myRagAgent(agent: Agent, agentConfig: AgentConfig) {
let vectorStoreId: any = "myVectorStore";
// Attempt to find an existing store named "myVectorStore"
let vectorStore = await agent.vectors().find(vectorStoreId);
// Create vector store with a dummy file if it doesn't exist
if (!vectorStore) {
const dummyContent = "I stand before you with unwavering faith in the collective power of humanity...";
const uploadedFile = await agent.files().upload(
dummyContent,
'assistants',
);
// Create a new vector store with the uploaded file
vectorStore = await agent.vectors().create(
'myVectorStore',
[uploadedFile.id],
);
}
vectorStoreId = vectorStore.id;
// Query the vector store with the user's message
const userMessage = await agent.messages().lastUser() || "No user message found.";
const results = await agent.vectors().query(vectorStoreId as string, userMessage, true);
const context = results.map((r: any) => r.file_content).join('\n');
// Provide the retrieved context + user message to the model
return await agent
.system(`You are a helpful RAG assistant. Below is context from our knowledge base:\n${context}`)
.user(userMessage)
.run({ model: "llama-v3p1-70b-instruct" });
}To create a RAG agent:
-
Create a new agent project:
nearai-ts create my-rag-agent
-
Use the RAG template as a starting point (or you can copy the code above):
# Copy the RAG template cp node_modules/@jutsuai/nearai-ts-cli/dist/template/agent.rag.ts ./my-rag-agent.ts -
Customize the RAG agent to use your own documents:
// Example of adding your own documents to the vector store const documents = [ "Document 1 content here...", "Document 2 content here...", "Document 3 content here..." ]; // Upload each document and collect file IDs const fileIds = []; for (const doc of documents) { const file = await agent.files().upload(doc, 'assistants'); fileIds.push(file.id); } // Create or update vector store with your documents const vectorStore = await agent.vectors().create('myKnowledgeBase', fileIds);
The NEAR AI TS Core SDK provides a comprehensive API for building agents.
import { Agent, AgentConfig } from '@jutsuai/nearai-ts-core';
// Create an agent with configuration
const agent = new Agent({
auth: {}, // Authentication credentials
baseUrl: "https://api.near.ai/v1", // API endpoint
threadId: "thread_xyz", // Thread ID for conversation
envVars: {} // Environment variables
});The Agent class provides chainable methods for building conversations:
// Add a system message (instructions for the agent)
agent.system("You are a helpful assistant.");
// Add a user message
agent.user("What's the weather like today?");
// Add an assistant message
agent.assistant("I don't have access to real-time weather data.");
// Run the agent to generate a response
const response = await agent.run({
model: "llama-v3p1-70b-instruct", // LLM model to use
maxTokens: 4000, // Maximum length of the response
temperature: 0.7, // Randomness of the response
tools: [], // Optional tools the agent can use
stream: false // Whether to stream the response
});// Get messages from the thread
const messages = await agent.messages().list();
// Add a message to the thread
await agent.messages().add("Hello there!", "assistant");
// Get the last user message
const lastUserMsg = await agent.messages().lastUser();
// Get the last assistant message
const lastAssistantMsg = await agent.messages().lastAssistant();// Read a file
const content = await agent.files().read("document.txt");
// Write a file
await agent.files().write("output.txt", "File content");
// Upload a file to the platform
const file = await agent.files().upload("File content", "assistants");// Find a vector store by ID or name
const store = await agent.vectors().find("myVectorStore");
// Query a vector store
const results = await agent.vectors().query(
"vs_123abc", // Vector store ID
"What is machine learning?", // Query text
true // Whether to include full file content
);
// Add a file to a vector store
await agent.vectors().addFile("vs_123abc", "file_456");
// Create a new vector store
const newStore = await agent.vectors().create(
"myVectorStore", // Name
["file_123", "file_456"], // File IDs
undefined, // Expiration
undefined, // Chunking strategy
{ custom: "metadata" } // Optional metadata
);// Get the agent's environment
const env = agent.getEnvironment();
// Get the raw client for advanced operations
const client = agent.raw();
// Generate a completion directly
const completion = await agent.completions().generate([
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello" }
], "llama-v3p1-70b-instruct");# Run an agent locally
nearai-ts run ./my-agent.ts
# Run with a specific config
nearai-ts run ./my-agent.ts '{"auth": {...}}'
# Run with local API server (for development)
nearai-ts run ./my-agent.ts --localWhen you run an agent, the NEAR AI TS runner:
- Loads your agent file (transpiling TypeScript to JavaScript if needed)
- Loads configuration from the command line or
~/.nearai/config.json - Initializes the environment
- Calls your agent's default export function
NEAR AI TS requires authentication to interact with the platform (before you can run or upload agents).
The easiest way to authenticate is using the CLI:
nearai-ts loginThis will guide you through the login process and store your credentials in ~/.nearai/config.json.
The authentication credentials are stored in a JSON file:
{
"auth": {
"account_id": "your_account_id",
"signature": "your_signature",
"public_key": "your_public_key",
"nonce": "your_nonce",
"recipient": "your_recipient",
"message": "your_message",
"on_behalf_of": null
}
}You can also provide auth credentials in your code:
const agent = new Agent({
auth: {
account_id: "your_account_id",
signature: "your_signature",
public_key: "your_public_key",
// Other required fields
}
});You can work with specific conversation threads:
// Create an agent with a specific thread ID
const agent = new Agent({
threadId: "thread_xyz"
});
// Access messages from a specific thread
const messages = await agent.messages("thread_abc").list();Proper error handling is essential:
try {
const response = await agent.run();
console.log("Response:", response);
} catch (error) {
console.error("Error running agent:", error);
// Check for specific error types
if (error.status === 401) {
console.error("Authentication failed - please log in again");
} else if (error.status === 404) {
console.error("Resource not found");
}
}You can pass environment variables to your agent:
const agent = new Agent({
envVars: {
API_KEY: process.env.THIRD_PARTY_API_KEY,
DEBUG: "true"
}
});Example of using NEAR AI TS in an Express application:
import express from 'express';
import { Agent } from '@jutsuai/nearai-ts-core';
const app = express();
app.use(express.json());
// Create a single agent instance
const agent = new Agent({
// Load auth from secure environment variable
auth: JSON.parse(process.env.NEAR_AI_AUTH || '{}')
});
app.post('/chat', async (req, res) => {
try {
const { message } = req.body;
// Process the message
const response = await agent
.system("You are a helpful assistant.")
.user(message)
.run();
res.json({ response });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Once you've developed and tested your agents, you can publish them:
# Upload your agent to NEAR AI
nearai-ts upload ./my-agent.tsThis will:
- Package your agent code
- Upload it to the NEAR AI platform
- Make it available for deployment and integration
NEAR AI TS provides a powerful TypeScript framework for building, testing, and deploying AI agents. By leveraging the CLI and SDK, you can quickly create sophisticated agents with features like conversation management, RAG capabilities, and vector store integration.
For more information:
- Check the GitHub repository: github.com/jutsuai/nearai-ts
- Install the packages: @jutsuai/nearai-ts-cli and @jutsuai/nearai-ts-core