Build Your First AxonFlow Agent in 10 Minutes
Build a production-ready AI agent with policy enforcement - No ML experience required.
What You'll Build
A simple AI agent that:
- Accepts natural language queries
- Enforces policy rules before execution
- Returns governed responses
- Logs all activity for audit compliance
Time to complete: 10 minutes Difficulty: Beginner Prerequisites: AxonFlow deployed (see Getting Started)
Overview
This tutorial walks you through creating your first AI agent using AxonFlow. By the end, you'll have a working agent that enforces policies and logs all activity.
What You'll Learn
- Installing the AxonFlow SDK
- Configuring your client
- Creating your first policy
- Sending queries to your agent
- Viewing audit logs
Prerequisites
Before starting, ensure you have:
-
AxonFlow Deployed
- Follow the Getting Started Guide to deploy via AWS Marketplace
- Retrieve your Agent Endpoint from CloudFormation Outputs
-
License Key
- Get your license key from CloudFormation Outputs
- Format:
AXON-V2-{base64}-{signature}
-
Development Environment
- Node.js 18+ OR Go 1.21+
- Text editor (VS Code, Sublime, etc.)
- Terminal access
-
AWS CLI (Optional)
- For viewing CloudWatch logs
- Installation:
pip install awscli
Step 1: Install the SDK (2 minutes)
Choose your preferred language:
TypeScript / JavaScript
# Create a new project directory
mkdir my-first-agent
cd my-first-agent
# Initialize npm project
npm init -y
# Install AxonFlow SDK
npm install @axonflow/sdk
# Install TypeScript (if using TypeScript)
npm install --save-dev typescript @types/node
npx tsc --init
Go
# Create a new project directory
mkdir my-first-agent
cd my-first-agent
# Initialize Go module
go mod init my-first-agent
# Install AxonFlow SDK
go get github.com/getaxonflow/axonflow-sdk-go
Step 2: Configure Your Client (2 minutes)
Create a configuration file for your AxonFlow connection.
TypeScript
Create index.ts:
import { AxonFlow } from '@axonflow/sdk';
// Initialize AxonFlow client
const axonflow = new AxonFlow({
endpoint: 'https://YOUR_AGENT_ENDPOINT', // Agent runs on port 8080
licenseKey: 'YOUR_LICENSE_KEY',
tenant: 'my-org',
debug: true // Enable debug logging in development
});
async function main() {
try {
// Test connection
const health = await axonflow.healthCheck();
console.log('✅ Connected to AxonFlow:', health);
} catch (error) {
console.error('❌ Connection failed:', error);
}
}
main();
Go
Create main.go:
package main
import (
"fmt"
"log"
"github.com/getaxonflow/axonflow-sdk-go"
)
func main() {
// Initialize AxonFlow client
client := axonflow.NewClient(axonflow.AxonFlowConfig{
AgentURL: "https://YOUR_AGENT_ENDPOINT", // Agent runs on port 8080
ClientID: "my-org",
ClientSecret: "YOUR_CLIENT_SECRET",
LicenseKey: "YOUR_LICENSE_KEY",
Debug: true, // Enable debug logging in development
})
// Test connection
if err := client.HealthCheck(); err != nil {
log.Fatal("Connection failed:", err)
}
fmt.Println("✅ Connected to AxonFlow")
}
Configuration Notes:
- Replace
YOUR_AGENT_ENDPOINTwith your actual endpoint (Agent runs on port 8080) - Replace
YOUR_LICENSE_KEYwith your license key - Replace
YOUR_CLIENT_SECRETwith your client secret (Go SDK) debug: trueis for development only (disable in production)
Run it:
# TypeScript
npx ts-node index.ts
# Go
go run main.go
Expected Output:
✅ Connected to AxonFlow: { status: 'healthy', version: '1.0.12' }
Step 3: Understanding Policies (3 minutes)
Policies define what your AI agent can and cannot do. In AxonFlow, policies are configured server-side in the Agent, not sent with each request.
How Policies Work
- Server-Side Configuration - Policies are deployed to your AxonFlow Agent via configuration files or the API
- Automatic Evaluation - Every SDK request is automatically evaluated against your configured policies
- Audit Logging - All policy decisions are automatically logged for compliance
Default Policy Behavior
By default, AxonFlow includes a permissive policy that:
- Allows all queries
- Logs all decisions for audit trail
- Checks for common security violations (SQL injection, prompt injection)
Example Policy (Rego)
Policies use Open Policy Agent (OPA) Rego syntax:
package axonflow.policy
# Allow all queries by default
default allow = true
# Block queries containing sensitive patterns
deny {
contains(input.query, "password")
}
deny {
contains(input.query, "credit card")
}
# Final decision
allow = false {
deny
}
Note: Policy configuration is covered in detail in the Policy-as-Code Guide. For this tutorial, the default policies are sufficient.
Step 4: Send Your First Query (2 minutes)
Now let's send a query to your agent with policy enforcement.
TypeScript
Update index.ts:
import { AxonFlow } from '@axonflow/sdk';
const axonflow = new AxonFlow({
endpoint: 'https://YOUR_AGENT_ENDPOINT', // Agent on port 8080
licenseKey: 'YOUR_LICENSE_KEY',
tenant: 'my-org',
debug: true
});
async function main() {
try {
// Send query with policy enforcement (Proxy Mode)
const response = await axonflow.executeQuery({
userToken: 'user-123',
query: 'What is the capital of France?',
requestType: 'llm_chat',
context: {
provider: 'openai',
model: 'gpt-4'
}
});
if (response.blocked) {
console.log('🚫 Blocked:', response.blockReason);
} else {
console.log('✅ Query Response:', response.data);
console.log('📊 Policy Info:', response.policyInfo);
}
} catch (error) {
console.error('❌ Query failed:', error);
}
}
main();
Note: Policies are configured server-side in AxonFlow Agent. The SDK sends queries that are automatically evaluated against your configured policies.
Go
Update main.go:
package main
import (
"fmt"
"log"
"github.com/getaxonflow/axonflow-sdk-go"
)
func main() {
client := axonflow.NewClient(axonflow.AxonFlowConfig{
AgentURL: "https://YOUR_AGENT_ENDPOINT", // Agent on port 8080
ClientID: "my-org",
ClientSecret: "YOUR_CLIENT_SECRET",
LicenseKey: "YOUR_LICENSE_KEY",
Debug: true,
})
// Send query with policy enforcement (Proxy Mode)
response, err := client.ExecuteQuery(
"user-123", // userToken
"What is the capital of France?", // query
"llm_chat", // requestType
map[string]interface{}{ // context
"provider": "openai",
"model": "gpt-4",
},
)
if err != nil {
log.Fatal("Query failed:", err)
}
if response.Blocked {
fmt.Println("🚫 Blocked:", response.BlockReason)
} else {
fmt.Println("✅ Query Response:", response.Data)
if response.PolicyInfo != nil {
fmt.Printf("📊 Policies evaluated: %v\n", response.PolicyInfo.PoliciesEvaluated)
fmt.Printf("⏱️ Processing time: %s\n", response.PolicyInfo.ProcessingTime)
}
}
}
Note: Policies are configured server-side in AxonFlow Agent. The SDK sends queries that are automatically evaluated against your configured policies.
Run Your Agent
# TypeScript
npx ts-node index.ts
# Go
go run main.go
Expected Output
✅ Query Response: The capital of France is Paris.
📊 Policies evaluated: [default-policy]
⏱️ Processing time: 4.2ms
What Just Happened?
- Query sent - "What is the capital of France?"
- Policy evaluated - AxonFlow checked server-side policies (single-digit ms!)
- Query allowed - Policy evaluation passed
- LLM routed - Request routed to configured LLM provider (OpenAI in this case)
- Response returned - Agent returned the LLM response
- Audit logged - All activity recorded in CloudWatch
Step 5: View Audit Logs (1 minute)
All queries are automatically logged to AWS CloudWatch for compliance and debugging.
View Logs in AWS Console
- Go to AWS CloudWatch Console
- Click Log Groups
- Find
/ecs/YOUR-STACK-NAME/agent - Click on the latest log stream
- Search for your query
View Logs via AWS CLI
aws logs tail /ecs/YOUR-STACK-NAME/agent --follow --region YOUR-REGION
Expected Log Entry
{
"timestamp": "2025-11-11T12:00:00Z",
"level": "info",
"message": "Query executed",
"query": "What is the capital of France?",
"policy_decision": "allow",
"latency_ms": 4,
"user_id": "user-123",
"organization_id": "my-org"
}
Congratulations! 🎉
You've successfully built your first AxonFlow agent! Here's what you accomplished:
- ✅ Installed the AxonFlow SDK
- ✅ Configured your client connection
- ✅ Created a policy for governance
- ✅ Sent a query with policy enforcement
- ✅ Viewed audit logs
What You Learned
- Sub-10ms Policy Enforcement - Your policy was evaluated in ~4ms
- Automatic Audit Logging - All activity is logged for compliance
- Policy-as-Code - Governance rules are versioned and testable
- Production-Ready - This agent can handle production traffic
Next Steps
Now that you have a working agent, explore these advanced topics:
1. Add LLM Integration
Connect your agent to AWS Bedrock, OpenAI, or Anthropic Claude:
// Proxy Mode - AxonFlow routes to your configured LLM
const response = await axonflow.executeQuery({
userToken: 'user-123',
query: 'Generate a product description for wireless headphones',
requestType: 'llm_chat',
context: {
provider: 'bedrock', // or 'openai', 'anthropic'
model: 'anthropic.claude-3-sonnet-20240229-v1:0'
}
});
📖 Learn more: LLM Providers
2. Connect to Your Database
Query your Snowflake, PostgreSQL, or Salesforce data with MCP connectors:
// Query an installed MCP connector
const response = await axonflow.queryConnector(
'snowflake', // connector name
'SELECT * FROM customers WHERE id = ?', // query
{ id: '12345' } // parameters
);
📖 Learn more: MCP Connectors
3. Implement Multi-Agent Planning (MAP)
Generate and execute multi-step plans:
// Generate a plan from natural language
const plan = await axonflow.generatePlan(
'Plan a trip to Paris with flights and hotels',
'travel' // domain hint
);
// Execute the plan
const result = await axonflow.executePlan(plan.planId);
console.log('Trip planned:', result.result);
📖 Learn more: Multi-Agent Planning
4. Deploy to Production
Learn best practices for production deployments:
# Multi-AZ setup
# Auto-scaling configuration
# Monitoring and alerting
# Backup and disaster recovery
📖 Learn more: AWS Marketplace Deployment
Troubleshooting
Connection Failed
Error: ECONNREFUSED or Connection timeout
Solutions:
- Verify your Agent Endpoint is correct (check CloudFormation Outputs)
- Ensure your security groups allow inbound HTTPS (port 443)
- Check that AxonFlow ECS tasks are running (AWS ECS Console)
- Verify VPC networking (NAT Gateway, route tables)
Invalid License Key
Error: License key validation failed
Solutions:
- Verify license key format:
AXON-V2-{base64}-{signature} - Check license key hasn't expired
- Ensure organization ID matches the licensed tenant
- Regenerate license key if needed
Policy Syntax Error
Error: Policy compilation failed
Solutions:
- Verify policy file is valid Rego syntax
- Check required package:
package axonflow.policy - Test policy locally:
opa test policy.rego - Review policy examples: Policy Syntax Guide
Slow Response Time
Expected: Sub-10ms P95 latency for policy evaluation
If slower:
- Check CloudWatch metrics for agent CPU/memory
- Verify database connection (RDS Multi-AZ)
- Check network latency (VPC peering, ALB)
- Review policy complexity (optimize Rego rules)
Additional Resources
Documentation
- Getting Started Guide - Deploy AxonFlow
- SDK Reference (TypeScript) - Complete SDK docs
- SDK Reference (Go) - Complete SDK docs
- Policy Syntax - Policy language reference
- API Reference - REST API documentation
Examples
- Healthcare AI Assistant - HIPAA-compliant example
- E-commerce Recommendations - Product recommendations
- Customer Support Chatbot - Support automation
- Trip Planner - Multi-agent travel planning
Support
- Email: support@getaxonflow.com
- Documentation: https://docs.getaxonflow.com
- GitHub Issues: https://github.com/axonflow/axonflow-sdk-typescript/issues
Appendix: Complete Code Examples
TypeScript Complete Example
// index.ts
import { AxonFlow } from '@axonflow/sdk';
const axonflow = new AxonFlow({
endpoint: process.env.AXONFLOW_ENDPOINT || 'https://YOUR_AGENT_ENDPOINT',
licenseKey: process.env.AXONFLOW_LICENSE_KEY || 'YOUR_LICENSE_KEY',
tenant: process.env.AXONFLOW_TENANT || 'my-org',
debug: process.env.NODE_ENV !== 'production'
});
async function main() {
try {
// Test connection
console.log('🔌 Connecting to AxonFlow...');
const health = await axonflow.healthCheck();
console.log('✅ Connected:', health);
// Execute query (Proxy Mode)
console.log('\n📤 Sending query...');
const response = await axonflow.executeQuery({
userToken: 'user-123',
query: 'What is the capital of France?',
requestType: 'llm_chat',
context: {
provider: 'openai',
model: 'gpt-4',
timestamp: new Date().toISOString(),
}
});
// Display results
if (response.blocked) {
console.log('\n🚫 Request blocked:', response.blockReason);
} else {
console.log('\n✅ Query Response:', response.data);
console.log('🆔 Request ID:', response.requestId);
if (response.policyInfo) {
console.log('\n📊 Policy Information:');
console.log(' - Policies:', response.policyInfo.policiesEvaluated?.join(', '));
console.log(' - Processing time:', response.policyInfo.processingTime);
}
}
} catch (error) {
console.error('❌ Error:', error);
process.exit(1);
}
}
main();
Go Complete Example
// main.go
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/getaxonflow/axonflow-sdk-go"
)
func main() {
// Load configuration from environment
agentURL := getEnv("AXONFLOW_ENDPOINT", "https://YOUR_AGENT_ENDPOINT")
licenseKey := getEnv("AXONFLOW_LICENSE_KEY", "YOUR_LICENSE_KEY")
clientID := getEnv("AXONFLOW_CLIENT_ID", "my-org")
clientSecret := getEnv("AXONFLOW_CLIENT_SECRET", "YOUR_CLIENT_SECRET")
env := getEnv("ENVIRONMENT", "development")
// Initialize client
client := axonflow.NewClient(axonflow.AxonFlowConfig{
AgentURL: agentURL,
ClientID: clientID,
ClientSecret: clientSecret,
LicenseKey: licenseKey,
Debug: env != "production",
})
// Test connection
fmt.Println("🔌 Connecting to AxonFlow...")
if err := client.HealthCheck(); err != nil {
log.Fatal("Connection failed:", err)
}
fmt.Println("✅ Connected to AxonFlow")
// Execute query (Proxy Mode)
fmt.Println("\n📤 Sending query...")
response, err := client.ExecuteQuery(
"user-123", // userToken
"What is the capital of France?", // query
"llm_chat", // requestType
map[string]interface{}{ // context
"provider": "openai",
"model": "gpt-4",
"timestamp": time.Now().Format(time.RFC3339),
},
)
if err != nil {
log.Fatal("Query failed:", err)
}
// Display results
if response.Blocked {
fmt.Println("\n🚫 Request blocked:", response.BlockReason)
} else {
fmt.Println("\n✅ Query Response:", response.Data)
fmt.Printf("🆔 Request ID: %s\n", response.RequestID)
if response.PolicyInfo != nil {
fmt.Println("\n📊 Policy Information:")
fmt.Printf(" - Policies: %v\n", response.PolicyInfo.PoliciesEvaluated)
fmt.Printf(" - Processing time: %s\n", response.PolicyInfo.ProcessingTime)
}
}
}
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
Environment Variables
Create .env:
# Agent endpoint (port 8080)
AXONFLOW_ENDPOINT=https://your-agent-endpoint:8080
# Authentication
AXONFLOW_LICENSE_KEY=AXON-V2-xxx-yyy
AXONFLOW_CLIENT_ID=my-org
AXONFLOW_CLIENT_SECRET=your-client-secret
AXONFLOW_TENANT=my-org
# Environment
ENVIRONMENT=development
Security Note: Never commit .env to git. Add to .gitignore.
Tutorial Complete! You now have a production-ready AxonFlow agent. 🚀