DocsAPI Reference

API_REFERENCE

REFERENCE

Detailed documentation for the AKIOS SDK classes, interfaces, and CLI commands.

CLI_COMMANDS#

The AKIOS CLI is your primary tool for managing local development and edge deployments.

COMMANDDESCRIPTION
AKIOS initScaffolds a new agent project with TypeScript and Zod.
AKIOS devStarts a local hot-reloading server at localhost:3000.
AKIOS deployBundles and pushes your agent to the AKIOS Edge Runtime.
AKIOS logsStreams live logs from production instances.
AKIOS secretsManage encrypted environment variables.

CLASS_AGENT#

The Agent class orchestrates the loop between the LLM, tools, and memory. It manages the complete agent lifecycle from input to response.

typescript
import { Agent } from '@AKIOS/core'

CONSTRUCTOR_OPTIONS

PropTypeDescription
nameReq
string
Unique identifier for the agent. Used for logging and memory partitioning.
modelReq
string | ModelProvider
The LLM to use. Can be a string ID (e.g. "gpt-4") or a configured provider instance.
tools
Tool[]
Default: []
Array of Tool instances available to the agent.
systemPrompt
string
Default: "You are a helpful assistant."
The base instructions for the agent behavior.
memory
MemoryStore
Default: InMemoryStore
Persistence layer for conversation history.
temperature
number
Default: 0.7
Sampling temperature (0.0 to 1.0).
maxSteps
number
Default: 10
Maximum number of thought/action loops before forced termination.
maxTokens
number
Default: 4096
Maximum tokens per response.
timeout
number
Default: 30000
Request timeout in milliseconds.
guardrails
Guardrail[]
Default: []
Input/output validation rules.
debug
boolean
Default: false
Enable detailed logging and tracing.

METHODS

run(input: string, context?: Record<string, any>): Promise<AgentResponse>

Executes the agent loop with the given input. Returns the final text response and trace metadata.

typescript
const response = await agent.run('What is the weather in Tokyo?')
console.log(response.text) // "The weather in Tokyo is sunny, 22°C"
console.log(response.steps) // Array of execution steps
stream(input: string): AsyncIterable<AgentEvent>

Generates a stream of events (thought, tool_call, tool_result, answer) for real-time UI updates.

typescript
for await (const event of agent.stream('Calculate 15 * 23')) {
  if (event.type === 'tool_call') {
    console.log('Tool called:', event.tool, event.args)
  } else if (event.type === 'answer') {
    console.log('Final answer:', event.text)
  }
}
pause(): Promise<void>

Pauses execution at the next safe point. Useful for human-in-the-loop workflows.

resume(): Promise<AgentResponse>

Resumes execution after a pause, continuing from the last safe state.

EXAMPLE

typescript
import { Agent, Tool } from '@AKIOS/core'
import { z } from 'zod'

const calculator = new Tool({
  name: 'calculate',
  description: 'Perform mathematical calculations',
  schema: z.object({ expression: z.string() }),
  handler: async ({ expression }) => {
    // Implementation here
    return eval(expression) // Note: Use a safe math parser in production
  }
})

const agent = new Agent({
  name: 'math-assistant',
  model: 'gpt-4-turbo',
  tools: [calculator],
  systemPrompt: 'You are a mathematical assistant. Use the calculator tool for computations.',
  temperature: 0.1, // Lower temperature for math
  maxSteps: 5
})

// Use the agent
const result = await agent.run('What is 15 * 23?')
console.log(result.text) // "15 * 23 = 345"

CLASS_TOOL#

Tools allow agents to interact with the outside world. Each tool defines a function that the LLM can call with structured arguments.

typescript
import { Tool } from '@AKIOS/core'

CONSTRUCTOR_OPTIONS

PropTypeDescription
nameReq
string
The function name exposed to the LLM (e.g. "get_weather"). Must be snake_case.
descriptionReq
string
Natural language description of what the tool does and when to use it.
schemaReq
z.ZodSchema
Zod schema defining the input arguments. Used for validation and JSON Schema generation.
handlerReq
(args: T) => Promise<any>
The implementation function. Receives validated arguments.
dangerous
boolean
Default: false
If true, requires human approval before execution in production environments.
timeout
number
Default: 10000
Maximum execution time in milliseconds.
retries
number
Default: 3
Number of retry attempts on failure.

METHODS

call(args: Record<string, any>): Promise<any>

Executes the tool with the given arguments. Validates input against the schema before calling the handler.

getSchema(): object

Returns the JSON Schema representation of the tool's input parameters for LLM consumption.

EXAMPLES

WEATHER_TOOL
typescript
import { Tool } from '@AKIOS/core'
import { z } from 'zod'

const weatherTool = new Tool({
  name: 'get_weather',
  description: 'Get current weather for a city',
  schema: z.object({
    city: z.string().describe('The city name'),
    unit: z.enum(['celsius', 'fahrenheit']).default('celsius')
  }),
  handler: async ({ city, unit }) => {
    const response = await fetch(`https://api.weather.com/${city}`)
    const data = await response.json()
    
    return {
      temperature: data.temp,
      unit: unit,
      condition: data.condition,
      city: city
    }
  }
})
DATABASE_QUERY_TOOL
typescript
const databaseTool = new Tool({
  name: 'query_database',
  description: 'Execute a read-only SQL query',
  schema: z.object({
    query: z.string().describe('SQL SELECT statement'),
    limit: z.number().max(1000).default(100)
  }),
  dangerous: true, // Requires approval
  handler: async ({ query, limit }) => {
    // Validate query is read-only
    if (!query.toLowerCase().startsWith('select')) {
      throw new Error('Only SELECT queries allowed')
    }
    
    const result = await db.query(query + ` LIMIT ${limit}`)
    return result.rows
  }
})

