aianim Package

Top-Level Exports (aianim)

aianim: AI agentic studio combining handanim drawing and voiceanim speech into video creation.

class aianim.ScenePlan(title, description='', total_duration=0.0, width=1920, height=1088, scenes=<factory>)[source]

Bases: object

Complete structured plan for a multi-scene handanim animation.

Parameters:
title: str
description: str = ''
total_duration: float = 0.0
width: int = 1920
height: int = 1088
scenes: list[SceneSpec]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

ScenePlan

to_dict()[source]
Return type:

dict[str, Any]

classmethod from_json(json_str)[source]

Parse from JSON string, handling optional markdown fence wrapping.

Parameters:

json_str (str)

Return type:

ScenePlan

to_json(indent=2)[source]
Parameters:

indent (int)

Return type:

str

validate()[source]

Validate structure and return list of validation warning/error messages.

Return type:

list[str]

classmethod get_json_schema()[source]

Return the OpenAPI / JSON Schema definition for tool-calling.

Return type:

dict[str, Any]

class aianim.SceneSpec(id=1, title='', duration=5.0, drawables=<factory>, animations=<factory>)[source]

Bases: object

Specification for an individual scene segment.

Parameters:
id: int | str = 1
title: str = ''
duration: float = 5.0
drawables: list[DrawableSpec]
animations: list[AnimationSpec]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

SceneSpec

class aianim.DrawableSpec(id, type, params=<factory>, styles=<factory>)[source]

Bases: object

Specification for a visual shape or element.

Parameters:
id: str
type: str
params: dict[str, Any]
styles: dict[str, Any]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

DrawableSpec

class aianim.AnimationSpec(drawable_id, type, start_time=0.0, duration=1.0, params=<factory>)[source]

Bases: object

Specification for an animation applied to a drawable.

Parameters:
drawable_id: str
type: str
start_time: float = 0.0
duration: float = 1.0
params: dict[str, Any]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

AnimationSpec

aianim.plan_to_python(plan, output_path='output.mp4')[source]

Compile a structured ScenePlan into canonical handanim Python code.

Parameters:
  • plan (ScenePlan | dict[str, Any]) – A ScenePlan instance or equivalent dictionary.

  • output_path (str) – Target video file path written to scene.render().

Returns:

A standalone, reproducible Python script string.

Return type:

str

aianim.check_code(code_str)[source]

Run static AST analysis on handanim Python code.

Parameters:

code_str (str) – Source code string to inspect.

Returns:

DiagnosticReport with validity flag, errors, warnings, and suggestions.

Return type:

DiagnosticReport

class aianim.DiagnosticReport(is_valid, errors=<factory>, warnings=<factory>, suggestions=<factory>)[source]

Bases: object

Diagnostic outcome containing syntax and semantic linter warnings/errors.

Parameters:
is_valid: bool
errors: list[str]
warnings: list[str]
suggestions: list[str]
to_dict()[source]
Return type:

dict[str, Any]

class aianim.InteractiveSession(model=None, verbose=True, output_dir='.')[source]

Bases: object

Conversational CLI session with live inspection and arrow-key user feedback.

Parameters:
log(tag, message, color='\x1b[94m')[source]

Print formatted stage log.

Parameters:
log_prompt(system_message, user_message)[source]

Print under-the-hood prompt when verbose mode is active.

Parameters:
  • system_message (str)

  • user_message (str)

prompt_choice(message, choices, default=None)[source]

Prompt user with an interactive arrow-key choice menu using questionary with fallback.

Parameters:
Return type:

str

prompt_text(message, default='')[source]

Prompt for text input using questionary or standard input.

Parameters:
Return type:

str

run()[source]

Run the interactive session.

handle_topic_turn(topic)[source]

Analyze topic, ask clarifying questions if ambiguous, or draft plan.

Parameters:

topic (str)

handle_user_message(message)[source]

Handle iterative conversational user feedback.

Parameters:

message (str)

generate_and_review_plan(topic_summary)[source]

