Step 04
SDK deep dive
Build custom agent workflows with the TypeScript, Python, and Go SDKs.
SDK overview
Nexus provides first-party SDKs for TypeScript, Python, and Go. All three SDKs implement the same core API with native typing, comprehensive documentation, and full support for all platform features. Choose the language that fits your stack.
TypeScript SDK
Install via npm:
npm install @nexus/sdk
Basic usage:
import { Nexus } from "@nexus/sdk";
const nexus = new Nexus({ apiKey: "nk_..." });
const agent = await nexus.agents.deploy({
name: "architect",
repo: "org/backend",
model: "nexus-1"
});
const result = await agent.ask(
"Refactor the auth module to use role-based access"
);
console.log(result.plan);Python SDK
Install via pip:
pip install nexus-sdk
Basic usage:
from nexus import Nexus
nexus = Nexus(api_key="nk_...")
agent = nexus.deploy_agent(
name="architect",
repo="org/backend"
)
result = agent.ask(
"Find all deprecated API endpoints"
)
print(result.summary)Core API concepts
All SDKs share five core operations: agents.deploy creates a new agent; agents.ask assigns a task; agents.status checks progress; agents.logs retrieves reasoning traces; and agents.stop terminates an agent. Each operation returns typed response objects with full metadata.
Webhooks and events
For asynchronous workflows, agents emit events that you can subscribe to via webhooks:
const webhook = await nexus.webhooks.create({
url: "https://my-app.com/nexus-events",
events: ["task.completed", "plan.ready_for_review"]
});Events include full payload data, making it easy to build custom dashboards, notification systems, or approval workflows.
Go SDK
The Go SDK provides the same core API with Go-native types and idioms. Install with:
go get github.com/nexus-ai/go-sdk
Basic usage:
import "github.com/nexus-ai/go-sdk/nexus"
func main() {
client := nexus.NewClient("nk_...")
agent, err := client.DeployAgent("architect", "org/backend")
if err != nil { log.Fatal(err) }
result, err := agent.Ask(ctx, "Refactor auth module")
if err != nil { log.Fatal(err) }
fmt.Println(result.Plan)
}Error handling patterns
SDK operations can fail in several ways. Here are the common error types and how to handle them. Authentication errors (NexusAuthError): your API key is invalid or expired. Check the key and regenerate if needed. Rate limit errors (NexusRateLimitError): you exceeded the API rate limit. Implement exponential backoff: wait 1s, 2s, 4s, 8s between retries. The SDK includes automatic retry with configurable backoff. Validation errors (NexusValidationError): the task or agent configuration is invalid. The error message includes the specific field that failed validation. Agent errors (NexusAgentError): the agent encountered an error during task execution. Check the agent logs for details. Timeout errors (NexusTimeoutError): the task exceeded the maximum execution time. Consider breaking the task into smaller subtasks.
Recommended error handling pattern in TypeScript:
try {
const result = await agent.ask(task);
console.log(result.summary);
} catch (err) {
if (err instanceof NexusRateLimitError) {
await delay(1000 * Math.pow(2, err.retryCount));
return retry();
}
if (err instanceof NexusAgentError) {
const logs = await agent.logs();
console.error("Agent failed:", logs.reasoningTrace);
}
throw err;
}Advanced SDK features
Beyond the five core operations, the SDK supports: Streaming responses ? receive agent output token-by-token for real-time display. Batch operations ? submit multiple tasks in parallel with agents.askBatch(tasks[]). Custom tools ? register your own tools with typed schemas. Webhook subscriptions ? receive asynchronous event notifications. Agent teams ? deploy and coordinate multiple agents programmatically.
Example: streaming agent output in TypeScript:
const stream = await agent.askStream("Refactor auth module");
for await (const chunk of stream) {
process.stdout.write(chunk.text);
if (chunk.toolCall) {
console.log("\n[Tool:", chunk.toolCall.name, "]");
}
}Authentication and security
All SDK calls are authenticated via API key. Best practices for API key management: (1) Never hardcode API keys ? use environment variables. The SDK automatically reads from NEXUS_API_KEY environment variable. (2) Use API key rotation ? rotate keys every 90 days. The SDK supports key rotation without downtime: set both NEXUS_API_KEY and NEXUS_API_KEY_NEXT during the rotation window. (3) Scope API keys ? create keys with minimum necessary permissions (read-only, specific agent types, specific environments).
Example: secure API key loading in TypeScript:
import { Nexus } from "@nexus/sdk";
import { config } from "dotenv";
config();
const nexus = new Nexus({
apiKey: process.env.NEXUS_API_KEY,
// Optional: specify environment
environment: process.env.NODE_ENV || "development",
// Optional: set timeout
timeout: 30000,
});Building custom integrations
The SDK'''s webhook system enables building custom integrations. Supported event types: task.created ? fired when a task is assigned to an agent. task.completed ? fired when an agent completes a task (includes result summary). plan.ready_for_review ? fired when an agent produces a plan that requires human approval. agent.error ? fired when an agent encounters a non-recoverable error. memory.consolidated ? fired when the memory system consolidates new long-term knowledge.
Example: building a Slack integration:
const webhook = await nexus.webhooks.create({
url: "https://hooks.slack.com/services/T.../B.../xxx",
events: ["task.completed", "plan.ready_for_review"],
secret: process.env.WEBHOOK_SECRET,
});
// Verify webhook signature on receiving end
function verifyWebhook(payload, signature, secret) {
const hmac = crypto.createHmac("sha256", secret);
hmac.update(JSON.stringify(payload));
return hmac.digest("hex") === signature;
}Next steps
With the SDK integrated, proceed to Step 5: Memory & persistence to learn how agents learn across sessions.