INTERFACE_MODEL_PROVIDER#

Implement this interface to connect AKIOS to custom LLMs or local inference servers.

typescript
interface ModelProvider {
  id: string
  generate(
    messages: Message[], 
    tools?: ToolDefinition[]
  ): Promise<ModelResponse>
  
  stream(
    messages: Message[], 
    tools?: ToolDefinition[]
  ): AsyncIterable<ModelStreamEvent>
}

INTERFACE_MEMORY_STORE#

Memory stores persist conversation history and context across agent runs. Implement this interface for custom storage backends.

typescript
interface MemoryStore {
  get(agentId: string, conversationId?: string): Promise<Conversation[]>
  save(agentId: string, conversationId: string, messages: Message[]): Promise<void>
  delete(agentId: string, conversationId?: string): Promise<void>
  list(agentId: string): Promise<string[]> // conversation IDs
}

BUILT_IN_IMPLEMENTATIONS

  • InMemoryStore - Simple in-memory storage (development only)
  • RedisStore - Redis-backed persistence with TTL
  • PostgresStore - PostgreSQL with full-text search
  • DynamoDBStore - AWS DynamoDB for serverless deployments

EXAMPLE_CUSTOM_MEMORY_STORE

typescript
import { MemoryStore, Message } from '@AKIOS/core'

class CustomMemoryStore implements MemoryStore {
  async get(agentId: string, conversationId?: string): Promise<Conversation[]> {
    // Implementation here
    return []
  }
  
  async save(agentId: string, conversationId: string, messages: Message[]): Promise<void> {
    // Implementation here
  }
  
  async delete(agentId: string, conversationId?: string): Promise<void> {
    // Implementation here
  }
  
  async list(agentId: string): Promise<string[]> {
    // Implementation here
    return []
  }
}

const agent = new Agent({
  name: 'my-agent',
  model: 'gpt-4',
  memory: new CustomMemoryStore()
})

ERROR_TYPES#

AKIOS defines specific error types for different failure modes. All errors extend the base AKIOSError class.

ValidationError

Thrown when tool arguments don't match the schema or input validation fails.

typescript
throw new ValidationError('Invalid arguments for tool get_weather')

ToolExecutionError

Thrown when a tool handler fails during execution.

typescript
throw new ToolExecutionError('API rate limit exceeded', { tool: 'get_weather' })

GuardrailViolationError

Thrown when input or output violates a safety policy.

typescript
throw new GuardrailViolationError('PII detected in response', { policy: 'pii-redaction' })

MaxStepsExceededError

Thrown when an agent exceeds the maximum allowed execution steps.

typescript
throw new MaxStepsExceededError('Agent exceeded 10 steps without completion')

HTTP_API_ENDPOINTS#

When deployed, AKIOS exposes REST endpoints for agent interaction. All endpoints require authentication.

AGENT_EXECUTION

POST /api/v1/agents/{agentId}/run

Execute an agent synchronously and return the final response.

json
{
  "input": "What is the weather in Tokyo?",
  "context": { "user_id": "123" },
  "stream": false
}
POST /api/v1/agents/{agentId}/stream

Execute an agent with Server-Sent Events streaming.

json
{
  "input": "Tell me a story",
  "context": { "session_id": "abc" }
}

MEMORY_MANAGEMENT

GET /api/v1/agents/{agentId}/conversations

List all conversation IDs for an agent.

GET /api/v1/agents/{agentId}/conversations/{conversationId}

Retrieve the full conversation history.

DELETE /api/v1/agents/{agentId}/conversations/{conversationId}

Delete a conversation and its history.

CONFIGURATION_&_ENVIRONMENT#

AKIOS can be configured via environment variables, configuration files, or programmatic options.

ENVIRONMENT_VARIABLES

VariableDescriptionDefault
AKIOS_LOG_LEVELLogging verbosity (error, warn, info, debug)info
AKIOS_MAX_MEMORY_MBMaximum memory usage before garbage collection512
AKIOS_REQUEST_TIMEOUTHTTP request timeout in milliseconds30000
AKIOS_RATE_LIMIT_RPMRequests per minute limit60
AKIOS_ENABLE_METRICSEnable Prometheus metrics collectionfalse
AKIOS_STORAGE_BACKENDMemory store backend (redis, postgres, dynamodb)memory
AKIOS_REDIS_URLRedis connection URLredis://localhost:6379
AKIOS_DATABASE_URLPostgreSQL connection string

CONFIGURATION_FILE

Create an akios.config.js or akios.config.ts file in your project root for advanced configuration.

typescript
// akios.config.ts
import { Config } from '@AKIOS/core'

export default {
  agents: {
    'my-agent': {
      model: 'gpt-4-turbo',
      temperature: 0.7,
      tools: ['calculator', 'weather'],
      guardrails: ['pii-redaction', 'content-safety']
    }
  },
  memory: {
    backend: 'redis',
    ttl: 86400 // 24 hours
  },
  guardrails: {
    'pii-redaction': {
      enabled: true,
      strict: false
    }
  }
} satisfies Config