DocumentationAPI ReferenceAPI Overview

API Reference

Main API functions for validating and exporting agent definitions.

validate()

Validates an agent definition structure and logic.

from ainalyn.api import validate
 
result = validate(agent)

Signature

def validate(definition: AgentDefinition) -> ValidationResult

Parameters

  • definition (required) - AgentDefinition instance to validate

Returns

ValidationResult object with the following properties:

PropertyTypeDescription
is_validboolTrue if no errors found
has_warningsboolTrue if warnings present
errorstuple[ValidationError, …]All errors and warnings

ValidationError Structure

Each error in result.errors contains:

PropertyTypeDescription
codestrError code (see Error Codes below)
messagestrHuman-readable error message
severitySeverityERROR or WARNING
locationstr | NoneOptional location where error occurred

Validation Process

The function performs two validation phases:

1. Schema Validation

  • Checks structural correctness
  • Verifies all required fields present
  • Validates field types and formats

2. Static Analysis

  • Detects cycles in workflows (DAG requirement)
  • Identifies unreachable nodes
  • Verifies all references resolve

Error Codes

Schema Validation Errors

CodeSeverityDescription
MISSING_FIELDERRORRequired field not provided
INVALID_FORMATERRORValue doesn’t match required format
DUPLICATE_NAMEERRORName used multiple times in scope
EMPTY_COLLECTIONERRORRequired collection is empty

Static Analysis Errors

CodeSeverityDescription
CYCLIC_DEPENDENCYERRORWorkflow contains cycle (not a DAG)
UNREACHABLE_NODEERRORNode cannot be reached from entry
REFERENCE_ERRORERRORResource reference not found
ORPHANED_RESOURCEWARNINGResource defined but never used

Example

from ainalyn import AgentBuilder, WorkflowBuilder, NodeBuilder, PromptBuilder
from ainalyn.api import validate
 
# Build agent
prompt = PromptBuilder("task-prompt").description("Task").template("Do task").build()
workflow = (
    WorkflowBuilder("main")
    .description("Main workflow")
    .add_node(
        NodeBuilder("task")
        .description("Execute task")
        .uses_prompt("task-prompt")
        .build()
    )
    .entry_node("task")
    .build()
)
agent = (
    AgentBuilder("my-agent")
    .version("1.0.0")
    .description("My agent")
    .add_prompt(prompt)
    .add_workflow(workflow)
    .build()
)
 
# Validate
result = validate(agent)
if result.is_valid:
    print("Validation passed")
else:
    print("Validation failed:")
    for error in result.errors:
        print(f"  [{error.severity}] {error.code}: {error.message}")
        if error.location:
            print(f"    Location: {error.location}")

Error Handling

result = validate(agent)
 
# Check overall validity
if not result.is_valid:
    # Has errors - cannot proceed
    for error in result.errors:
        if error.severity == Severity.ERROR:
            print(f"ERROR: {error.message}")
 
# Check warnings
if result.has_warnings:
    # Has warnings - can proceed but should review
    for error in result.errors:
        if error.severity == Severity.WARNING:
            print(f"WARNING: {error.message}")

export_yaml()

Exports an agent definition to YAML string.

from ainalyn.api import export_yaml
 
yaml_output = export_yaml(agent)

Signature

def export_yaml(definition: AgentDefinition) -> str

Parameters

  • definition (required) - AgentDefinition instance to export

Returns

YAML-formatted string with header comments

Important Notes

  • Does NOT validate before export
  • For validation + export, use compile_agent() instead
  • Output includes header comments explaining SDK boundary

Output Format

# Ainalyn Agent Definition
# This file is a description submitted to Platform Core for review.
# It does NOT execute by itself. Execution is handled by Platform Core.
#
# Local compilation does NOT equal platform execution.
 
name: my-agent
version: 1.0.0
description: Agent description
workflows:
  - name: main
    description: Main workflow
    entry_node: task
    nodes:
      - name: task
        description: Task node
        type: prompt
        reference: task-prompt
prompts:
  - name: task-prompt
    description: Task prompt
    template: Do the task

