Self-Review Encount: Concept and Framework
Self-Review Encount is a structured, reflective, and iterative self-assessment methodology that empowers individuals to evaluate their own work with the rigor and objectivity typically associated with external reviewers. This method fosters personal growth, enhances the quality of work, and cultivates critical thinking by encouraging individuals to adopt an outsider's perspective on their own outputs.
Concept Overview
-
Objective: To enable individuals to critically analyze their own work systematically, identifying strengths, weaknesses, and areas for improvement as an external reviewer would.
-
Philosophy: Emulates the impartiality and thoroughness of an external review, promoting self-awareness and continuous improvement.
-
Application Areas: Applicable across various domains, including academic writing, project management, creative endeavors, professional reports, and personal development plans.
Framework Components
-
Preparation Phase
- Selection of Work: Identify the specific piece of work to be reviewed.
- Establishment of Criteria: Define clear, objective criteria or standards against which the work will be evaluated.
- Setting Objectives: Outline what you aim to achieve through the review (e.g., identify gaps, improve clarity, enhance effectiveness).
-
Objective Assessment
- Structural Evaluation: Examine the organization, coherence, and logical flow of the work.
- Content Analysis: Assess the accuracy, relevance, and depth of the content.
- Compliance Check: Ensure adherence to predefined standards, guidelines, or requirements.
-
Critical Analysis
- Strength Identification: Highlight areas where the work excels.
- Weakness Identification: Pinpoint aspects that require improvement.
- Evidence-Based Insights: Use specific examples from the work to support evaluations.
-
Reflection
- Impact Consideration: Reflect on how the identified strengths and weaknesses affect the overall effectiveness of the work.
- Bias Awareness: Acknowledge any personal biases that may influence the review.
- Perspective Shift: Consider alternative viewpoints or interpretations.
-
Actionable Recommendations
- Improvement Strategies: Develop concrete steps to address weaknesses and build on strengths.
- Prioritization: Determine which recommendations are most critical to implement.
- Resource Allocation: Identify the resources (time, tools, information) needed to execute recommendations.
-
Revision and Iteration
- Implementation: Apply the recommended changes to the work.
- Feedback Integration: Incorporate feedback from any further reviews or reflections.
- Continuous Improvement: Repeat the review process periodically to maintain and enhance quality.
-
Final Review
- Comprehensive Evaluation: Conduct a final assessment to ensure all objectives have been met.
- Confirmation of Standards: Verify that the revised work aligns with established criteria.
- Documentation: Record insights and outcomes from the review for future reference.
Integration into the Existing Streamlit Application
To integrate the Self-Review Encount method into your existing Streamlit application, we will enhance the user interface to accommodate the self-review process and modify the backend logic to guide users through the self-assessment steps. The integration will involve the following additions:
-
User Interface Enhancements
- Mode Selection: Allow users to choose between different modes, such as "Problem Analysis" (existing functionality) and "Self-Review Encount."
- Input Sections: Provide dedicated input areas for users to submit the work they wish to review.
- Guided Steps: Present step-by-step prompts guiding users through the self-review process.
- Progress Tracking: Visual indicators to show users their progress through the self-review steps.
-
Backend Logic Adjustments
- Self-Review Workflow: Implement a workflow that follows the Self-Review Encount framework, prompting users to perform each phase systematically.
- AI Assistance: Utilize the AI to generate prompts, feedback, and recommendations based on user inputs.
- Data Management: Store and manage input data, review notes, and revision histories.
-
Enhanced Response Generation
- Customized Prompts: Tailor the AI's system messages to align with the self-review methodology.
- Iterative Feedback: Allow the AI to provide iterative feedback after each self-review step.
Below is the modified script incorporating the Self-Review Encount method:
import streamlit as st
import g4f
from g4f.client import Client
import os
import json
import time
client = Client()
def make_api_call(messages, max_tokens, is_final_answer=False):
for attempt in range(3):
try:
response = client.chat.completions.create(
model="gpt-4o", # Adjust the model as needed
messages=messages,
max_tokens=max_tokens,
temperature=0.2,
response_format={"type": "json_object"}
)
return json.loads(response.choices[0].message.content)
except Exception as e:
if attempt == 2:
error_content = f"Failed to generate {'final answer' if is_final_answer else 'step'} after 3 attempts. Error: {str(e)}"
return {
"title": "Error",
"content": error_content,
"next_action": "final_answer" if is_final_answer else "continue"
}
time.sleep(1) # Wait for 1 second before retrying
def generate_response(prompt, mode="analysis"):
if mode == "analysis":
system_prompt = """You are an advanced analytical AI assistant with adaptive capabilities to thoroughly analyze complex problems. Your task is to provide detailed, step-by-step explanations of your thought process using advanced analytical methods, adaptive reasoning, and advanced common-sense reasoning. For each step:
1. **Advanced Analysis**: Apply sophisticated analytical techniques to dissect the problem.
2. **Adaptive Reasoning**: Reflect on previous steps to adjust your approach based on new insights or information.
3. **Common-Sense Reasoning**: Utilize everyday knowledge and logical reasoning to fill in gaps and make sound judgments.
4. **In-depth Exploration**: Explore multiple dimensions and perspectives of the problem.
5. **Critical Evaluation**: Critically evaluate your findings and adjust hypotheses accordingly.
**Response Format:**
Use JSON with keys:
- `"title"`: A clear, concise title describing the current reasoning phase.
- `"content"`: Elaborate on your thought process in this step.
- `"next_action"`: Decide whether to `"continue"` reasoning or provide a `"final_answer"`.
**Key Instructions:**
- Employ at least 5 distinct reasoning steps.
- In each step, explicitly reference relevant parts of previous steps to adapt your reasoning.
- Use advanced analytical methods (e.g., statistical analysis, logical deductions, scenario planning).
- Apply advanced common-sense reasoning to make logical inferences and fill in gaps in information.
- Adapt your reasoning strategies based on the complexity and nuances of the problem.
- Acknowledge your limitations and explicitly state what you can and cannot do.
- Evaluate alternative answers or approaches thoroughly.
- Critically assess your reasoning; identify potential flaws or biases.
- Ensure that your explanations are consistent and coherent throughout the reasoning process.
- Utilize diverse methods to derive or verify your answer.
- Incorporate relevant domain knowledge and best practices.
- Quantify certainty levels for each step and the final conclusion when applicable.
- Consider potential edge cases, exceptions, or unintended consequences.
- Provide clear justifications for eliminating alternative hypotheses.
**Example of a valid JSON response:**
```json
{
"title": "Advanced Statistical Analysis",
"content": "I will perform a statistical analysis to determine... [detailed explanation]... This will help quantify the relationships between variables.",
"next_action": "continue"
}```
"""
elif mode == "self_review":
system_prompt = """You are a self-review facilitator designed to help individuals critically assess their own work as if reviewed by an external expert. Guide the user through each phase of the Self-Review Encount method systematically. For each phase:
1. **Preparation Phase**: Assist in selecting the work, establishing criteria, and setting objectives.
2. **Objective Assessment**: Help evaluate the work's structure, content, and compliance with standards.
3. **Critical Analysis**: Facilitate the identification of strengths and weaknesses with evidence-based insights.
4. **Reflection**: Encourage consideration of the impact of strengths and weaknesses, awareness of biases, and perspective shifts.
5. **Actionable Recommendations**: Aid in developing improvement strategies, prioritizing actions, and allocating resources.
6. **Revision and Iteration**: Support the implementation of changes and integration of feedback.
7. **Final Review**: Guide the comprehensive evaluation, confirmation of standards, and documentation of outcomes.
**Response Format:**
Use JSON with keys:
- `"phase"`: The current phase of the self-review process.
- `"instruction"`: Guidance or questions to assist the user in this phase.
- `"next_phase"`: The next phase to proceed to, or `"completed"` if the review is finished.
**Key Instructions:**
- Provide clear and concise instructions for each phase.
- Encourage deep reflection and critical thinking.
- Offer constructive prompts to uncover insights and areas for improvement.
- Ensure the user progresses through all phases systematically.
- Maintain an objective and supportive tone.
- Facilitate the user’s ability to document their reflections and actions.
**Example of a valid JSON response:**
```json
{
"phase": "Preparation Phase",
"instruction": "Please select the specific piece of work you wish to review and outline the criteria you will use for this assessment.",
"next_phase": "Objective Assessment"
}```
"""
else:
raise ValueError("Invalid mode specified.")
messages = [
{
"role": "system",
"content": system_prompt
},
{"role": "user", "content": prompt}
]
steps = []
step_count = 1
total_thinking_time = 0
summary_of_steps = ""
while True:
start_time = time.time()
# Add summary of previous steps to the messages
if summary_of_steps:
if mode == "analysis":
messages.append({"role": "user", "content": f"Summary of previous steps:\n{summary_of_steps}"})
elif mode == "self_review":
messages.append({"role": "user", "content": f"Summary of previous phases:\n{summary_of_steps}"})
step_data = make_api_call(messages, 800)
end_time = time.time()
thinking_time = end_time - start_time
total_thinking_time += thinking_time
# Update summary of steps for assistant to adapt reasoning
if mode == "analysis":
summary_of_steps += f"Step {step_count} ({step_data['title']}): {step_data['content']}\n\n"
elif mode == "self_review":
summary_of_steps += f"Phase {step_count} ({step_data['phase']}): {step_data['instruction']}\n\n"
if mode == "analysis":
steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
elif mode == "self_review":
steps.append((f"Phase {step_count}: {step_data['phase']}", step_data['instruction'], thinking_time))
# Add the assistant's response to the message history
messages.append({"role": "assistant", "content": json.dumps(step_data)})
if (mode == "analysis" and step_data.get('next_action', '') == 'final_answer') or (mode == "self_review" and step_data.get('next_phase', '') == 'completed'):
break
step_count += 1
# Yield after each step for Streamlit to update
yield steps, None # Total time is yielded at the end
if mode == "analysis":
# Generate final answer
messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
start_time = time.time()
final_data = make_api_call(messages, 500, is_final_answer=True)
end_time = time.time()
thinking_time = end_time - start_time
total_thinking_time += thinking_time
steps.append(("Final Answer", final_data['content'], thinking_time))
elif mode == "self_review":
# Final documentation phase
final_phase = {
"phase": "Final Review",
"instruction": "Conduct a comprehensive evaluation to ensure all objectives have been met and document the insights and outcomes from your self-review.",
"next_phase": "completed"
}
steps.append((f"Phase {step_count + 1}: {final_phase['phase']}", final_phase['instruction'], thinking_time))
total_thinking_time += thinking_time
yield steps, total_thinking_time
def main():
st.set_page_config(page_title="Adaptive AI Reasoning Chains", page_icon="🧠", layout="wide")
st.title("Adaptive AI Assistant with Advanced Analytical and Common-Sense Capabilities")
st.markdown("""
This application utilizes an adaptive AI assistant that applies advanced analytical methods and common-sense reasoning to thoroughly analyze complex problems.
Forked from [bklieger-groq](https://github.com/bklieger-groq)
Open source [repository here](https://github.com/win4r/o1)
""")
# Mode selection
mode = st.sidebar.selectbox(
"Choose Mode",
("Problem Analysis", "Self-Review Encount")
)
if mode == "Problem Analysis":
# Existing functionality
user_query = st.text_input(
"Enter a complex problem for analysis:",
placeholder="e.g., Analyze the potential impacts of implementing a universal basic income."
)
if user_query:
st.write("Generating response...")
# Create empty elements to hold the generated text and total time
response_container = st.empty()
time_container = st.empty()
# Generate and display the response
for steps, total_thinking_time in generate_response(user_query, mode="analysis"):
with response_container.container():
for i, (title, content, thinking_time) in enumerate(steps):
if title.startswith("Final Answer"):
st.markdown(f"### {title}")
st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
else:
with st.expander(title, expanded=False):
st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
# Only show total time when it's available at the end
if total_thinking_time is not None:
time_container.markdown(f"**Total thinking time: {total_thinking_time:.2f} seconds**")
elif mode == "Self-Review Encount":
st.header("Self-Review Encount")
st.markdown("""
Welcome to the **Self-Review Encount** tool. This guided process will help you critically assess your own work systematically, emulating the perspective of an external reviewer. Follow each phase carefully to enhance the quality of your work.
""")
# Text area for user to input the work they want to review
user_work = st.text_area(
"Paste your work here for review:",
height=300,
placeholder="e.g., Paste your report, essay, project description, etc., here..."
)
if user_work:
st.write("Starting self-review process...")
# Create empty elements to hold the generated instructions and total time
review_container = st.empty()
review_time_container = st.empty()
# Initiate the self-review process
initial_prompt = f"Review the following work:\n\n{user_work}\n\nBegin the Self-Review Encount process."
for review_steps, total_review_time in generate_response(initial_prompt, mode="self_review"):
with review_container.container():
for i, (phase, instruction, thinking_time) in enumerate(review_steps):
if phase.startswith("Phase"):
st.markdown(f"### {phase}")
st.markdown(instruction.replace('\n', '<br>'), unsafe_allow_html=True)
else:
st.markdown(f"### {phase}")
st.markdown(instruction.replace('\n', '<br>'), unsafe_allow_html=True)
# Only show total time when it's available at the end
if total_review_time is not None:
review_time_container.markdown(f"**Total self-review time: {total_review_time:.2f} seconds**")
# Optionally, provide a section for users to input their reflections or notes
st.markdown("---")
st.subheader("Your Reflections and Notes")
user_reflections = st.text_area(
"Document your reflections, insights, and action plans based on the self-review:"
)
if user_reflections:
st.success("Your reflections have been recorded. Consider revisiting them to implement improvements.")
if __name__ == "__main__":
main()
Explanation of Integration
-
Mode Selection:
- Added a sidebar selection allowing users to choose between "Problem Analysis" and "Self-Review Encount."
-
Self-Review Encount Mode:
- User Input: Introduced a text area where users can paste the work they wish to review.
- Process Initiation: When the user submits their work, the
generate_response function is called with mode="self_review", triggering the Self-Review Encount workflow.
- Phased Guidance: The AI assistant guides the user through each phase of the self-review process, providing instructions and prompts based on the framework.
- Progress Display: Each phase is displayed as an expandable section, allowing users to focus on one phase at a time.
- Reflection Section: Added a section for users to document their reflections and action plans after completing the self-review.
-
Backend Logic Adjustments:
generate_response Function: Modified to accept a mode parameter, allowing it to switch between "analysis" and "self_review" modes.
- System Prompts: Defined distinct system prompts for each mode to tailor the AI's responses according to the desired workflow.
- Response Handling: Structured the AI's responses to align with the phases of the Self-Review Encount method, ensuring a smooth and guided user experience.
-
User Experience Enhancements:
- Clear Instructions: Provided comprehensive instructions and explanations to guide users through the self-review process.
- Interactive Elements: Utilized Streamlit's expandable sections to manage content display effectively, preventing information overload.
- Documentation Encouragement: Encouraged users to document their insights and action plans, reinforcing the self-review's effectiveness.
Usage Workflow
-
Select Mode: On the application sidebar, choose "Self-Review Encount."
-
Input Work: Paste the work you intend to review into the designated text area.
-
Initiate Review: The application begins the self-review process, guiding you through each phase:
- Preparation Phase: Define what you're reviewing and set criteria.
- Objective Assessment: Evaluate structure, content, and compliance.
- Critical Analysis: Identify strengths and weaknesses.
- Reflection: Consider the impact of your findings and acknowledge biases.
- Actionable Recommendations: Develop strategies for improvement.
- Revision and Iteration: Implement changes based on your recommendations.
- Final Review: Conduct a comprehensive evaluation and document outcomes.
-
Document Reflections: After completing the phases, use the "Your Reflections and Notes" section to record your insights and action plans.
-
Review and Implement: Revisit your reflections to implement the necessary improvements effectively.
Conclusion
By integrating the Self-Review Encount method into your Streamlit application, users gain a powerful tool for self-assessment that mirrors the thoroughness of external reviews. This enhancement not only broadens the application's functionality but also fosters a culture of continuous improvement and critical self-reflection among its users.