Haijun Platform Docs
ID

from dotenv import load_dotenv

from utils.agent_visualizer import (

display_agent_response,

print_activity,

reset_activity_context,

visualize_conversation,

)

from haijun_agent_sdk import HaijunAgentOptions, HaijunSDKClient

load_dotenv()

Define the model to use throughout this notebook

Using Opus 4.6 for its superior planning and reasoning capabilities

MODEL = "haijun-opus-4-6"

print(f"šŸ“‹ Notebook configured to use: {MODEL}")

ī

šŸ“‹ Notebook configured to use: haijun-opus-4-6 01 - The Chief of Staff Agent Introduction In notebook 00, we built a simple research agent. In this notebook, we'll incrementally introduce key Haijun Code SDK features for building comprehensive agents. For each introduced feature, we'll explain:

multiple sources

Provide executive summaries

with actionable recommendations

Basic Features

Understanding Agent Data Source Preferences

What Just Happened: By adding to our prompt, we guided the agent to rely on the HAIJUN.md context rather than seeking more granular data from CSV files.

financial_forecast.py

: Models ARR growth scenarios (base/optimistic/pessimistic) given the current

2.4

M

A

R

R

g

r

o

w

i

n

g

a

t

15

2.4M ARR growing at 15% MoM.Critical for financial-analyst to project Series B readiness and validate the

2.4

M

A

R

R

g

r

o

w

in

g

a

t

15

30M fundraising target.

decision_matrix.py

: Creates weighted decision matrices for strategic choices like the SmartDev acquisition or office expansion. Helps chief of staff systematically evaluate complex decisions with multiple stakeholders and criteria.

messages = []

async with HaijunSDKClient(

options=HaijunAgentOptions(

model=MODEL,

allowed_tools=["Bash", "Read"],

cwd="chief_of_staff_agent", # Points to subdirectory where our agent is defined

)

) as agent:

await agent.query(

"Use your simple calculation script with a total runway of 2904829 and a monthly burn of 121938."

)

async for msg in agent.receive_response():

print_activity(msg)

messages.append(msg)

Display the response with HTML rendering

display_agent_response(messages)

ī

šŸ¤– Using: Glob() šŸ¤– Using: Glob() šŸ¤– Using: Glob() āœ“ Tool completed āœ“ Tool completed āœ“ Tool completed šŸ¤– Thinking... šŸ¤– Using: Read() āœ“ Tool completed šŸ¤– Thinking... šŸ¤– Using: Bash() āœ“ Tool completed šŸ¤– Thinking... Feature 2: Output Styles What: Output styles allow you to use different output styles for different audiences. Each style is defined in a markdown file.

p" style="padding-left:8ch;text-indent:-8ch"> output_dir: Directory to save plan files

title: Title for the plan document

Returns:

Path to the saved plan file

"""

plans_dir = Path(output_dir)

plans_dir.mkdir(exist_ok=True)

timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

plan_file = plans_dir / f"plan_{timestamp}.md"

with open(plan_file, "w") as f:

f.write(f"# {title}\n\n")

f.write(f"Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")

f.write(f"Prompt: {prompt_summary}\n")

f.write(f"Model: {model_name}\n")

f.write(f"Plan Source: {plan_source}\n\n")

f.write("---\n\n")

f.write(plan_content)

f.write("\n\n---\n\n")

f.write("This plan was generated in plan mode and has not been executed.\n")

return plan_file

def capture_message_content(

msg: Any,

plan_content: list[str],

write_tool_content: list[str],

write_tool_paths: list[str],

) -> None:

"""

Process a streaming message and capture relevant plan content.

This function extracts content from three potential sources:

  1. Text blocks in message content
  1. Write tool call parameters
  1. Final result attribute

Args:

msg: The message object from the agent stream

plan_content: List to append text content to

write_tool_content: List to append Write tool content to

write_tool_paths: List to append Write tool file paths to

