AI Prompt Engineering Demo
Recursive Self-Improvement (RSI) – Prompt Template
A configurable system prompt for an RSI-focused agent. Edit the variables
directly in the template, then copy it into your LangChain or AutoGen workflow.
Each {variable} is a
placeholder you replace at runtime.
Education – AI-Enhanced Learning Template
Swap in education-focused variables to generate prompts for adaptive learning, cognitive-principle integration, and classroom implementation strategies. This template is designed for instructors and instructional designers.
LangChain – ChatPromptTemplate for RSI
A chat-style template using system + human message roles. Variables are injected from JSON, YAML config, or a form at runtime. This is the recommended approach for models that support chat completions (GPT-4, Claude, etc.).
from langchain_core.prompts import ChatPromptTemplate
rsi_chat_prompt = ChatPromptTemplate.from_messages([
(
"system",
"You are a {role} specializing in {domain_expertise}.\n\n"
"Objective: {primary_objective}.\n\n"
"Context:\n"
"- Target audience: {audience_type}\n"
"- Knowledge level: {knowledge_level}\n"
"- Use case: {use_case}\n\n"
"Instructions:\n"
"- Define {core_concept} clearly and precisely.\n"
"- Explain the core loop: {process_steps}.\n"
"- Describe enabling mechanisms: {mechanisms_list}.\n"
"- Include a simplified pseudocode sketch of the system.\n"
"- Analyze constraints: {limitations}.\n"
"- Evaluate risks: {risk_types}.\n"
"- Compare with {comparison_domain}.\n"
"- Provide {number_of_examples} example(s): {example_type}.\n"
"- Include current research status and open challenges.\n\n"
"Constraints:\n"
"- Length: {word_range}\n"
"- Tone: {tone_style}\n"
"- Clarity level: {clarity_level}\n\n"
"Output format:\n"
"- Structure: {structure_type}\n"
"- Include pseudocode: {include_pseudocode}\n"
"- Include analogies: {include_analogies}\n"
"- Avoid: {exclusions}"
),
("human", "{user_query}"),
])
# Invoke with variable values
chain = rsi_chat_prompt | llm
response = chain.invoke({
"role": "AI Research Scientist",
"domain_expertise": "recursive self-improvement and alignment",
"primary_objective": "Explain RSI architectures comprehensively",
"audience_type": "graduate ML students",
"knowledge_level": "intermediate",
"use_case": "lecture preparation",
"core_concept": "Recursive Self-Improvement",
"process_steps": "evaluate → plan → modify → validate → repeat",
"mechanisms_list": "gradient-based weight updates, prompt optimization, code generation",
"limitations": "compute cost, credit assignment, alignment stability",
"risk_types": "objective mis-specification, capability gain, deceptive alignment",
"comparison_domain": "evolutionary algorithms",
"number_of_examples": "2",
"example_type": "concrete",
"word_range": "800–1200 words",
"tone_style": "academic but accessible",
"clarity_level": "high",
"structure_type": "sections with headers",
"include_pseudocode": "yes",
"include_analogies": "yes",
"exclusions": "no ungrounded speculation",
"user_query": "Explain the RSI loop with a concrete example.",
})
LangChain – PromptTemplate for RSI
The simpler string-based template using PromptTemplate.from_template().
Best for legacy models, single-turn completions, or when you need to pass the
full formatted string to a non-chat endpoint.
from langchain_core.prompts import PromptTemplate
rsi_prompt = PromptTemplate(
input_variables=[
"role", "domain_expertise", "audience_type",
"core_concept", "process_steps", "mechanisms_list",
"limitations", "risk_types", "comparison_domain",
"number_of_examples", "example_type",
"word_range", "tone_style", "clarity_level", "exclusions",
],
template="""You are a {role} specializing in {domain_expertise}.
Your job:
- Explain and analyze recursive self-improvement (RSI) in AI systems.
- Maintain conceptual rigor while staying understandable to {audience_type}.
- Explicitly separate current reality from speculative scenarios.
You must:
- Define {core_concept} clearly.
- Explain the RSI loop: {process_steps}.
- Describe enabling mechanisms: {mechanisms_list}.
- Include at least one pseudocode-style sketch of an RSI loop.
- Analyze constraints: {limitations}.
- Evaluate risks: {risk_types}.
- Compare RSI with {comparison_domain}.
- Provide {number_of_examples} {example_type} example(s).
- Summarize current research status and open challenges.
Style constraints:
- Length: {word_range}.
- Tone: {tone_style}.
- Clarity level: {clarity_level}.
- Avoid: {exclusions}."""
)
# Format and use
formatted = rsi_prompt.format(
role="AI Safety Researcher",
domain_expertise="recursive self-improvement and alignment",
audience_type="technical policymakers",
core_concept="Recursive Self-Improvement",
process_steps="evaluate → plan → modify → validate → repeat",
mechanisms_list="gradient-based updates, prompt optimization, code synthesis",
limitations="compute cost, credit assignment, alignment stability",
risk_types="objective mis-specification, deceptive alignment",
comparison_domain="evolutionary algorithms",
number_of_examples="2",
example_type="concrete",
word_range="800–1200 words",
tone_style="authoritative but non-alarmist",
clarity_level="high",
exclusions="ungrounded speculation, science fiction scenarios",
)
# Pass to any LLM
response = llm.invoke(formatted)
AutoGen – RSI Agent System Prompt
How to wire the RSI template into a Microsoft AutoGen multi-agent conversation. The system message drives the assistant agent's behavior; the user proxy handles human-in-the-loop control.
import autogen
# ── Configuration ──
llm_config = {
"model": "gpt-4",
"temperature": 0.7,
"api_key": "your-api-key-here", # or set OPENAI_API_KEY env var
}
# ── System prompt (formatted at definition time) ──
RSI_SYSTEM_MESSAGE = """You are an AI Research Scientist specializing in \
recursive self-improvement and alignment.
Your job:
- Explain and analyze RSI in AI systems with conceptual rigor.
- Stay understandable to graduate-level ML students.
- Explicitly separate current reality from speculation.
You must:
- Define Recursive Self-Improvement clearly.
- Explain the RSI loop: evaluate → plan → modify → validate → repeat.
- Describe enabling mechanisms: gradient-based updates, prompt optimization.
- Include a pseudocode sketch of an RSI loop.
- Analyze constraints: compute cost, credit assignment, stability.
- Evaluate risks: objective mis-specification, deceptive alignment.
- Compare RSI with evolutionary algorithms.
- Provide 2 concrete examples.
- Summarize current research and open challenges.
Style: academic but accessible, 800–1200 words, high clarity.
Avoid: ungrounded speculation, science fiction scenarios.
When responding:
- Use clear headers and bullet points.
- Flag speculative claims with "[Speculative]".
- End with a "Key Takeaways" section."""
# ── Agents ──
rsi_agent = autogen.AssistantAgent(
name="RSI_Expert",
llm_config=llm_config,
system_message=RSI_SYSTEM_MESSAGE,
max_consecutive_auto_reply=3,
)
user_proxy = autogen.UserProxyAgent(
name="User",
human_input_mode="ALWAYS",
max_consecutive_auto_reply=0,
code_execution_config=False,
)
# ── Start conversation ──
user_proxy.initiate_chat(
rsi_agent,
message="Explain the RSI loop in detail with a concrete example.",
)
# ── Multi-agent variant (with a critic) ──
critic = autogen.AssistantAgent(
name="Critic",
llm_config=llm_config,
system_message=(
"You are a critical reviewer. Check the RSI Expert's response for: "
"accuracy, speculation vs. evidence, logical gaps, and missing caveats. "
"Be concise and constructive."
),
)
groupchat = autogen.GroupChat(
agents=[user_proxy, rsi_agent, critic],
messages=[],
max_round=6,
)
manager = autogen.GroupChatManager(
groupchat=groupchat, llm_config=llm_config
)
user_proxy.initiate_chat(
manager,
message="Walk me through a full RSI architecture with safety constraints.",
)
Integrate with a Backend API
To move from this static prototype to a working application, follow these steps to connect the prompt templates to a real LLM backend. Each step builds on the previous one.
Set up the API server
Create a FastAPI or Flask endpoint that accepts JSON with template variables and the template name. Validate input with Pydantic models.
Register your templates
Load prompt templates from a .yaml or
.json file at startup. Map template
names to their string definitions and required variable schemas.
Format and validate
Use Python's str.format() or LangChain's
.format() to inject variables. Catch
KeyError for missing variables and
return a 422 response.
Call the LLM
Pass the formatted prompt to OpenAI, Anthropic, or a local model via their
SDK. Use streaming (stream=True) for
real-time output in the frontend.
Stream the response
Use Server-Sent Events (SSE) or WebSocket to stream tokens to the browser. This gives users immediate feedback instead of waiting for the full response.
Connect the frontend
Replace the static textareas with fetch()
calls to your API endpoint. Wire the "Generate" button to trigger the stream
and render tokens into the output area.
Live Generation Preview
This is a mock preview of what the live generation experience would look like. Fill in a few variables and hit Generate to see a simulated streaming response.
Template Variables
Generated Response
Fill in the variables and click Generate to see a simulated response.