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) -> ValidationResultParameters
definition(required) - AgentDefinition instance to validate
Returns
ValidationResult object with the following properties:
| Property | Type | Description |
|---|---|---|
is_valid | bool | True if no errors found |
has_warnings | bool | True if warnings present |
errors | tuple[ValidationError, …] | All errors and warnings |
ValidationError Structure
Each error in result.errors contains:
| Property | Type | Description |
|---|---|---|
code | str | Error code (see Error Codes below) |
message | str | Human-readable error message |
severity | Severity | ERROR or WARNING |
location | str | None | Optional 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
| Code | Severity | Description |
|---|---|---|
MISSING_FIELD | ERROR | Required field not provided |
INVALID_FORMAT | ERROR | Value doesn’t match required format |
DUPLICATE_NAME | ERROR | Name used multiple times in scope |
EMPTY_COLLECTION | ERROR | Required collection is empty |
Static Analysis Errors
| Code | Severity | Description |
|---|---|---|
CYCLIC_DEPENDENCY | ERROR | Workflow contains cycle (not a DAG) |
UNREACHABLE_NODE | ERROR | Node cannot be reached from entry |
REFERENCE_ERROR | ERROR | Resource reference not found |
ORPHANED_RESOURCE | WARNING | Resource 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) -> strParameters
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 taskExample
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
) -> CompilationResultParameters
definition(required) - AgentDefinition instance to compileoutput_path(optional) - Path to write YAML file. If None, only returns YAML without writing.
Returns
CompilationResult object with the following properties:
| Property | Type | Description |
|---|---|---|
validation_result | ValidationResult | Validation results |
yaml_content | str | None | YAML string if successful, None if validation failed |
output_path | Path | None | File path if written, None otherwise |
is_successful | bool | True if validation passed |
Compilation Workflow
- Validate definition (schema + static analysis)
- Export to YAML (only if validation passes)
- 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 descriptionError Message:
MissingFieldError: Required field 'version' is missing or empty in AgentBuilderFix:
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 spaceError Message:
InvalidFormatError: Invalid value for 'name': 'Invalid Name'.
Agent name must start with lowercase letter and contain only lowercase letters, numbers, and hyphensFix:
agent = AgentBuilder("invalid-name") # Lowercase with hyphensDuplicateError
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-aFix: 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_valid3. 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 intentsubmit_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
) -> SubmissionResultParameters
definition(required) - AgentDefinition instance to submitapi_key(required) - Developer API key for authenticationbase_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:
| Property | Type | Description |
|---|---|---|
review_id | str | Unique identifier for tracking |
status | SubmissionStatus | Current review status |
agent_id | str | None | Assigned agent ID after approval |
tracking_url | str | None | URL to track progress |
marketplace_url | str | None | URL if agent is live |
feedback | tuple | Feedback items from Platform Core |
is_accepted | bool | True if accepted for review |
is_live | bool | True if published to marketplace |
is_rejected | bool | True if rejected |
Submission Workflow
- Validates the definition (SDK-level validation)
- Exports to YAML format
- 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
) -> SubmissionResultParameters
review_id(required) - Review ID returned fromsubmit_agent()api_key(required) - Developer API key for authenticationbase_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.
Related Documentation
- Builders API - Builder methods and parameters
- Entities Reference - Domain entities including EIP types
- Error Handling - Comprehensive error guide
- Validation Guide - Detailed validation rules
- How the SDK Works - Compilation process