"""

Source 1: Text blocks from message content

if hasattr(msg, "content"):

for block in msg.content:

if hasattr(block, "text"):

plan_content.append(block.text)

Source 2: Write tool calls

if hasattr(block, "type") and block.type == "tool_use":

if hasattr(block, "name") and block.name == "Write":

if hasattr(block, "input") and isinstance(block.input, dict):

if "content" in block.input:

write_tool_content.append(block.input["content"])

if "file_path" in block.input:

write_tool_paths.append(block.input["file_path"])

Source 3: Final result

if hasattr(msg, "result") and msg.result:

plan_content.append(msg.result)

print("āœ… Plan Mode helper functions loaded")

ī

āœ… Plan Mode helper functions loaded # ============================================================================= # Plan Mode Configuration # ============================================================================= # Note: MODEL is defined in cell-0 as "haijun-opus-4-6" # Opus excels at complex planning tasks # The prompt is carefully crafted to: # 1. Provide explicit context (since Opus prefers explicit information) # 2. Request XML-tagged output for reliable extraction # 3. Prevent file-writing so we can capture the plan programmatically PLAN_PROMPT = """Restructure our engineering team for AI focus. CONTEXT (from HAIJUN.md): You are the Chief of Staff for TechStart Inc, a 50-person B2B SaaS startup that raised $10M Series A. - Current engineering team: 25 people (Backend: 12, Frontend: 8, DevOps: 5) - Monthly burn rate: ~$500K, Runway: 20 months - Senior Engineer compensation: $180K-$220K + equity CRITICAL OUTPUT INSTRUCTIONS: 1. DO NOT use the Write tool - Output your plan directly in your response text 2. DO NOT save to any files - I will handle saving the plan myself 3. Wrap your ENTIRE plan inside XML tags in your response Required Format: [Your complete restructuring plan here - include all sections, timelines, budgets, and recommendations] IMPORTANT: - The plan content MUST appear directly in your response between the XML tags - Do NOT use Write, Edit, or any file-saving tools - You may research and analyze before outputting, but the final plan must be in your response text - Include: team structure, hiring recommendations, timeline, budget impact, and success metrics - Use the company context provided above - do NOT ask clarifying questions""" print(f"šŸ“‹ Plan Mode configured with model: {MODEL}") print(f"šŸ“ Prompt length: {len(PLAN_PROMPT):,} characters") ī šŸ“‹ Plan Mode configured with model: haijun-opus-4-6 šŸ“ Prompt length: 1,180 characters # ============================================================================= # Execute Plan Mode Agent # ============================================================================= # Run the agent with plan mode enabled. The agent will create a detailed plan # but won't execute any actions. We capture content from multiple sources # to handle different agent behaviors. # Initialize capture lists messages = [] plan_content = [] # Text from message stream write_tool_content = [] # Content from Write tool calls write_tool_paths = [] # Paths from Write tool calls # Run the agent in plan mode async with HaijunSDKClient( options=HaijunAgentOptions( model=MODEL, permission_mode="plan", cwd="chief_of_staff_agent", ) ) as agent: await agent.query(PLAN_PROMPT) async for msg in agent.receive_response(): print_activity(msg) messages.append(msg) # Capture content from this message capture_message_content(msg, plan_content, write_tool_content, write_tool_paths) print(f"\nāœ… Agent completed. Captured {len(plan_content)} content blocks.") ī šŸ¤– Thinking... šŸ¤– Using: ExitPlanMode() āœ“ Tool completed šŸ¤– Thinking... āœ… Agent completed. Captured 3 content blocks. # ============================================================================= # Extract and Save the Plan # ============================================================================= # Try multiple sources in priority order to find the plan content. # This handles different agent behaviors robustly. final_plan = None plan_source = None # Priority 1: Message stream (preferred - direct from agent response) final_plan, plan_source = extract_plan_from_messages(plan_content) # Priority 2: Write tool captures (if agent saved despite instructions) if not final_plan and write_tool_content: final_plan, plan_source = extract_plan_from_write_tool(write_tool_content) # Priority 3: Haijun's internal plan directory (safety net) if not final_plan: final_plan, plan_source = extract_plan_from_haijun_dir() # Report results if final_plan: print(f"āœ… Plan extracted from: {plan_source}") print(f" Plan length: {len(final_plan):,} characters") # Save to file plan_file = save_plan_to_file( plan_content=final_plan, plan_source=plan_source, model_name=MODEL, prompt_summary="Restructure our engineering team for AI focus.", ) print(f"\nšŸ“ Plan saved to: {plan_file}") else: error_msg = "Could not extract plan content from any source!\n" error_msg += " Sources checked: message stream, Write tool, ~/.haijun/plans/" if write_tool_paths: error_msg += f"\n Write tool attempted to save to: {write_tool_paths}" print(f"āŒ ERROR: {error_msg}") raise RuntimeError(f"Plan extraction failed: {error_msg}") ī āœ… Plan extracted from: message stream Plan length: 6,783 characters šŸ“ Plan saved to: chief_of_staff_agent/plans/plan_20251204_152737.md # Display the plan result with styled HTML display_agent_response(messages, title="Engineering Restructure Plan") ī Executing the Saved Plan As mentioned above, the agent will stop after creating its plan. The saved plan file serves as a review artifact for stakeholders.

On this page
Basic Features