Example

from ainalyn import AgentBuilder
from ainalyn.api import export_yaml
 
agent = (
    AgentBuilder("my-agent")
    .version("1.0.0")
    .description("Test agent")
    .add_workflow(workflow)
    .build()
)
 
yaml_str = export_yaml(agent)
print(yaml_str)
 
# Write to file
with open("agent.yaml", "w") as f:
    f.write(yaml_str)

compile_agent()

Validates and exports an agent definition (recommended workflow).

from ainalyn.api import compile_agent
from pathlib import Path
 
result = compile_agent(agent, Path("agent.yaml"))

Signature

def compile_agent(
    definition: AgentDefinition,
    output_path: Path | None = None
) -> CompilationResult

Parameters

  • definition (required) - AgentDefinition instance to compile
  • output_path (optional) - Path to write YAML file. If None, only returns YAML without writing.

Returns

CompilationResult object with the following properties:

PropertyTypeDescription
validation_resultValidationResultValidation results
yaml_contentstr | NoneYAML string if successful, None if validation failed
output_pathPath | NoneFile path if written, None otherwise
is_successfulboolTrue if validation passed

Compilation Workflow

  1. Validate definition (schema + static analysis)
  2. Export to YAML (only if validation passes)
  3. Write to file (if output_path provided)

Important Note

Local compilation does NOT equal platform execution. This creates a description for platform submission. Platform Core applies additional validation and governance policies.

Example: Compile to String

from ainalyn import AgentBuilder
from ainalyn.api import compile_agent
 
agent = (
    AgentBuilder("my-agent")
    .version("1.0.0")
    .description("Test agent")
    .add_workflow(workflow)
    .build()
)
 
# Compile without writing file
result = compile_agent(agent)
 
if result.is_successful:
    print("Compilation successful!")
    print(result.yaml_content)
else:
    print("Compilation failed:")
    for error in result.validation_result.errors:
        print(f"  {error.code}: {error.message}")

Example: Compile to File

from ainalyn.api import compile_agent
from pathlib import Path
 
# Compile and write to file
result = compile_agent(agent, Path("output/agent.yaml"))
 
if result.is_successful:
    print(f"Compiled successfully to {result.output_path}")
else:
    print("Compilation failed:")
    for error in result.validation_result.errors:
        print(f"  {error.code}: {error.message}")

Error Handling

from ainalyn.api import compile_agent
from pathlib import Path
 
result = compile_agent(agent, Path("agent.yaml"))
 
# Check success
if result.is_successful:
    # Validation passed, YAML generated and written
    print(f"Success! File: {result.output_path}")
    print(f"YAML content:\n{result.yaml_content}")
else:
    # Validation failed, no YAML generated
    print("Compilation failed with errors:")
 
    for error in result.validation_result.errors:
        print(f"\n[{error.severity}] {error.code}")
        print(f"  Message: {error.message}")
        if error.location:
            print(f"  Location: {error.location}")

Complete Error Reference

Build-Time Errors

These errors occur when calling .build() on builders:

MissingFieldError

Cause: Required field not provided

Example:

agent = AgentBuilder("test").build()  # Missing version and description

Error Message:

MissingFieldError: Required field 'version' is missing or empty in AgentBuilder

Fix:

agent = (
    AgentBuilder("test")
    .version("1.0.0")
    .description("Test agent")
    .build()
)

InvalidFormatError

Cause: Value doesn’t match required format

Example:

agent = AgentBuilder("Invalid Name")  # Uppercase and space

Error Message:

InvalidFormatError: Invalid value for 'name': 'Invalid Name'.
Agent name must start with lowercase letter and contain only lowercase letters, numbers, and hyphens

Fix:

agent = AgentBuilder("invalid-name")  # Lowercase with hyphens

DuplicateError

Cause: Name used multiple times in same scope

Example:

workflow = (
    WorkflowBuilder("main")
    .add_node(NodeBuilder("task").description("Task 1").uses_prompt("p1").build())
    .add_node(NodeBuilder("task").description("Task 2").uses_prompt("p2").build())
    .build()
)

