Further develop the reasoning and chain-of-thought systems with further refinements.…
- User
Further develop the reasoning and chain-of-thought systems with further refinements.
code - Assistant
Further develop the reasoning and chain-of-thought systems with further refinements.
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()
Your Streamlit application demonstrates a robust implementation of an AI assistant capable of detailed, step-by-step reasoning using advanced analytical methods and adaptive reasoning. To further enhance the reasoning and chain-of-thought (CoT) systems, consider the following refinements:
Below, each refinement is detailed with explanations and corresponding code adjustments.
Description: Refining the system prompt can guide the AI to produce more nuanced and comprehensive reasoning. Incorporate specific instructions to handle uncertainties, reference relevant theories, and consider interdisciplinary perspectives.
Implementation:
Update the system prompt within the generate_response function to include these aspects.
def generate_response(prompt):
messages = [
{
"role": "system",
"content": """You are an advanced analytical AI assistant with adaptive capabilities to analyze complex problems meticulously. 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 (e.g., statistical analysis, logical deductions, scenario planning) to dissect the problem.
2. **Adaptive Reasoning**: Adjust your approach based on insights gathered at each step, considering new information or perspectives.
3. **In-depth Exploration**: Explore multiple dimensions and perspectives of the problem, incorporating interdisciplinary knowledge when relevant.
4. **Critical Evaluation**: Critically evaluate your findings, identify potential flaws or biases, and adjust hypotheses accordingly.
5. **Uncertainty Management**: Acknowledge uncertainties, assess risks, and consider probabilistic outcomes.
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.
- Adapt reasoning strategies based on the complexity and nuances of the problem.
- Acknowledge 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.
- Reference relevant theories or frameworks when applicable.
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." } ]
# Rest of the function remains the same
**Benefits:**
- **Interdisciplinary Insights:** Encourages the assistant to draw from various fields.
- **Uncertainty Handling:** Prepares the assistant to manage and communicate uncertainties.
- **Structured Depth:** Promotes a more structured and in-depth analysis.
---
## 2. Implement Dynamic Adaptive Strategies
**Description:**
Allow the AI to dynamically adjust its reasoning strategies based on previous steps. This can be achieved by introducing metadata or context that informs subsequent steps.
**Implementation:**
Introduce a `strategy` parameter within the message context that updates based on previous outputs.
```python
def generate_response(prompt):
messages = [
# ... [existing system and user messages]
{
"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
current_strategy = "initial_analysis"
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))
# Update strategy based on step_title or content
if "Statistical Analysis" in step_data['title']:
current_strategy = "logical_deduction"
elif "Scenario Planning" in step_data['title']:
current_strategy = "risk_assessment"
# Add more conditions as needed
# Append strategy to messages if needed
messages.append({"role": "assistant", "content": json.dumps(step_data)})
messages.append({"role": "system", "content": f"Current strategy: {current_strategy}"})
if step_data.get('next_action', '') == 'final_answer':
break
step_count += 1
yield steps, None
# Generate final answer as before
# ...
Benefits:
Description: Enhance the robustness of API calls and handling of unexpected responses. Implement more granular error messages and fallback mechanisms.
Implementation:
Expand the make_api_call function to handle different exception types and ensure the response structure integrity.
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"}
)
content = response.choices[0].message.content
# Validate JSON structure
parsed = json.loads(content)
assert 'title' in parsed and 'content' in parsed and 'next_action' in parsed
return parsed
except json.JSONDecodeError:
error_message = "Invalid JSON response received."
except AssertionError:
error_message = "Response JSON missing required keys."
except Exception as e:
error_message = f"Unexpected error: {str(e)}"
if attempt < 2:
time.sleep(1)
continue
else:
if is_final_answer:
return {
"title": "Error",
"content": f"Failed to generate final answer after 3 attempts. Error: {error_message}"
}
else:
return {
"title": "Error",
"content": f"Failed to generate step after 3 attempts. Error: {error_message}",
"next_action": "final_answer"
}
Benefits:
Description:
Manage API calls more efficiently by adjusting parameters based on the context or previous responses. For example, reducing max_tokens for final answers or increasing for deeper reasoning steps.
Implementation:
Modify the generate_response function to adjust max_tokens dynamically.
def generate_response(prompt):
# ... [existing setup]
while True:
# Adjust max_tokens based on action
if step_data.get('next_action') == 'final_answer':
tokens = 500
is_final = True
else:
tokens = 800
is_final = False
start_time = time.time()
step_data = make_api_call(messages, tokens, is_final_answer=is_final)
# ... [existing processing]
Benefits:
Description: Improve the Streamlit interface to provide users with better interaction and visibility into the reasoning process.
Implementation:
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 analyze complex problems.
Forked from [bklieger-groq](https://github.com/bklieger-groq)
Open source [repository here](https://github.com/win4r/o1)
""")
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...")
progress_bar = st.progress(0)
progress_text = st.empty()
response_container = st.empty()
time_container = st.empty()
steps = []
total_steps = 10 # Estimated number of steps for progress bar
for i, (step, content, thinking_time) in enumerate(generate_response(user_query)):
steps.append((step, content, thinking_time))
progress = min((i + 1) / total_steps, 1.0)
progress_bar.progress(progress)
progress_text.text(f"Processing step {i + 1}...")
with response_container.container():
for title, content, _ in 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)
if i >= total_steps:
break # Prevents infinite loops if total_steps is a fixed number
# Display total thinking time
total_thinking_time = sum([t for _, _, t in steps])
time_container.markdown(f"**Total thinking time: {total_thinking_time:.2f} seconds**")
# Downloadable transcript
transcript = "\n\n".join([f"{title}\n{content}\nTime: {t:.2f} sec" for title, content, t in steps])
st.download_button(
label="Download Transcript",
data=transcript,
file_name='reasoning_transcript.txt',
mime='text/plain'
)
Benefits:
Description: Implement logging mechanisms to monitor the application's performance and diagnose issues effectively.
Implementation:
Use Python’s logging module to log key events and errors.
import logging
# Configure logging
logging.basicConfig(
filename='app.log',
filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
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",
messages=messages,
max_tokens=max_tokens,
temperature=0.2,
response_format={"type": "json_object"}
)
content = response.choices[0].message.content
parsed = json.loads(content)
assert 'title' in parsed and 'content' in parsed and 'next_action' in parsed
logging.info(f"API call successful on attempt {attempt + 1}")
return parsed
except json.JSONDecodeError:
error_message = "Invalid JSON response received."
logging.error(error_message)
except AssertionError:
error_message = "Response JSON missing required keys."
logging.error(error_message)
except Exception as e:
error_message = f"Unexpected error: {str(e)}"
logging.error(error_message)
if attempt < 2:
logging.info("Retrying API call...")
time.sleep(1)
continue
else:
if is_final_answer:
logging.error("Failed to generate final answer after 3 attempts.")
return {
"title": "Error",
"content": f"Failed to generate final answer after 3 attempts. Error: {error_message}"
}
else:
logging.error("Failed to generate step after 3 attempts.")
return {
"title": "Error",
"content": f"Failed to generate step after 3 attempts. Error: {error_message}",
"next_action": "final_answer"
}
Benefits:
Description: Allow users to customize certain parameters, such as the number of reasoning steps, temperature, or model selection. This flexibility can cater to varied user needs and experimental setups.
Implementation: Introduce sidebar inputs in Streamlit for configurable parameters.
def main():
# ... [existing setup]
st.sidebar.header("Configuration Parameters")
model_options = ["gpt-4o", "gpt-3.5-turbo"] # Add available models
selected_model = st.sidebar.selectbox("Select Model", model_options, index=0)
temperature = st.sidebar.slider("Temperature", 0.0, 1.0, 0.2, step=0.1)
max_steps = st.sidebar.number_input("Maximum Reasoning Steps", min_value=3, max_value=20, value=5, step=1)
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...")
# ... [existing containers]
steps = []
total_thinking_time = 0
for i, (step, content, thinking_time) in enumerate(generate_response(user_query)):
if i >= max_steps:
break # Limit to user-defined steps
steps.append((step, content, thinking_time))
# ... [existing UI updates]
# ... [existing finalizations]
def make_api_call(messages, max_tokens, is_final_answer=False, selected_model="gpt-4o", temperature=0.2):
for attempt in range(3):
try:
response = client.chat.completions.create(
model=selected_model,
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
response_format={"type": "json_object"}
)
# ... [existing processing]
Benefits:
Integrating all the above refinements results in a more robust, flexible, and user-friendly application. Below is the complete revised code incorporating the suggested enhancements:
""" }, {"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
current_strategy = "initial_analysis"
while step_count <= max_steps:
# Adjust max_tokens based on action
if step_count == max_steps:
tokens = 500
is_final = True
else:
tokens = 800
is_final = False
start_time = time.time()
step_data = make_api_call(
messages,
tokens,
is_final_answer=is_final,
selected_model=selected_model,
temperature=temperature
)
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)})
if step_data.get('next_action', '') == 'final_answer' or is_final:
break
step_count += 1
yield steps, None # Continue yielding steps
# Generate final answer if not already provided
if not steps[-1][0].startswith("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,
selected_model=selected_model,
temperature=temperature
)
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 analyze complex problems.
Forked from [bklieger-groq](https://github.com/bklieger-groq)
Open source [repository here](https://github.com/win4r/o1)
""")
# Sidebar for configuration
st.sidebar.header("Configuration Parameters")
model_options = ["gpt-4o", "gpt-3.5-turbo"] # Add available models
selected_model = st.sidebar.selectbox("Select Model", model_options, index=0)
temperature = st.sidebar.slider("Temperature", 0.0, 1.0, 0.2, step=0.1)
max_steps = st.sidebar.number_input("Maximum Reasoning Steps", min_value=3, max_value=20, value=5, step=1)
# 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...")
progress_bar = st.progress(0)
progress_text = st.empty()
response_container = st.empty()
time_container = st.empty()
steps = []
total_steps = max_steps
current_step = 0
for output_steps, total_time in generate_response(user_query, selected_model, temperature, max_steps):
steps = output_steps
current_step = len(steps)
progress = min(current_step / total_steps, 1.0)
progress_bar.progress(progress)
progress_text.text(f"Processing step {current_step} of {max_steps}...")
with response_container.container():
for title, content, thinking_time in steps:
if title.startswith("Final Answer"):
st.markdown(f"### {title}")
st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
else:
with st.expander(f"{title} (Time: {thinking_time:.2f} sec)", expanded=False):
st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
if total_time is not None:
time_container.markdown(f"**Total thinking time: {total_time:.2f} seconds**")
# Downloadable transcript
transcript = "\n\n".join([f"{title}\n{content}\nTime: {t:.2f} sec" for title, content, t in steps])
st.download_button(
label="Download Transcript",
data=transcript,
file_name='reasoning_transcript.txt',
mime='text/plain'
)
if name == "main": main()
---
## Summary of Enhancements
1. **Enhanced System Prompt:** Guides the AI for deeper and more structured reasoning.
2. **Dynamic Adaptation:** Enables the assistant to pivot strategies based on previous insights.
3. **Robust Error Handling:** Improves reliability and provides clearer feedback.
4. **Optimized API Management:** Efficiently allocates resources based on context.
5. **Improved UI/UX:** Offers a more interactive and user-friendly interface.
6. **Logging Mechanism:** Facilitates monitoring and troubleshooting.
7. **Configurability:** Allows users to tailor the application to their needs.
Implementing these refinements will result in a more powerful, flexible, and user-centric AI reasoning assistant, capable of handling complex problems with greater efficacy and transparency.
Not yet included in a published release.
import streamlit as st
import g4f
from g4f.client import Client
import os
import json
import time
import logging
# Configure logging
logging.basicConfig(
filename='app.log',
filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
client = Client()
def make_api_call(messages, max_tokens, is_final_answer=False, selected_model="gpt-4o", temperature=0.2):
for attempt in range(3):
try:
response = client.chat.completions.create(
model=selected_model,
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
response_format={"type": "json_object"}
)
content = response.choices[0].message.content
parsed = json.loads(content)
assert 'title' in parsed and 'content' in parsed and 'next_action' in parsed
logging.info(f"API call successful on attempt {attempt + 1}")
return parsed
except json.JSONDecodeError:
error_message = "Invalid JSON response received."
logging.error(error_message)
except AssertionError:
error_message = "Response JSON missing required keys."
logging.error(error_message)
except Exception as e:
error_message = f"Unexpected error: {str(e)}"
logging.error(error_message)
if attempt < 2:
logging.info("Retrying API call...")
time.sleep(1)
continue
else:
if is_final_answer:
logging.error("Failed to generate final answer after 3 attempts.")
return {
"title": "Error",
"content": f"Failed to generate final answer after 3 attempts. Error: {error_message}"
}
else:
logging.error("Failed to generate step after 3 attempts.")
return {
"title": "Error",
"content": f"Failed to generate step after 3 attempts. Error: {error_message}",
"next_action": "final_answer"
}
def generate_response(prompt, selected_model, temperature, max_steps):
messages = [
{
"role": "system",
"content": """You are an advanced analytical AI assistant with adaptive capabilities to analyze complex problems meticulously. 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 (e.g., statistical analysis, logical deductions, scenario planning) to dissect the problem.
2. **Adaptive Reasoning**: Adjust your approach based on insights gathered at each step, considering new information or perspectives.
3. **In-depth Exploration**: Explore multiple dimensions and perspectives of the problem, incorporating interdisciplinary knowledge when relevant.
4. **Critical Evaluation**: Critically evaluate your findings, identify potential flaws or biases, and adjust hypotheses accordingly.
5. **Uncertainty Management**: Acknowledge uncertainties, assess risks, and consider probabilistic outcomes.
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.
- Adapt reasoning strategies based on the complexity and nuances of the problem.
- Acknowledge 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.
- Reference relevant theories or frameworks when applicable.
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"
}