Run Ideation stage, display plan, and provide interactive arrow-key choice menu.

Parameters:

topic_summary (str)

refine_plan(feedback)[source]

Ask the model to update the current ScenePlan based on user feedback.

Parameters:

feedback (str)

display_plan_summary(plan)[source]

Format and print an attractive summary of the plan using rich tree/panels or ANSI.

Parameters:

plan (ScenePlan)

generate_code_from_plan()[source]

Compile plan into Python and execute.

execute_and_verify(code, output_path)[source]

Run code in subprocess and report live results.

Parameters:
  • code (str)

  • output_path (str)

auto_repair_code(broken_code, error_message, output_path)[source]

Ask model to repair broken Python script.

Parameters:
  • broken_code (str)

  • error_message (str)

  • output_path (str)

class aianim.AnimationGenerator(model=None, prompt_manager=None, executor=None, prompt_version='v1')[source]

Bases: object

Orchestrates topic ideation, code generation, execution, and self-correction.

Parameters:
generate(topic, output_path='output.mp4', max_retries=2, use_compiler=False)[source]

Run end-to-end animation generation pipeline with self-correction feedback loop.

Parameters:
  • topic (str) – Natural language topic description (e.g. ‘explain Pythagorean theorem’).

  • output_path (str) – Target video or image output path.

  • max_retries (int) – Maximum self-correction attempts upon syntax or execution failure.

  • use_compiler (bool) – If True, compiles the ScenePlan directly using plan_to_python() instead of calling the LLM codegen prompt.

Returns:

PipelineResult containing generated code, plan, and execution status.

Return type:

PipelineResult

class aianim.PipelineResult(success, code, scene_plan, output_path, retries_used, execution_result, error='')[source]

Bases: object

Outcome of the animation generation pipeline.

Parameters:
success: bool
code: str
scene_plan: ScenePlan | None
output_path: str
retries_used: int
execution_result: ExecutionResult | None
error: str = ''
class aianim.CodeExecutor(default_timeout=45.0)[source]

Bases: object

Executes generated Python code in an isolated subprocess.

Parameters:

default_timeout (float)

execute(code, expected_output=None, timeout=None, working_dir=None)[source]

Execute Python code string in a subprocess and verify output creation.

Parameters:
  • code (str) – Full Python source code.

  • expected_output (str | None) – Optional path to output media file (e.g. .mp4, .svg) to verify.

  • timeout (float | None) – Subprocess timeout in seconds. Defaults to self.default_timeout.

  • working_dir (str | Path | None) – Working directory for execution. Defaults to repository root.

Returns:

ExecutionResult containing execution status, logs, and error details.

Return type:

ExecutionResult

class aianim.ExecutionResult(success, stdout, stderr, returncode, output_exists, execution_time, error_summary='')[source]

Bases: object

Outcome of running a generated handanim script.

Parameters:
success: bool
stdout: str
stderr: str
returncode: int
output_exists: bool
execution_time: float
error_summary: str = ''
class aianim.BaseLLMModel[source]

Bases: ABC

Abstract base class for LLM providers.

abstractmethod invoke(messages, system_message=None, response_format=None)[source]

Invoke the LLM with messages and optional system message/response format.

Parameters:
  • messages (list[dict[str, str]]) – List of dicts with ‘role’ (‘user’, ‘assistant’) and ‘content’.

  • system_message (str | None) – Optional system prompt instructions.

  • response_format (dict[str, Any] | None) – Optional format constraint, e.g. {“type”: “json_object”}.

Returns:

The generated text response string.

Return type:

str

class aianim.BedrockModel(model_id=None, region_name=None, profile_name=None, client=None)[source]

Bases: BaseLLMModel

AWS Bedrock model provider using the unified Bedrock Converse API.

Supports Claude 3.5 Sonnet, Nova, Llama 3, and any model hosted on Bedrock.

Parameters:
  • model_id (str | None)

  • region_name (str | None)

  • profile_name (str | None)

  • client (Any)

