You are a programming expert. Carefully review the code. The code is buggy.
import gradio as gr
import uuid
import json
import threading
from datetime import datetime
from typing import Dict, Optional, Any, List, Union
from dataclasses import dataclass, asdict
from enum import Enum
import time
import logging
from threading import Lock
from pydantic import BaseModel, Field, validator
from langchain.chat_models import ChatOpenAI
import gradio as gr
from typing import Dict, Optional, Any, List, Union, Tuple
from pydantic import BaseModel, Field, validator
from enum import Enum
import json
from datetime import datetime
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
import random
from datetime import datetime
from typing import Sequence
from langchain_core.messages import BaseMessage
from langgraph.graph.message import add_messages
from typing_extensions import Annotated, TypedDict
from langchain_core.messages import SystemMessage, trim_messages
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
class WorkflowLLMConfig(BaseModel):
"""Configuration class for all LLMs used in the workflow"""
content_enhancement: LLMConfig = Field(
default_factory=lambda: LLMConfig(
model="gpt-4o-mini",
temperature=0.3,
presence_penalty=0.1
)
)
@validator('goal')
def goal_not_empty(cls, v):
if not v.strip():
raise ValueError('Please enter a workflow goal')
return v.strip()
@validator('output_fields')
def output_fields_not_empty(cls, v):
if not v:
raise ValueError('Please add at least one output field')
return v
class Config:
error_msg_templates = {
'value_error.missing': 'This field is required',
'value_error.empty': 'This field cannot be empty',
}
@dataclass
class SessionState:
"""Represents the current state of a user session"""
user_id: str
workflow_state: Optional[WorkflowState] = None
current_stage: str = "input_collection"
last_active: datetime = None
is_complete: bool = False
llm_config: WorkflowLLMConfig = Field(default_factory=WorkflowLLMConfig)
def create_session(self) -> str:
session_id = str(uuid.uuid4())
self.sessions[session_id] = SessionState(
user_id=session_id,
last_active=datetime.now(),
llm_config=WorkflowLLMConfig()
)
self.locks[session_id] = Lock()
return session_id
def get_session(self, session_id: str) -> Optional[SessionState]:
if session_id in self.sessions:
session = self.sessions[session_id]
session.last_active = datetime.now()
return session
return None
def update_session(self, session_id: str, **updates) -> bool:
if session_id in self.sessions:
with self.locks[session_id]:
for key, value in updates.items():
setattr(self.sessions[session_id], key, value)
self.sessions[session_id].last_active = datetime.now()
return True
return False
def _cleanup_expired_sessions(self):
while True:
current_time = datetime.now()
expired_sessions = [
sid for sid, session in self.sessions.items()
if (current_time - session.last_active).total_seconds() > self.timeout_minutes * 60
]
for sid in expired_sessions:
del self.sessions[sid]
del self.locks[sid]
time.sleep(60)
class GradioWorkflowManager:
def init(self):
self.session_manager = GradioSessionManager()
self.logger = logging.getLogger(name)
code
def enhance_content(self, session_id: str, content: Dict[str, Any]) -> Dict[str, Any]:
"""Enhance content using LLM"""
session = self.session_manager.get_session(session_id)
if not session:
return {"error": "Session expired"}
llm = session.llm_config.content_enhancement.create_llm()
# Add content enhancement logic here using the LLM
return content
class WorkflowPrompts:
"""Collection of prompts for different workflow stages"""
code
CONTENT_ENHANCEMENT_PROMPT = """
As an AI assistant, enhance the following workflow content to be more precise and comprehensive:
Goal: {goal}
Output Fields:
{fields}
Enhance both the goal and field descriptions to be:
1. More specific and actionable
2. Better structured for data extraction
3. Include relevant context and constraints
Return the enhanced content in JSON format with 'enhanced_goal' and 'enhanced_fields' keys.
"""
QUERY_GENERATION_PROMPT = """
Generate {num_queries} diverse example queries that would help extract information for the following workflow:
Goal: {goal}
Required Fields:
{fields}
Each query should:
1. Be natural and conversational
2. Help extract information for multiple fields
3. Cover different aspects of the goal
4. Include edge cases and variations
Return the queries in JSON format with 'queries' key containing an array of query objects.
"""
RESPONSE_GENERATION_PROMPT = """
Generate a response to the following query that extracts information for our workflow:
Workflow Goal: {goal}
Required Fields:
{fields}
Query: {query}
Your response should:
1. Be natural and helpful
2. Extract all relevant field information
3. Ask for clarification if needed
4. Maintain conversation context
Return both a conversational response and structured extracted data in JSON format.
"""
PROMPT_EVALUATION_PROMPT = """
Evaluate the effectiveness of the following prompt for our workflow:
Prompt to Evaluate:
{prompt}
Workflow Context:
Goal: {goal}
Fields: {fields}
Evaluate based on:
1. Clarity and specificity
2. Coverage of requirements
3. Potential for accurate extraction
4. Handling of edge cases
Return evaluation metrics and suggestions in JSON format.
"""
class WorkflowAgent:
"""Agent responsible for managing workflow-related LLM interactions"""
code
def __init__(self, llm_config: WorkflowLLMConfig):
self.llm_config = llm_config
self.prompts = WorkflowPrompts()
def enhance_content(self, workflow_state: WorkflowState) -> Dict[str, Any]:
"""Enhance workflow content using LLM"""
llm = self.llm_config.content_enhancement.create_llm()
fields_str = "\n".join(
f"- {field.name}: {field.description} ({field.get_type_str()})"
for field in workflow_state.output_fields
)
prompt = self.prompts.CONTENT_ENHANCEMENT_PROMPT.format(
goal=workflow_state.goal,
fields=fields_str
)
response = llm.predict(prompt)
enhanced_content = json.loads(response)
# Update workflow state with enhanced content
workflow_state.goal = enhanced_content["enhanced_goal"]
for i, field in enumerate(workflow_state.output_fields):
field.description = enhanced_content["enhanced_fields"][i]["description"]
return workflow_state.dict()
def generate_queries(self, workflow_state: WorkflowState, num_queries: int = 3) -> List[ExampleQuery]:
"""Generate example queries using LLM"""
llm = self.llm_config.content_enhancement.create_llm()
fields_str = "\n".join(
f"- {field.name}: {field.description} ({field.get_type_str()})"
for field in workflow_state.output_fields
)
prompt = self.prompts.QUERY_GENERATION_PROMPT.format(
num_queries=num_queries,
goal=workflow_state.goal,
fields=fields_str
)
response = llm.predict(prompt)
queries_data = json.loads(response)
return [
ExampleQuery(query=q["query"])
for q in queries_data["queries"]
]
def generate_response(self, workflow_state: WorkflowState, query: str) -> Tuple[str, Dict[str, Any]]:
# rest of your code
"""Generate response to a query using LLM"""
llm = self.llm_config.content_enhancement.create_llm()
fields_str = "\n".join(
f"- {field.name}: {field.description} ({field.get_type_str()})"
for field in workflow_state.output_fields
)
prompt = self.prompts.RESPONSE_GENERATION_PROMPT.format(
goal=workflow_state.goal,
fields=fields_str,
query=query
)
response = llm.predict(prompt)
response_data = json.loads(response)
return response_data["conversational_response"], response_data["extracted_data"]
def evaluate_prompt(self, workflow_state: WorkflowState, prompt: str) -> Dict[str, Any]:
"""Evaluate a prompt's effectiveness using LLM"""
llm = self.llm_config.content_enhancement.create_llm()
fields_str = "\n".join(
f"- {field.name}: {field.description} ({field.get_type_str()})"
for field in workflow_state.output_fields
)
evaluation_prompt = self.prompts.PROMPT_EVALUATION_PROMPT.format(
prompt=prompt,
goal=workflow_state.goal,
fields=fields_str
)
response = llm.predict(evaluation_prompt)
return json.loads(response)
class GradioWorkflowManager:
def init(self):
self.session_manager = GradioSessionManager()
self.logger = logging.getLogger(name)
code
def initialize_agent(self, session_id: str) -> Optional[WorkflowAgent]:
"""Initialize workflow agent for a session"""
session = self.session_manager.get_session(session_id)
if not session:
return None
return WorkflowAgent(session.llm_config)
def enhance_content(self, session_id: str, content: Dict[str, Any]) -> Dict[str, Any]:
"""Enhance content using workflow agent"""
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Invalid session"}
try:
workflow_state = WorkflowState(**content)
return agent.enhance_content(workflow_state)
except Exception as e:
self.logger.error(f"Error enhancing content: {str(e)}")
return {"error": str(e)}
def generate_queries(self, workflow_state: WorkflowState) -> List[ExampleQuery]:
"""Generate example queries using workflow agent"""
agent = WorkflowAgent(WorkflowLLMConfig())
return agent.generate_queries(workflow_state)
def evaluate_prompts(self, workflow_state: WorkflowState) -> Dict[str, Any]:
"""Evaluate prompts using workflow agent"""
agent = WorkflowAgent(WorkflowLLMConfig())
evaluations = {}
for prompt_name, prompt in workflow_state.prompts.items():
evaluations[prompt_name] = agent.evaluate_prompt(workflow_state, prompt)
return evaluations
def generate_responses(self, session_id: str) -> Tuple[List[Dict[str, Any]], str]:
"""Generate responses for queries using workflow agent"""
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Invalid session"}, "Error: Invalid session"
session = self.session_manager.get_session(session_id)
if not session or not session.workflow_state:
return {"error": "Invalid workflow state"}, "Error: Invalid workflow state"
try:
for query in session.workflow_state.example_queries:
if not query.response:
response, extracted_data = agent.generate_response(
session.workflow_state,
query.query
)
query.response = response
query.metadata["extracted_data"] = extracted_data
self.session_manager.update_session(
session_id,
workflow_state=session.workflow_state
)
return (
[query.dict() for query in session.workflow_state.example_queries],
"Responses generated successfully"
)
except Exception as e:
self.logger.error(f"Error generating responses: {str(e)}")
return {"error": str(e)}, f"Error: {str(e)}"
def create_interface(self):
with gr.Blocks() as demo:
session_id = gr.State(lambda: self.session_manager.create_session())
gr.Markdown("# Workflow Manager")
with gr.Tabs() as tabs:
with gr.Tab("1. Input Collection", id="input_collection"):
with gr.Column():
goal_input = gr.Textbox(
label="Enter your goal",
placeholder="Describe the goal of your workflow..."
)
with gr.Column() as fields_col:
gr.Markdown("### Output Fields")
field_name = gr.Textbox(label="Field Name")
field_desc = gr.Textbox(label="Description")
field_type = gr.Dropdown(
choices=[t.value for t in FieldType],
label="Field Type"
)
field_source = gr.Dropdown(
choices=[s.value for s in DataSource],
label="Data Source"
)
field_required = gr.Checkbox(label="Required")
add_field_btn = gr.Button("Add Field")
fields_json = gr.JSON(label="Current Fields")
error_message = gr.Markdown(visible=False)
submit_inputs_btn = gr.Button("Submit & Continue")
with gr.Tab("2. Content Enhancement", id="enhancement"):
with gr.Column():
gr.Markdown("### Enhancement Options")
enhance_goal = gr.Checkbox(label="Enhance Goal")
enhance_fields = gr.Checkbox(label="Enhance Field Descriptions")
current_content = gr.JSON(label="Current Content")
enhanced_preview = gr.JSON(label="Enhanced Preview")
apply_enhancements_btn = gr.Button("Apply Enhancements")
with gr.Tab("3. Example Queries", id="queries"):
with gr.Column():
queries_display = gr.JSON(label="Generated Queries")
edit_query_index = gr.Number(
label="Query Index to Edit (0-2)",
minimum=0,
maximum=2,
step=1
)
new_query_text = gr.Textbox(label="New Query Text")
edit_query_btn = gr.Button("Update Query")
continue_queries_btn = gr.Button("Continue to Responses")
with gr.Tab("4. Response Generation", id="responses"):
with gr.Column():
responses_display = gr.JSON(label="Generated Responses")
response_status = gr.Markdown("Awaiting response generation...")
generate_responses_btn = gr.Button("Generate Responses")
edit_responses_btn = gr.Button("Edit Responses")
with gr.Tab("5. Prompts", id="prompts"):
with gr.Column():
prompts_display = gr.JSON(label="Generated Prompts")
evaluation_display = gr.JSON(label="Prompt Evaluation")
generate_prompts_btn = gr.Button("Generate Prompts")
evaluate_prompts_btn = gr.Button("Evaluate Prompts")
with gr.Tab("6. Agent Testing", id="testing"):
with gr.Column():
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Enter your message")
clear = gr.Button("Clear")
# Event handlers
# Enhanced event handlers
def add_field(session_id, name, desc, type_, source, required):
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Session expired"}
try:
new_field = OutputField(
name=name,
description=desc,
type=type_,
source=source,
required=required
)
session = self.session_manager.get_session(session_id)
# If workflow state doesn't exist, initialize it with the current goal
if session.workflow_state is None:
current_goal = goal_input.value # Get the current goal from UI
if not current_goal:
return {"error": "Please enter a goal before adding fields"}
session.workflow_state = WorkflowState(
goal=current_goal,
output_fields=[new_field] # Initialize with the new field
)
else:
# If workflow state exists, append the new field
session.workflow_state.output_fields.append(new_field)
self.session_manager.update_session(
session_id,
workflow_state=session.workflow_state
)
return [field.dict() for field in session.workflow_state.output_fields]
except Exception as e:
self.logger.error(f"Error adding field: {str(e)}")
return {"error": str(e)}
def submit_inputs(session_id, goal, fields_json):
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Session expired"}, gr.update()
try:
workflow_state = WorkflowState(
goal=goal,
output_fields=[OutputField(**field) for field in fields_json]
)
self.session_manager.update_session(
session_id,
workflow_state=workflow_state,
current_stage="enhancement"
)
# Auto-switch to enhancement tab
return workflow_state.dict(), gr.update(selected="enhancement")
except Exception as e:
self.logger.error(f"Error submitting inputs: {str(e)}")
return {"error": str(e)}, gr.update()
def apply_enhancements(session_id, enhance_goal, enhance_fields):
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Session expired"}, {"error": "Session expired"}
try:
session = self.session_manager.get_session(session_id)
if enhance_goal or enhance_fields:
enhanced_state = agent.enhance_content(session.workflow_state)
session.workflow_state = WorkflowState(**enhanced_state)
# Generate example queries automatically after enhancement
queries = agent.generate_queries(session.workflow_state)
session.workflow_state.example_queries = queries
self.session_manager.update_session(
session_id,
workflow_state=session.workflow_state,
current_stage="queries"
)
return enhanced_state, [query.dict() for query in queries]
return session.workflow_state.dict(), []
except Exception as e:
self.logger.error(f"Error applying enhancements: {str(e)}")
return {"error": str(e)}, {"error": str(e)}
def update_query(session_id, index, new_text):
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Session expired"}
try:
session = self.session_manager.get_session(session_id)
if 0 <= index < len(session.workflow_state.example_queries):
session.workflow_state.example_queries[index].query = new_text
session.workflow_state.example_queries[index].response = "" # Clear previous response
self.session_manager.update_session(
session_id,
workflow_state=session.workflow_state
)
return [query.dict() for query in session.workflow_state.example_queries]
return {"error": "Invalid query index"}
except Exception as e:
self.logger.error(f"Error updating query: {str(e)}")
return {"error": str(e)}
def generate_responses_handler(session_id):
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Session expired"}, "Session expired"
try:
session = self.session_manager.get_session(session_id)
responses, status = self.generate_responses(session_id)
if "error" not in responses:
# Generate prompts automatically after responses
prompts = self.generate_prompts(session_id)
session.workflow_state.prompts = prompts
self.session_manager.update_session(
session_id,
workflow_state=session.workflow_state,
current_stage="prompts"
)
return responses, "Responses generated successfully. Proceed to Prompts tab."
return responses, status
except Exception as e:
self.logger.error(f"Error generating responses: {str(e)}")
return {"error": str(e)}, str(e)
def chat_response(session_id, message, history):
agent = self.initialize_agent(session_id)
if not agent:
return history + [("Error: Session expired", "")], ""
try:
session = self.session_manager.get_session(session_id)
# Use the workflow state context for chat responses
prompt = f"""
Workflow Context:
Goal: {session.workflow_state.goal}
Chat History:
{history}
User: {message}
Respond as an AI assistant helping with this workflow:
"""
response = agent.llm_config.content_enhancement.create_llm().predict(prompt)
return history + [(message, response)], ""
except Exception as e:
self.logger.error(f"Error in chat: {str(e)}")
return history + [(message, f"Error: {str(e)}")], ""
# Wire up all the event handlers
add_field_btn.click(
add_field,
inputs=[session_id, field_name, field_desc, field_type,
field_source, field_required],
outputs=[fields_json, error_message]
)
# Add goal validation
def validate_goal(goal):
if not goal.strip():
return {"error": "Please enter a goal before adding fields"}
return {"success": True}
goal_input.change(
validate_goal,
inputs=[goal_input],
outputs=[error_message]
)
submit_inputs_btn.click(
submit_inputs,
inputs=[session_id, goal_input, fields_json],
outputs=[current_content, tabs]
)
apply_enhancements_btn.click(
apply_enhancements,
inputs=[session_id, enhance_goal, enhance_fields],
outputs=[enhanced_preview, queries_display]
)
edit_query_btn.click(
update_query,
inputs=[session_id, edit_query_index, new_query_text],
outputs=[queries_display]
)
generate_responses_btn.click(
generate_responses_handler,
inputs=[session_id],
outputs=[responses_display, response_status]
)
msg.submit(
chat_response,
inputs=[session_id, msg, chatbot],
outputs=[chatbot, msg]
)
# Auto-update handlers for tab transitions
def update_content_on_tab_change(session_id, current_tab):
session = self.session_manager.get_session(session_id)
if not session or not session.workflow_state:
return None
if current_tab == "enhancement":
return session.workflow_state.dict()
elif current_tab == "queries":
return [q.dict() for q in session.workflow_state.example_queries]
elif current_tab == "responses":
return [q.dict() for q in session.workflow_state.example_queries]
elif current_tab == "prompts":
return session.workflow_state.prompts
return None
tabs.change(
update_content_on_tab_change,
inputs=[session_id, tabs],
outputs=[current_content]
)
return demo
def generate_prompts(self, session_id: str) -> Dict[str, Any]:
"""Generate prompts based on the workflow state"""
session = self.session_manager.get_session(session_id)
if not session or not session.workflow_state:
return {"error": "Invalid session or workflow state"}
try:
llm = session.llm_config.content_enhancement.create_llm()
# Generate different types of prompts
prompts = {
"base_prompt": self._generate_base_prompt(session.workflow_state),
"enhanced_prompt": self._generate_enhanced_prompt(session.workflow_state),
"structured_prompt": self._generate_structured_prompt(session.workflow_state)
}
session.workflow_state.prompts = prompts
self.session_manager.update_session(session_id, workflow_state=session.workflow_state)
return prompts
except Exception as e:
self.logger.error(f"Error generating prompts: {str(e)}")
return {"error": str(e)}
def _generate_base_prompt(self, workflow_state: WorkflowState) -> str:
"""Generate a basic prompt from the workflow state"""
prompt = f"Goal: {workflow_state.goal}\n\nRequired Fields:\n"
for field in workflow_state.output_fields:
prompt += f"- {field.name}: {field.description} ({field.get_type_str()})\n"
return prompt
def _generate_enhanced_prompt(self, workflow_state: WorkflowState) -> str:
"""Generate an enhanced prompt with additional context and examples"""
base_prompt = self._generate_base_prompt(workflow_state)
example_section = "\nExample Queries:\n"
for query in workflow_state.example_queries:
example_section += f"Q: {query.query}\nA: {query.response}\n"
return base_prompt + example_section
def _generate_structured_prompt(self, workflow_state: WorkflowState) -> str:
"""Generate a structured prompt with specific formatting and constraints"""
prompt = {
"goal": workflow_state.goal,
"fields": [field.dict() for field in workflow_state.output_fields],
"constraints": self._generate_constraints(workflow_state),
"format": self._generate_format_instructions(workflow_state)
}
return json.dumps(prompt, indent=2)
def _generate_constraints(self, workflow_state: WorkflowState) -> List[str]:
"""Generate constraints based on field types and requirements"""
constraints = []
for field in workflow_state.output_fields:
if field.required:
constraints.append(f"{field.name} is required")
constraints.append(f"{field.name} must be of type {field.get_type_str()}")
return constraints
def _generate_format_instructions(self, workflow_state: WorkflowState) -> Dict[str, Any]:
"""Generate format instructions for the output"""
return {
"output_format": "json",
"fields": {
field.name: {
"type": field.get_type_str(),
"description": field.description
}
for field in workflow_state.output_fields
}
}
def edit_query(self, session_id: str, query_index: int, new_query_text: str) -> List[Dict[str, Any]]:
"""Edit an existing example query"""
session = self.session_manager.get_session(session_id)
if not session or not session.workflow_state:
return {"error": "Invalid session or workflow state"}
try:
if 0 <= query_index < len(session.workflow_state.example_queries):
session.workflow_state.example_queries[query_index].query = new_query_text
self.session_manager.update_session(session_id, workflow_state=session.workflow_state)
return [query.dict() for query in session.workflow_state.example_queries]
return {"error": "Invalid query index"}
except Exception as e:
self.logger.error(f"Error editing query: {str(e)}")
return {"error": str(e)}
def generate_responses(self, session_id: str) -> Tuple[List[Dict[str, Any]], str]:
"""Generate responses for the example queries"""
session = self.session_manager.get_session(session_id)
if not session or not session.workflow_state:
return {"error": "Invalid session or workflow state"}, "Error: Invalid session"
try:
llm = session.llm_config.content_enhancement.create_llm()
for query in session.workflow_state.example_queries:
if not query.response:
prompt = self._generate_enhanced_prompt(session.workflow_state)
prompt += f"\nQ: {query.query}\nA:"
query.response = llm.predict(prompt)
self.session_manager.update_session(session_id, workflow_state=session.workflow_state)
return (
[query.dict() for query in session.workflow_state.example_queries],
"Responses generated successfully"
)
except Exception as e:
self.logger.error(f"Error generating responses: {str(e)}")
return {"error": str(e)}, f"Error: {str(e)}"
def launch(self, **kwargs):
"""Launch the Gradio interface"""
demo = self.create_interface()
demo.launch(**kwargs)
if name == "main":
logging.basicConfig(level=logging.INFO)
manager = GradioWorkflowManager()
manager.launch()
Certainly! Let's carefully review your extensive Python code to identify and address the bugs and potential issues. The code integrates Gradio for the UI, Pydantic for data modeling, LangChain for LLM interactions, and manages user sessions. Below are the identified problems along with detailed explanations and suggestions for fixes:
1. Duplicate Imports
Issue:
Multiple imports of the same modules (e.g., gradio, pydantic, datetime, typing) can lead to redundancy and potential conflicts.
Example:
python
import gradio as gr
...
import gradio as gr
...
from pydantic import BaseModel, Field, validator
...
from pydantic import BaseModel, Field, validator
Impact:
While Python handles duplicate imports gracefully, it clutters the code and can lead to confusion or maintenance challenges.
Solution:
Consolidate imports to ensure each module is imported only once.
Example Fix:
python
import gradio as gr
import uuid
import json
import threading
from datetime import datetime
from typing import Dict, Optional, Any, List, Union, Tuple
from dataclasses import dataclass, field # Use 'field' from dataclasses
from enum import Enum
import time
import logging
from threading import Lock
from pydantic import BaseModel, Field, validator
from langchain.chat_models import ChatOpenAI
from langchain_openai import ChatOpenAI # Verify if both are needed
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
import random
from typing import Sequence
from langchain_core.messages import BaseMessage
from langgraph.graph.message import add_messages
from typing_extensions import Annotated, TypedDict
from langchain_core.messages import SystemMessage, trim_messages
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
2. Duplicate Class Definitions
Issue:
The GradioWorkflowManager class is defined twice, which causes the first definition to be overwritten by the second. This leads to loss of methods and functionalities defined in the first class.
First Definition:
python
class GradioWorkflowManager:
def __init__(self, timeout_minutes: int = 30):
...
def enhance_content(self, session_id: str, content: Dict[str, Any]) -> Dict[str, Any]:
...
Only the second GradioWorkflowManager definition is retained, causing all methods from the first definition (like session management) to be lost. This results in missing functionalities and potential runtime errors when those methods are called.
Solution:
Merge the two class definitions into a single GradioWorkflowManager class that includes all necessary methods.
Example Fix:
python
class GradioWorkflowManager:
def __init__(self, timeout_minutes: int = 30):
self.session_manager = GradioSessionManager(timeout_minutes)
self.logger = logging.getLogger(__name__)
def initialize_agent(self, session_id: str) -> Optional[WorkflowAgent]:
...
def enhance_content(self, session_id: str, content: Dict[str, Any]) -> Dict[str, Any]:
...
# Include all other methods from both definitions here
def create_interface(self):
...
def generate_prompts(self, session_id: str) -> Dict[str, Any]:
...
def launch(self, **kwargs):
...
3. Incorrect Usage of predict() Method on LLM
Issue:
The code uses llm.predict(prompt), which is not a standard method in LangChain's ChatOpenAI class.
Example:
python
response = llm.predict(prompt)
Impact:
This will raise an AttributeError at runtime since predict does not exist for ChatOpenAI instances.
Solution:
Use the correct methods provided by LangChain's ChatOpenAI. Typically, you should use the generate or __call__ (llm()) methods.
Example Fix:
python
response = llm(prompt) # Using the __call__ method
# Or for more advanced usage:
response = llm.generate([prompt])
The model name "gpt-4o-mini" appears to be a typo. OpenAI models typically include names like "gpt-4", "gpt-3.5-turbo", etc.
Example:
python
class LLMConfig(BaseModel):
model: str = "gpt-4o-mini"
...
Impact:
Using an invalid model name will cause the LLM initialization to fail, raising errors when attempting to create the LLM instance.
Solution:
Correct the model name to a valid OpenAI model. For example, use "gpt-4" or another appropriate model identifier.
Example Fix:
python
class LLMConfig(BaseModel):
model: str = "gpt-4" # Corrected model name
...
5. Incorrect Return Formats in Gradio Event Handlers
Issue:
Event handler functions return data that does not match the expected output components in Gradio. For instance, returning a single dictionary when multiple outputs are expected.
Example:
python
def add_field(...):
...
return [field.dict() for field in session.workflow_state.output_fields] # Expected two outputs
...
return {"error": str(e)}
Impact:
Gradio expects each handler to return outputs corresponding to the defined outputs parameter. Mismatched return types can cause runtime errors or unexpected UI behavior.
Solution:
Ensure that each event handler returns a value for each output component defined.
Example Fix for add_field:
python
def add_field(session_id, name, desc, type_, source, required):
...
try:
...
return [updated_fields, ""] # Updated fields and no error
except Exception as e:
self.logger.error(f"Error adding field: {str(e)}")
return [current_fields, f"Error: {str(e)}"] # Current fields and error message
Consistency in Other Handlers:
Similarly, ensure all other event handlers return tuples or lists matching the number of output components.
6. Incorrect Access to Gradio Component Values Within Functions
Issue:
Inside event handler functions, there's an attempt to access Gradio component values directly (e.g., goal_input.value), which is not the correct approach in Gradio.
Example:
python
if session.workflow_state is None:
current_goal = goal_input.value # Incorrect access
...
Impact:
Gradio manages component states internally and passes them as inputs to handler functions. Direct access like goal_input.value is invalid and will raise AttributeError.
Solution:
Pass all necessary values as inputs to the handler functions.
Example Fix:
Modify the add_field function to accept goal as an input if needed.
python
def add_field(session_id, name, desc, type_, source, required, goal):
...
if session.workflow_state is None:
if not goal.strip():
return [current_fields, "Please enter a goal before adding fields"]
...
...
Then, update the event binding to include goal_input as an input.
7. Incorrect Usage of dataclass with Pydantic's Field
Issue:
The SessionState class is defined as a dataclass but uses Pydantic's Field for llm_config.
Example:
python
@dataclass
class SessionState:
...
llm_config: WorkflowLLMConfig = Field(default_factory=WorkflowLLMConfig)
Impact:
dataclasses.field() should be used instead of Pydantic's Field within a dataclass. Using Field from Pydantic in a standard dataclass can cause unexpected behavior.
Solution:
Usedataclasses.field for default factories in dataclass.
Example Fix:
python
from dataclasses import dataclass, field # Ensure 'field' is imported
@dataclass
class SessionState:
user_id: str
workflow_state: Optional[WorkflowState] = None
current_stage: str = "input_collection"
last_active: datetime = field(default_factory=datetime.now)
is_complete: bool = False
llm_config: WorkflowLLMConfig = field(default_factory=WorkflowLLMConfig)
Alternative Approach:
If you prefer using Pydantic models for consistency:
Gradio expects a direct value or an initial value for gr.State, not a callable. This will cause the state to hold a lambda function instead of the intended session ID.
Solution:
Initialize the gr.State with the session ID before launching the interface or use a startup event to create the session.
Example Fix:
python
with gr.Blocks() as demo:
initial_session_id = self.session_manager.create_session()
session_id = gr.State(initial_session_id)
...
Alternatively, use a separate function to initialize the state upon launching.
9. Misalignment Between Event Handlers and UI Components
Issue:
Some event handlers attempt to update UI components (like tab selection) in ways that may not align with Gradio's API.
If tab switching isn't directly supported, consider guiding the user or restructuring the UI flow.
10. Handling Chat History Incorrectly
Issue:
In the chat_response function, history is likely a list of tuples (user and assistant messages). Concatenating it directly into a string may not produce the desired prompt format.
Example:
python
prompt = f"""
Workflow Context:
Goal: {session.workflow_state.goal}
Chat History:
{history}
User: {message}
Respond as an AI assistant helping with this workflow:
"""
Impact:
The history may not be formatted correctly, leading to ambiguous prompts and suboptimal LLM responses.
Solution:
Properly format the chat history before including it in the prompt.
Example Fix:
python
def chat_response(session_id, message, history):
...
formatted_history = "\n".join([f"User: {msg[0]}\nAI: {msg[1]}" for msg in history])
prompt = f"""
Workflow Context:
Goal: {session.workflow_state.goal}
Chat History:
{formatted_history}
User: {message}
Respond as an AI assistant helping with this workflow:
"""
...
11. Potential Issues with Session Cleanup Thread
Issue:
The session cleanup thread runs indefinitely without a condition to properly shut down, which can prevent graceful termination of the program.
Example:
python
def _cleanup_expired_sessions(self):
while True:
...
time.sleep(60)
Impact:
Prevents the program from exiting cleanly and may lead to unintended resource usage.
Solution:
Implement a mechanism to gracefully stop the cleanup thread when the application is shutting down.
Example Fix:
python
import threading
class GradioSessionManager:
def __init__(self, timeout_minutes: int = 30):
...
self._stop_cleanup = threading.Event()
self._cleanup_thread = threading.Thread(target=self._cleanup_expired_sessions, daemon=True)
self._cleanup_thread.start()
def _cleanup_expired_sessions(self):
while not self._stop_cleanup.is_set():
...
time.sleep(60)
def stop(self):
self._stop_cleanup.set()
self._cleanup_thread.join()
# Ensure to call 'stop' method when shutting down the application
12. Inconsistent Method Definitions in WorkflowAgent
Issue:
The WorkflowAgent class has a method generate_response that returns a tuple, but in the second GradioWorkflowManager definition, a method with the same name is also defined differently.
Impact:
Confusion in method behavior and potential runtime errors due to inconsistent method signatures.
Solution:
Ensure that methods within classes are uniquely defined and follow consistent signatures.
Example Fix:
Consolidate method definitions to maintain consistency.
13. Usage of Undefined Methods or Variables
Issue:
In enhance_content, the method tries to access session.workflow_state, but it's unclear if workflow_state is being properly set before.
Impact:
May lead to AttributeError if workflow_state is None.
Solution:
Add checks to ensure workflow_state exists before accessing its attributes.
Example Fix:
python
def enhance_content(self, session_id: str, content: Dict[str, Any]) -> Dict[str, Any]:
session = self.session_manager.get_session(session_id)
if not session or not session.workflow_state:
return {"error": "Invalid session or workflow state"}
...
14. General Code Quality and Maintainability
Suggestions:
Modularize the code by separating models, session management, agent logic, and UI into different modules or files for better readability and maintenance.
Add Type Hints consistently across all functions and methods to enhance code clarity and help with debugging.
Implement Error Handling comprehensively to manage unexpected scenarios gracefully.
Write Unit Tests for individual components to ensure each part functions as intended.
Revised Code Snippet
Below is a revised version of some critical parts of your code incorporating the fixes discussed above. Due to space constraints, not all parts are included, but this should guide you in correcting the entire codebase.
python
Conclusion
By addressing the issues outlined above, your code should function more reliably and maintainably. Here's a summary of critical fixes:
Eliminate Duplicate Imports: Streamline import statements to avoid redundancy.
Consolidate Class Definitions: Ensure each class is defined only once with all necessary methods.
Correct LLM Method Usage: Use appropriate methods (__call__ or generate) instead of undefined predict().
Fix Model Naming: Use valid OpenAI model identifiers.
Properly Access Gradio States: Pass all required data as inputs to handlers instead of accessing UI components directly.
Use Appropriate Field Definitions: Align dataclass fields with dataclasses.field instead of Pydantic's Field.
Initialize Gradio States Correctly: Provide initial values without using callables.
Format Chat History Properly: Structure chat histories in prompts correctly.
Manage Cleanup Threads Gracefully: Implement mechanisms to stop threads when the application exits.
Recommendation: After implementing these fixes, thoroughly test each component individually (unit testing) and perform end-to-end testing of the entire application to ensure all parts work harmoniously.
If you encounter specific errors during testing, feel free to reach out with the error messages for more targeted assistance!
Dataset releases
Not yet included in a published release.
import gradio as gr
import uuid
import json
import threading
from datetime import datetime
from typing import Dict, Optional, Any, List, Union, Tuple
from dataclasses import dataclass, field
from enum import Enum
import time
import logging
from threading import Lock
from pydantic import BaseModel, Field, validator
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
import random
from typing import Sequence
from langchain_core.messages import BaseMessage
from langgraph.graph.message import add_messages
from typing_extensions import Annotated, TypedDict
from langchain_core.messages import SystemMessage, trim_messages
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
# Enums and Models (unchanged as per previous sections)
# ...
@dataclass
class SessionState:
"""Represents the current state of a user session"""
user_id: str
workflow_state: Optional['WorkflowState'] = None
current_stage: str = "input_collection"
last_active: datetime = field(default_factory=datetime.now)
is_complete: bool = False
llm_config: 'WorkflowLLMConfig' = field(default_factory='WorkflowLLMConfig')
class GradioSessionManager:
def __init__(self, timeout_minutes: int = 30):
self.sessions: Dict[str, SessionState] = {}
self.locks: Dict[str, Lock] = {}
self.timeout_minutes = timeout_minutes
self._stop_cleanup = threading.Event()
self._cleanup_thread = threading.Thread(target=self._cleanup_expired_sessions, daemon=True)
self._cleanup_thread.start()
def create_session(self) -> str:
session_id = str(uuid.uuid4())
self.sessions[session_id] = SessionState(
user_id=session_id,
llm_config=WorkflowLLMConfig()
)
self.locks[session_id] = Lock()
return session_id
def get_session(self, session_id: str) -> Optional[SessionState]:
if session_id in self.sessions:
session = self.sessions[session_id]
session.last_active = datetime.now()
return session
return None
def update_session(self, session_id: str, **updates) -> bool:
if session_id in self.sessions:
with self.locks[session_id]:
for key, value in updates.items():
setattr(self.sessions[session_id], key, value)
self.sessions[session_id].last_active = datetime.now()
return True
return False
def _cleanup_expired_sessions(self):
while not self._stop_cleanup.is_set():
current_time = datetime.now()
expired_sessions = [
sid for sid, session in self.sessions.items()
if (current_time - session.last_active).total_seconds() > self.timeout_minutes * 60
]
for sid in expired_sessions:
del self.sessions[sid]
del self.locks[sid]
time.sleep(60)
def stop(self):
self._stop_cleanup.set()
self._cleanup_thread.join()
class GradioWorkflowManager:
def __init__(self, timeout_minutes: int = 30):
self.session_manager = GradioSessionManager(timeout_minutes)
self.logger = logging.getLogger(__name__)
def initialize_agent(self, session_id: str) -> Optional['WorkflowAgent']:
"""Initialize workflow agent for a session"""
session = self.session_manager.get_session(session_id)
if not session:
return None
return WorkflowAgent(session.llm_config)
def enhance_content(self, session_id: str, content: Dict[str, Any]) -> Dict[str, Any]:
"""Enhance content using workflow agent"""
agent = self.initialize_agent(session_id)
if not agent:
return {"error": "Invalid session"}
try:
workflow_state = WorkflowState(**content)
return agent.enhance_content(workflow_state)
except Exception as e:
self.logger.error(f"Error enhancing content: {str(e)}")
return {"error": str(e)}
# Include all other methods with appropriate fixes
# ...
def create_interface(self):
with gr.Blocks() as demo:
initial_session_id = self.session_manager.create_session()
session_id = gr.State(initial_session_id)
gr.Markdown("# Workflow Manager")
with gr.Tabs() as tabs:
with gr.Tab("1. Input Collection"):
with gr.Column():
goal_input = gr.Textbox(
label="Enter your goal",
placeholder="Describe the goal of your workflow..."
)
with gr.Column() as fields_col:
gr.Markdown("### Output Fields")
field_name = gr.Textbox(label="Field Name")
field_desc = gr.Textbox(label="Description")
field_type = gr.Dropdown(
choices=[t.value for t in FieldType],
label="Field Type"
)
field_source = gr.Dropdown(
choices=[s.value for s in DataSource],
label="Data Source"
)
field_required = gr.Checkbox(label="Required")
add_field_btn = gr.Button("Add Field")
fields_json = gr.JSON(label="Current Fields")
error_message = gr.Markdown(visible=False)
submit_inputs_btn = gr.Button("Submit & Continue")
# Define other tabs similarly
# ...
# Event handlers with corrected signatures and return values
def add_field(session_id, name, desc, type_, source, required, goal):
agent = self.initialize_agent(session_id)
if not agent:
return [fields_json.value, "Session expired"]
try:
new_field = OutputField(
name=name,
description=desc,
type=type_,
source=source,
required=required
)
session = self.session_manager.get_session(session_id)
if session.workflow_state is None:
if not goal.strip():
return [fields_json.value, "Please enter a goal before adding fields"]
session.workflow_state = WorkflowState(
goal=goal,
output_fields=[new_field]
)
else:
session.workflow_state.output_fields.append(new_field)
self.session_manager.update_session(
session_id,
workflow_state=session.workflow_state
)
return [ [field.dict() for field in session.workflow_state.output_fields], "" ]
except Exception as e:
self.logger.error(f"Error adding field: {str(e)}")
return [fields_json.value, f"Error: {str(e)}"]
add_field_btn.click(
add_field,
inputs=[session_id, field_name, field_desc, field_type,
field_source, field_required, goal_input],
outputs=[fields_json, error_message]
)
# Similarly, update other event handlers
# ...
return demo
def launch(self, **kwargs):
"""Launch the Gradio interface"""
demo = self.create_interface()
demo.launch(**kwargs)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
manager = GradioWorkflowManager()
try:
manager.launch()
finally:
manager.session_manager.stop() # Ensure cleanup thread is stopped