TronCode Tron CLI SDK 开发

概述

Tron SDK 提供编程接口,让你在代码中集成 Tron 能力,构建基于 AI 的自动化工具、工作流引擎或内嵌 AI 功能的应用程序。无论是 Node.js 后端服务还是 Python 脚本,都能通过 SDK 直接与 Tron 交互。

SDK 支持同步调用和流式响应,内置会话管理、工具调用和文件操作等核心能力。

安装 SDK

根据你的技术栈选择对应的 SDK:

Node.js
npm install @troncode/sdk
Python
pip install troncode-sdk

Node.js 示例

以下示例展示如何在 Node.js 中使用 SDK 创建客户端、发送消息并处理响应:

javascript
import { TronClient } from '@troncode/sdk';

// 创建客户端实例
const client = new TronClient({
  apiKey: process.env.TRONCODE_API_KEY,
  model: 'claude-opus-4-6',
  workdir: process.cwd(),
});

// 发送消息,获取完整响应
const response = await client.chat({
  message: '分析这个项目的代码结构,给出优化建议',
  sessionId: 'my-session',
});

console.log(response.content);
console.log(`使用 Token: ${response.usage.totalTokens}`);

Python 示例

Python SDK 提供同等功能,接口设计保持一致:

python
import os
from troncode_sdk import TronClient

# 创建客户端实例
client = TronClient(
    api_key=os.environ["TRONCODE_API_KEY"],
    model="claude-opus-4-6",
    workdir=os.getcwd(),
)

# 发送消息,获取完整响应
response = client.chat(
    message="分析这个项目的代码结构,给出优化建议",
    session_id="my-session",
)

print(response.content)
print(f"使用 Token: {response.usage.total_tokens}")

流式响应

对于长响应,推荐使用流式模式,可以更快地展示给用户:

javascript
// Node.js 流式响应示例(async iterator)
const stream = client.stream({
  message: '为 auth.ts 添加完整的 JWT 刷新逻辑',
  sessionId: 'my-session',
});

for await (const chunk of stream) {
  if (chunk.type === 'text') {
    process.stdout.write(chunk.delta);
  } else if (chunk.type === 'tool_call') {
    console.log(`\n[工具调用] ${chunk.tool}: ${chunk.input}`);
  } else if (chunk.type === 'done') {
    console.log(`\n完成,共 ${chunk.usage.totalTokens} tokens`);
  }
}
python
# Python 流式响应示例(async generator)
import asyncio

async def main():
    async for chunk in client.stream(
        message="为 auth.py 添加完整的 JWT 刷新逻辑",
        session_id="my-session",
    ):
        if chunk.type == "text":
            print(chunk.delta, end="", flush=True)
        elif chunk.type == "done":
            print(f"\n完成,共 {chunk.usage.total_tokens} tokens")

asyncio.run(main())

文件操作

通过 SDK 可以让 Tron 读写文件,使用 executeTool 方法直接调用 Tron 内置工具:

javascript
// 读取文件内容
const fileContent = await client.executeTool('read_file', {
  path: 'src/api/auth.ts',
});

// 写入文件
await client.executeTool('write_file', {
  path: 'src/api/auth.ts',
  content: updatedContent,
});

// 列出目录内容
const files = await client.executeTool('list_directory', {
  path: 'src/',
  recursive: true,
});

// 执行 shell 命令
const result = await client.executeTool('bash', {
  command: 'npm test',
  timeout: 60000,
});
💡
完整文档

SDK 完整 API 参考和更多示例请访问 docs.troncode.cn/sdk