DEFAULT_MODEL_ID = 'anthropic.claude-3-5-sonnet-20241022-v2:0'
__init__(model_id=None, region_name=None, profile_name=None, client=None)[source]

Initialize AWS Bedrock client.

Parameters:
  • model_id (str | None) – AWS Bedrock model ID. Defaults to Claude 3.5 Sonnet v2.

  • region_name (str | None) – AWS region (e.g. ‘us-east-1’, ‘us-west-2’).

  • profile_name (str | None) – Optional AWS credentials profile name.

  • client (Any) – Optional pre-configured boto3 bedrock-runtime client.

invoke(messages, system_message=None, response_format=None)[source]

Invoke model via AWS Bedrock Converse API.

Parameters:
Return type:

str

class aianim.OpenRouterModel(model_name='anthropic/claude-3.5-sonnet', api_key=None)[source]

Bases: BaseLLMModel

OpenRouter LLM provider for OpenAI-compatible completions.

Parameters:
  • model_name (str)

  • api_key (str | None)

BASE_URL = 'https://openrouter.ai/api/v1/chat/completions'
invoke(messages, system_message=None, response_format=None)[source]

Invoke the LLM with messages and optional system message/response format.

Parameters:
  • messages (list[dict[str, str]]) – List of dicts with ‘role’ (‘user’, ‘assistant’) and ‘content’.

  • system_message (str | None) – Optional system prompt instructions.

  • response_format (dict[str, Any] | None) – Optional format constraint, e.g. {“type”: “json_object”}.

Returns:

The generated text response string.

Return type:

str

class aianim.MockModel(responses=None, response_fn=None)[source]

Bases: BaseLLMModel

Deterministic mock model for testing and offline runs.

Parameters:
call_history: list[dict[str, Any]]
invoke(messages, system_message=None, response_format=None)[source]

Invoke the LLM with messages and optional system message/response format.

Parameters:
  • messages (list[dict[str, str]]) – List of dicts with ‘role’ (‘user’, ‘assistant’) and ‘content’.

  • system_message (str | None) – Optional system prompt instructions.

  • response_format (dict[str, Any] | None) – Optional format constraint, e.g. {“type”: “json_object”}.

Returns:

The generated text response string.

Return type:

str

aianim.get_model(provider=None, model_name=None, **kwargs)[source]

Factory to instantiate the appropriate LLM provider.

Resolution order: 1. Explicit provider argument (‘bedrock’, ‘openrouter’, ‘mock’). 2. Environment variable HANDANIM_AI_PROVIDER. 3. If AWS credentials exist, defaults to Bedrock. 4. If OPENROUTER_API_KEY exists, defaults to OpenRouter. 5. Fallback to MockModel.

Parameters:
  • provider (str | None)

  • model_name (str | None)

  • kwargs (Any)

Return type:

BaseLLMModel

class aianim.PromptManager(prompts_dir=None)[source]

Bases: object

Manages prompt template loading and version discovery.

Parameters:

prompts_dir (Path | None)

get(name, version='v1')[source]

Load a prompt template by name and version (e.g. name=’big_picture’, version=’v1’).

Parameters:
Return type:

PromptTemplate

list_prompts()[source]

List all discovered prompt templates across version directories.

Return type:

list[dict[str, str]]

aianim.get_available_assets()[source]

Scan and return available fonts, colors, and asset files.

Return type:

dict[str, Any]

aianim.format_assets_markdown()[source]

Format available assets as clean Markdown for prompt injection.

Return type:

str

class aianim.HandanimMCPServer[source]

Bases: object

Stdio-based JSON-RPC 2.0 Model Context Protocol Server.

SERVER_NAME = 'handanim-mcp'
SERVER_VERSION = '0.1.0'
PROTOCOL_VERSION = '2024-11-05'
run()[source]

Main stdio loop reading JSON-RPC requests.

handle_request(req)[source]
Parameters:

req (dict[str, Any])

Return type:

dict[str, Any] | None

call_tool(tool_name, args)[source]