Error Message:

DuplicateError: Duplicate node name 'task' in workflow 'main'.
Each node must have a unique name within its scope.

Fix:

workflow = (
    WorkflowBuilder("main")
    .add_node(NodeBuilder("task-1").description("Task 1").uses_prompt("p1").build())
    .add_node(NodeBuilder("task-2").description("Task 2").uses_prompt("p2").build())
    .build()
)

ReferenceError

Cause: Node references undefined resource

Example:

agent = (
    AgentBuilder("test")
    .version("1.0.0")
    .description("Test")
    .add_workflow(
        WorkflowBuilder("main")
        .add_node(
            NodeBuilder("task")
            .description("Task")
            .uses_prompt("undefined-prompt")  # Prompt not defined
            .build()
        )
        .entry_node("task")
        .build()
    )
    .build()
)

Error Message:

ReferenceError: 'task' references undefined prompt 'undefined-prompt'.
The prompt must be defined in the agent.

Fix:

prompt = PromptBuilder("my-prompt").description("Prompt").template("Text").build()
agent = (
    AgentBuilder("test")
    .add_prompt(prompt)  # Define the prompt
    .add_workflow(...)
    .build()
)

EmptyCollectionError

Cause: Required collection is empty

Example:

agent = (
    AgentBuilder("test")
    .version("1.0.0")
    .description("Test")
    .build()  # No workflows added
)

Error Message:

EmptyCollectionError: 'Agent 'test'' has no workflows.
At least one workflow is required.

Fix:

agent = (
    AgentBuilder("test")
    .version("1.0.0")
    .description("Test")
    .add_workflow(workflow)  # Add at least one workflow
    .build()
)

Validation Errors

These errors occur during validate():

CyclicDependencyError

Cause: Workflow contains cycle

Detection: Static analysis finds cycle in node graph

Example:

# node-a → node-b → node-c → node-a (cycle!)

Error Message:

CyclicDependencyError: Workflow contains a cycle: node-a → node-b → node-c → node-a

Fix: Remove cycle by restructuring workflow to form a DAG


UnreachableNodeError

Cause: Node cannot be reached from entry node

Detection: Static analysis finds node with no path from entry

Example:

# entry-node → task-a
# orphan-node (unreachable)

Error Message:

UnreachableNodeError: Node 'orphan-node' is unreachable from entry node 'entry-node'.
All nodes must be reachable via edges.

Fix: Connect node to workflow or remove it


Best Practices

1. Use compile_agent() for Production

Recommended approach combines validation and export:

from ainalyn.api import compile_agent
from pathlib import Path
 
result = compile_agent(agent, Path("agent.yaml"))
if result.is_successful:
    # Safe to submit to platform
    submit_to_platform(result.output_path)
else:
    # Fix errors before submission
    handle_errors(result.validation_result.errors)

2. Validate During Development

Validate after each major change:

# After adding workflow
agent = agent.add_workflow(workflow)
result = validate(agent.build())
assert result.is_valid
 
# After adding resources
agent = agent.add_prompt(prompt)
result = validate(agent.build())
assert result.is_valid

3. Handle Errors Specifically

from ainalyn.domain.errors import (
    MissingFieldError,
    InvalidFormatError,
    ReferenceError,
)
 
try:
    agent = builder.build()
except MissingFieldError as e:
    print(f"Missing required field: {e.field_name}")
except InvalidFormatError as e:
    print(f"Invalid {e.field_name}: {e.value}")
    print(f"Constraint: {e.constraint}")
except ReferenceError as e:
    print(f"Undefined {e.resource_type}: {e.reference}")

4. Review Generated YAML

Always inspect output before submission:

yaml = export_yaml(agent)
print(yaml)  # Verify structure matches intent

submit_agent()

Submits an agent definition to Platform Core for review.

from ainalyn.api import submit_agent
 
result = submit_agent(agent, api_key="dev_sk_xxx")

Signature

def submit_agent(
    definition: AgentDefinition,
    api_key: str,
    *,
    base_url: str | None = None,
    auto_deploy: bool = False
) -> SubmissionResult

