Further enhance and further refine the chain-of-thought system and add in a more robust…
- User
Further enhance and further refine the chain-of-thought system and add in a more robust framework.
code - Assistant
Further enhance and further refine the chain-of-thought system and add in a more robust framework.
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:
if is_final_answer:
return {
"title": "Error",
"content": f"Failed to generate final answer after 3 attempts. Error: {str(e)}"
}
else:
return {
"title": "Error",
"content": f"Failed to generate step after 3 attempts. Error: {str(e)}",
"next_action": "final_answer"
}
time.sleep(1) # Wait for 1 second before retrying
def generate_response(prompt):
messages = [
{
"role": "system",
"content": """You are an advanced analytical AI assistant with adaptive capabilities to severely analyze complex problems. Your task is to provide detailed, step-by-step explanations of your thought process using advanced analytical methods and adaptive reasoning. For each step:
1. **Advanced Analysis**: Apply sophisticated analytical techniques to dissect the problem.
2. **Adaptive Reasoning**: Adjust your approach based on the insights gathered at each step.
3. **In-depth Exploration**: Explore multiple dimensions and perspectives of the problem.
4. **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.
- Use advanced analytical methods (e.g., statistical analysis, logical deductions, scenario planning).
- 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.
- 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"
}```
"""
},
{"role": "user", "content": prompt},
{
"role": "assistant",
"content": "Understood. I will proceed to analyze the problem using advanced analytical methods and adaptive reasoning."
}
]
steps = []
step_count = 1
total_thinking_time = 0
while True:
start_time = time.time()
step_data = make_api_call(messages, 800)
end_time = time.time()
thinking_time = end_time - start_time
total_thinking_time += thinking_time
steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
messages.append({"role": "assistant", "content": json.dumps(step_data)})
# Adaptive Reasoning: Modify approach based on previous steps
# (This could be expanded to adjust parameters or strategy)
if step_data.get('next_action', '') == 'final_answer':
break
step_count += 1
# Yield after each step for Streamlit to update
yield steps, None # Total time is yielded at the end
# 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))
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 Capabilities")
st.markdown("""
This application utilizes an adaptive AI assistant that applies advanced analytical methods to severely analyze complex problems.
Forked from [bklieger-groq](https://github.com/bklieger-groq)
Open source [repository here](https://github.com/win4r/o1)
""")
# Text input for user query
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):
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**")
if __name__ == "__main__":
main()
Certainly! I've enhanced and refined the chain-of-thought system in your code to create a more robust framework. Below is the updated code with added features:
make_api_call function with exponential backoff for retries.confidence and reflections.Here's the updated code:
import streamlit as st
import g4f
from g4f.client import Client
import os
import json
import time
import logging
client = Client()
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
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:
logger.error(f"API call failed on attempt {attempt +1}: {e}")
if attempt == 2:
if is_final_answer:
return {
"title": "Error",
"content": f"Failed to generate final answer after 3 attempts. Error: {str(e)}",
"confidence": 0
}
else:
return {
"title": "Error",
"content": f"Failed to generate step after 3 attempts. Error: {str(e)}",
"confidence": 0,
"next_action": "final_answer"
}
time.sleep(2 ** attempt) # Exponential backoff
def generate_response(prompt):
messages = [
{
"role": "system",
"content": """You are an advanced analytical AI assistant with adaptive capabilities to severely analyze complex problems. Your task is to first create a detailed plan outlining the steps you will take to analyze the problem, and then proceed to provide detailed, step-by-step explanations of your thought process using advanced analytical methods and adaptive reasoning. After each step, you will reflect on your reasoning and adjust your plan if necessary.
For each phase:
1. **Planning Phase**: Generate a plan with clear steps you intend to follow.
2. **Advanced Analysis**: Apply sophisticated analytical techniques to dissect the problem.
3. **Self-Reflection**: Reflect on your previous steps to improve future reasoning.
4. **Adaptive Reasoning**: Adjust your approach based on your reflections.
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.
- 'confidence': A numerical value indicating your confidence level in this step out of 100.
- 'next_action': Decide whether to 'continue' reasoning, 'update_plan', or provide a 'final_answer'.
Key Instructions:
- Begin with a Planning Phase before proceeding with the analysis.
- Employ at least 5 distinct reasoning steps.
- Use advanced analytical methods (e.g., statistical analysis, logical deductions, scenario planning).
- Adapt your reasoning strategies based on the complexity and nuances of the problem.
- After each step, reflect on previous reasoning and adjust if necessary.
- 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.
- 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": "Planning Phase",
"content": "I will start by... [outline of steps]... This plan will guide my analysis.",
"confidence": 90,
"next_action": "continue"
}```
"""
},
{"role": "user", "content": prompt},
{
"role": "assistant",
"content": "Understood. I will begin by creating a plan and then proceed with the analysis."
}
]
steps = []
step_count = 1
total_thinking_time = 0
# Step 1: Generate the plan
logger.info("Generating initial plan.")
start_time = time.time()
plan_data = make_api_call(messages, 800)
end_time = time.time()
thinking_time = end_time - start_time
total_thinking_time += thinking_time
steps.append((f"Step {step_count}: {plan_data['title']}", plan_data['content'], plan_data.get('confidence', None), thinking_time))
messages.append({"role": "assistant", "content": json.dumps(plan_data)})
step_count += 1
while True:
logger.info(f"Starting reasoning step {step_count}.")
start_time = time.time()
step_data = make_api_call(messages, 800)
end_time = time.time()
thinking_time = end_time - start_time
total_thinking_time += thinking_time
steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], step_data.get('confidence', None), thinking_time))
messages.append({"role": "assistant", "content": json.dumps(step_data)})
# Check the next action
next_action = step_data.get('next_action', '').lower()
if next_action == 'final_answer':
logger.info("Assistant decided to provide the final answer.")
break
elif next_action == 'update_plan':
# Assistant wants to update the plan
logger.info("Assistant chose to update the plan.")
step_count += 1
continue # Proceed to the next step
else:
# Continue reasoning
logger.info("Assistant will continue reasoning.")
pass
step_count += 1
# Yield after each step for Streamlit to update
yield steps, None # Total time is yielded at the end
# 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'], final_data.get('confidence', None), 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 Capabilities")
st.markdown("""
This application utilizes an adaptive AI assistant that applies advanced analytical methods to severely analyze complex problems.
Forked from [bklieger-groq](https://github.com/bklieger-groq)
Open source [repository here](https://github.com/win4r/o1)
""")
# Text input for user query
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):
with response_container.container():
for i, (title, content, confidence, thinking_time) in enumerate(steps):
if title.startswith("Final Answer"):
st.markdown(f"### {title}")
st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
if confidence is not None:
st.write(f"**Confidence Level:** {confidence}/100")
else:
with st.expander(title, expanded=False):
st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
if confidence is not None:
st.write(f"**Confidence Level:** {confidence}/100")
st.write(f"*Thinking time for this step: {thinking_time:.2f} seconds*")
# 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**")
if __name__ == "__main__":
main()
Planning Phase: The assistant now begins by generating a detailed plan outlining the steps it will take. This is implemented in the generate_response function, where the first API call is made to create the plan.
Self-Reflection and Adaptive Reasoning: After each reasoning step, the assistant reflects on its previous reasoning and decides whether to continue, update the plan, or provide the final answer. This is managed by checking the next_action in the assistant's response.
Confidence Levels: Each response includes a confidence key, indicating the assistant's confidence level for that step out of 100. This helps quantify certainty and is displayed in the Streamlit app.
Enhanced Error Handling: In make_api_call, I've implemented exponential backoff (time.sleep(2 ** attempt)) to handle API failures more gracefully. This reduces the load in case of repeated failures and provides time for transient issues to resolve.
Logging: Added logging statements to trace the execution flow, which can be very helpful for debugging purposes. Logging includes when the plan is generated, each reasoning step starts, and when the assistant decides on the next action.
Expanded Response Format: Updated the Response Format in the system prompt to include confidence and detailed instructions for the assistant.
Dynamic Plan Adjustment: If the assistant decides that the plan needs updating (by setting next_action to update_plan), the code handles this by continuing the loop and allowing the assistant to provide an updated plan.
Display Enhancements: In the Streamlit app, each step's confidence level and thinking time are displayed. This provides users with more insight into the assistant's reasoning process.
streamlit, g4f, etc.).streamlit run your_script_name.py."gpt-4o". Ensure that this model is available in your g4f client setup or adjust as needed.g4f API to avoid interruptions.By incorporating these enhancements, the assistant becomes more robust, transparent, and capable of handling complex analytical tasks with adaptive reasoning and self-improvement mechanisms.
Not yet included in a published release.