Dispatch tool calls and format MCP tool response content.

Parameters:
Return type:

list[dict[str, Any]]

aianim.schema

Structured scene representation and validation schema for AI-assisted animation.

class aianim.schema.DrawableSpec(id, type, params=<factory>, styles=<factory>)[source]

Bases: object

Specification for a visual shape or element.

Parameters:
id: str
type: str
params: dict[str, Any]
styles: dict[str, Any]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

DrawableSpec

class aianim.schema.AnimationSpec(drawable_id, type, start_time=0.0, duration=1.0, params=<factory>)[source]

Bases: object

Specification for an animation applied to a drawable.

Parameters:
drawable_id: str
type: str
start_time: float = 0.0
duration: float = 1.0
params: dict[str, Any]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

AnimationSpec

class aianim.schema.SceneSpec(id=1, title='', duration=5.0, drawables=<factory>, animations=<factory>)[source]

Bases: object

Specification for an individual scene segment.

Parameters:
id: int | str = 1
title: str = ''
duration: float = 5.0
drawables: list[DrawableSpec]
animations: list[AnimationSpec]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

SceneSpec

class aianim.schema.ScenePlan(title, description='', total_duration=0.0, width=1920, height=1088, scenes=<factory>)[source]

Bases: object

Complete structured plan for a multi-scene handanim animation.

Parameters:
title: str
description: str = ''
total_duration: float = 0.0
width: int = 1920
height: int = 1088
scenes: list[SceneSpec]
classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

ScenePlan

to_dict()[source]
Return type:

dict[str, Any]

classmethod from_json(json_str)[source]

Parse from JSON string, handling optional markdown fence wrapping.

Parameters:

json_str (str)

Return type:

ScenePlan

to_json(indent=2)[source]
Parameters:

indent (int)

Return type:

str

validate()[source]

Validate structure and return list of validation warning/error messages.

Return type:

list[str]

classmethod get_json_schema()[source]

Return the OpenAPI / JSON Schema definition for tool-calling.

Return type:

dict[str, Any]

aianim.compiler

Deterministic compiler: translates a structured ScenePlan into clean, executable Python code.

aianim.compiler.plan_to_python(plan, output_path='output.mp4')[source]

Compile a structured ScenePlan into canonical handanim Python code.

Parameters:
  • plan (ScenePlan | dict[str, Any]) – A ScenePlan instance or equivalent dictionary.

  • output_path (str) – Target video file path written to scene.render().

Returns:

A standalone, reproducible Python script string.

Return type:

str

aianim.pipeline

Autonomous animation generation pipeline with self-correction feedback loop.

class aianim.pipeline.PipelineResult(success, code, scene_plan, output_path, retries_used, execution_result, error='')[source]

Bases: object

Outcome of the animation generation pipeline.

Parameters:
success: bool
code: str
scene_plan: ScenePlan | None
output_path: str
retries_used: int
execution_result: ExecutionResult | None
error: str = ''
class aianim.pipeline.AnimationGenerator(model=None, prompt_manager=None, executor=None, prompt_version='v1')[source]

Bases: object

Orchestrates topic ideation, code generation, execution, and self-correction.

Parameters:
generate(topic, output_path='output.mp4', max_retries=2, use_compiler=False)[source]

Run end-to-end animation generation pipeline with self-correction feedback loop.

Parameters:
  • topic (str) – Natural language topic description (e.g. ‘explain Pythagorean theorem’).

  • output_path (str) – Target video or image output path.

  • max_retries (int) – Maximum self-correction attempts upon syntax or execution failure.

  • use_compiler (bool) – If True, compiles the ScenePlan directly using plan_to_python() instead of calling the LLM codegen prompt.

Returns:

PipelineResult containing generated code, plan, and execution status.

Return type:

PipelineResult

aianim.diagnostics

AST guardrails and code linter for agentic workflows and AI-generated scripts.

class aianim.diagnostics.DiagnosticReport(is_valid, errors=<factory>, warnings=<factory>, suggestions=<factory>)[source]