Parameters

  • definition (required) - AgentDefinition instance to submit
  • api_key (required) - Developer API key for authentication
  • base_url (optional) - Platform Core API base URL (defaults to production)
  • auto_deploy (optional) - Auto-deploy after approval (default: False)

Returns

SubmissionResult object with the following properties:

PropertyTypeDescription
review_idstrUnique identifier for tracking
statusSubmissionStatusCurrent review status
agent_idstr | NoneAssigned agent ID after approval
tracking_urlstr | NoneURL to track progress
marketplace_urlstr | NoneURL if agent is live
feedbacktupleFeedback items from Platform Core
is_acceptedboolTrue if accepted for review
is_liveboolTrue if published to marketplace
is_rejectedboolTrue if rejected

Submission Workflow

  1. Validates the definition (SDK-level validation)
  2. Exports to YAML format
  3. Submits to Platform Core API

Important - Platform Constitution

  • SDK can submit but NOT approve (Platform Core has final authority)
  • Submission does NOT create an Execution
  • Submission does NOT incur billing (unless platform policy states)

Example

from ainalyn import AgentBuilder
from ainalyn.api import submit_agent
from ainalyn.domain.entities import EIPDependency, CompletionCriteria
 
# Build agent with Platform submission requirements
agent = (
    AgentBuilder("my-agent")
    .version("1.0.0")
    .description("My agent")
    .task_goal("Process and analyze user input")
    .completion_criteria(CompletionCriteria(
        success="Output generated successfully",
        failure="Processing failed"
    ))
    .add_eip_dependency(EIPDependency(
        provider="openai",
        service="gpt-4",
        version=">=1.0.0"
    ))
    .add_workflow(workflow)
    .build()
)
 
# Submit to Platform Core
result = submit_agent(agent, api_key="dev_sk_xxx")
 
if result.is_accepted:
    print(f"Submitted for review!")
    print(f"Review ID: {result.review_id}")
    print(f"Track at: {result.tracking_url}")
else:
    print("Submission rejected")
    for feedback in result.feedback:
        print(f"  - {feedback.message}")

Error Handling

from ainalyn.domain.errors import (
    SubmissionError,
    AuthenticationError,
    NetworkError,
)
 
try:
    result = submit_agent(agent, api_key="dev_sk_xxx")
except AuthenticationError as e:
    print(f"Invalid API key: {e.message}")
except NetworkError as e:
    print(f"Network error: {e.message}")
except SubmissionError as e:
    print(f"Submission failed: {e.message}")
    if e.validation_errors:
        for err in e.validation_errors:
            print(f"  - {err.message}")

track_submission()

Tracks the status of a submitted agent definition.

from ainalyn.api import track_submission
 
result = track_submission(review_id="review_abc123", api_key="dev_sk_xxx")

Signature

def track_submission(
    review_id: str,
    api_key: str,
    *,
    base_url: str | None = None
) -> SubmissionResult

Parameters

  • review_id (required) - Review ID returned from submit_agent()
  • api_key (required) - Developer API key for authentication
  • base_url (optional) - Platform Core API base URL

Returns

SubmissionResult object with current status and feedback.

Example

from ainalyn.api import track_submission
from ainalyn.domain.entities import SubmissionStatus
 
# Check submission status
result = track_submission(review_id="review_abc123", api_key="dev_sk_xxx")
 
print(f"Status: {result.status.value}")
 
if result.status == SubmissionStatus.ACCEPTED:
    print(f"Agent approved! ID: {result.agent_id}")
elif result.status == SubmissionStatus.DEPLOYED:
    print(f"Agent is live: {result.marketplace_url}")
elif result.status == SubmissionStatus.REJECTED:
    print("Rejected. Feedback:")
    for issue in result.get_blocking_issues():
        print(f"  [{issue.severity.value}] {issue.message}")
elif result.status == SubmissionStatus.PENDING_REVIEW:
    print("Still under review...")

Note

Currently uses MockPlatformClient for testing until Platform Core API is available. Real HTTP communication will be enabled in future versions.