Bases: object

Diagnostic outcome containing syntax and semantic linter warnings/errors.

Parameters:
is_valid: bool
errors: list[str]
warnings: list[str]
suggestions: list[str]
to_dict()[source]
Return type:

dict[str, Any]

class aianim.diagnostics.HandanimCodeAuditor[source]

Bases: NodeVisitor

AST visitor inspecting handanim-specific coding patterns and anti-patterns.

IMMUTABLE_TRANSFORMS = {'rotate', 'scale', 'translate'}
errors: list[str]
warnings: list[str]
suggestions: list[str]
visit_ImportFrom(node)[source]
Parameters:

node (ImportFrom)

visit_Expr(node)[source]

Check for standalone function/method calls that discard return values.

Parameters:

node (Expr)

visit_Call(node)[source]
Parameters:

node (Call)

visit_Constant(node)[source]
Parameters:

node (Constant)

aianim.diagnostics.check_code(code_str)[source]

Run static AST analysis on handanim Python code.

Parameters:

code_str (str) – Source code string to inspect.

Returns:

DiagnosticReport with validity flag, errors, warnings, and suggestions.

Return type:

DiagnosticReport

aianim.executor

Subprocess execution engine with timeout and error capture for generated animations.

class aianim.executor.ExecutionResult(success, stdout, stderr, returncode, output_exists, execution_time, error_summary='')[source]

Bases: object

Outcome of running a generated handanim script.

Parameters:
success: bool
stdout: str
stderr: str
returncode: int
output_exists: bool
execution_time: float
error_summary: str = ''
class aianim.executor.CodeExecutor(default_timeout=45.0)[source]

Bases: object

Executes generated Python code in an isolated subprocess.

Parameters:

default_timeout (float)

execute(code, expected_output=None, timeout=None, working_dir=None)[source]

Execute Python code string in a subprocess and verify output creation.

Parameters:
  • code (str) – Full Python source code.

  • expected_output (str | None) – Optional path to output media file (e.g. .mp4, .svg) to verify.

  • timeout (float | None) – Subprocess timeout in seconds. Defaults to self.default_timeout.

  • working_dir (str | Path | None) – Working directory for execution. Defaults to repository root.

Returns:

ExecutionResult containing execution status, logs, and error details.

Return type:

ExecutionResult

aianim.models

Multi-provider LLM interface supporting AWS Bedrock, OpenRouter, and Mock providers.

class aianim.models.BaseLLMModel[source]

Bases: ABC

Abstract base class for LLM providers.

abstractmethod invoke(messages, system_message=None, response_format=None)[source]

Invoke the LLM with messages and optional system message/response format.

Parameters:
  • messages (list[dict[str, str]]) – List of dicts with ‘role’ (‘user’, ‘assistant’) and ‘content’.

  • system_message (str | None) – Optional system prompt instructions.

  • response_format (dict[str, Any] | None) – Optional format constraint, e.g. {“type”: “json_object”}.

Returns:

The generated text response string.

Return type:

str

class aianim.models.BedrockModel(model_id=None, region_name=None, profile_name=None, client=None)[source]

Bases: BaseLLMModel

AWS Bedrock model provider using the unified Bedrock Converse API.

Supports Claude 3.5 Sonnet, Nova, Llama 3, and any model hosted on Bedrock.

Parameters:
  • model_id (str | None)

  • region_name (str | None)

  • profile_name (str | None)

  • client (Any)

DEFAULT_MODEL_ID = 'anthropic.claude-3-5-sonnet-20241022-v2:0'
__init__(model_id=None, region_name=None, profile_name=None, client=None)[source]

Initialize AWS Bedrock client.

Parameters:
  • model_id (str | None) – AWS Bedrock model ID. Defaults to Claude 3.5 Sonnet v2.

  • region_name (str | None) – AWS region (e.g. ‘us-east-1’, ‘us-west-2’).

  • profile_name (str | None) – Optional AWS credentials profile name.

  • client (Any) – Optional pre-configured boto3 bedrock-runtime client.

invoke(messages, system_message=None, response_format=None)[source]

Invoke model via AWS Bedrock Converse API.

Parameters:
Return type:

str

class aianim.models.OpenRouterModel(model_name='anthropic/claude-3.5-sonnet', api_key=None)[source]

Bases: BaseLLMModel

OpenRouter LLM provider for OpenAI-compatible completions.

Parameters:
  • model_name (str)

  • api_key (str | None)

BASE_URL = 'https://openrouter.ai/api/v1/chat/completions'
invoke(messages, system_message=None, response_format=None)[source]

Invoke the LLM with messages and optional system message/response format.

Parameters:
  • messages (list[dict[str, str]]) – List of dicts with ‘role’ (‘user’, ‘assistant’) and ‘content’.

  • system_message (str | None) – Optional system prompt instructions.

  • response_format (dict[str, Any] | None) – Optional format constraint, e.g. {“type”: “json_object”}.

Returns:

The generated text response string.

Return type:

str

class aianim.models.MockModel(responses=None, response_fn=None)[source]

Bases: BaseLLMModel

Deterministic mock model for testing and offline runs.

Parameters:
call_history: list[dict[str, Any]]
invoke(messages, system_message=None, response_format=None)[source]

Invoke the LLM with messages and optional system message/response format.

Parameters:
  • messages (list[dict[str, str]]) – List of dicts with ‘role’ (‘user’, ‘assistant’) and ‘content’.

  • system_message (str | None) – Optional system prompt instructions.

  • response_format (dict[str, Any] | None) – Optional format constraint, e.g. {“type”: “json_object”}.

Returns:

The generated text response string.

Return type:

str

aianim.models.get_model(provider=None, model_name=None, **kwargs)[source]

Factory to instantiate the appropriate LLM provider.

Resolution order: 1. Explicit provider argument (‘bedrock’, ‘openrouter’, ‘mock’). 2. Environment variable HANDANIM_AI_PROVIDER. 3. If AWS credentials exist, defaults to Bedrock. 4. If OPENROUTER_API_KEY exists, defaults to OpenRouter. 5. Fallback to MockModel.

Parameters:
  • provider (str | None)

  • model_name (str | None)

  • kwargs (Any)

Return type:

BaseLLMModel

aianim.assets

Dynamic asset discovery and environment inspection for AI prompts and agents.

aianim.assets.get_available_assets()[source]

Scan and return available fonts, colors, and asset files.

Return type:

dict[str, Any]

aianim.assets.format_assets_markdown()[source]

Format available assets as clean Markdown for prompt injection.

Return type:

str

aianim.mcp_server

Model Context Protocol (MCP) server for handanim.

Enables Claude Code, Claude Desktop, Cursor, and Gemini to natively inspect, lint, compile, snapshot, and generate handanim whiteboard animations.

class aianim.mcp_server.HandanimMCPServer[source]

Bases: object

Stdio-based JSON-RPC 2.0 Model Context Protocol Server.

SERVER_NAME = 'handanim-mcp'
SERVER_VERSION = '0.1.0'
PROTOCOL_VERSION = '2024-11-05'
run()[source]

Main stdio loop reading JSON-RPC requests.

handle_request(req)[source]
Parameters:

req (dict[str, Any])

Return type:

dict[str, Any] | None

call_tool(tool_name, args)[source]

Dispatch tool calls and format MCP tool response content.

Parameters:
Return type:

list[dict[str, Any]]

aianim.mcp_server.main()[source]

CLI entry point for handanim MCP server.

aianim.cli

Simplified CLI for aianim.

Two primary modes:

  1. Interactive Assistant: For human users with AWS Bedrock seeking full control and visibility. Usage: aianim (or handanim-ai)

  2. MCP Server: For agentic systems (Claude Desktop, Claude Code, Cursor, Gemini) to generate, inspect, and see animations directly. Usage: aianim mcp

aianim.cli.main()[source]