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


# Retain original enums and base models
class FieldType(str, Enum):
    STRING = "string"
    INTEGER = "integer"
    FLOAT = "float"
    BOOLEAN = "boolean"
    LIST = "list"
    DATETIME = "datetime"
    ENUM = "enum"
    OBJECT = "object"

class DataSource(str, Enum):
    DATABASE = "database"
    API = "api"
    USER_INPUT = "user_input"
    COMPUTED = "computed"
    EXTERNAL = "external"

class LLMConfig(BaseModel):
    """Configuration class for OpenAI LLM settings"""
    model: str = "gpt-4o-mini"
    temperature: float = 0.0
    max_tokens: Optional[int] = None
    presence_penalty: float = 0.0
    frequency_penalty: float = 0.0
    top_p: float = 1.0
    
    def create_llm(self) -> ChatOpenAI:
        return ChatOpenAI(
            model=self.model,
            temperature=self.temperature,
            max_tokens=self.max_tokens,
            presence_penalty=self.presence_penalty,
            frequency_penalty=self.frequency_penalty,
            top_p=self.top_p
        )

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
        )
    )

class OutputField(BaseModel):
    name: str
    description: str
    type: FieldType
    source: DataSource
    required: bool

    class Config:
        use_enum_values = True

    def get_type_str(self) -> str:
        return self.type.value if isinstance(self.type, FieldType) else str(self.type)

class ExampleQuery(BaseModel):
    query: str
    response: str = ""
    metadata: Dict[str, Any] = Field(default_factory=dict)
    timestamp: datetime = Field(default_factory=datetime.now)

    @validator('query')
    def query_not_empty(cls, v):
        if not v.strip():
            raise ValueError('Query cannot be empty')
        return v.strip()

class WorkflowState(BaseModel):
    version: str = "1.0"
    goal: str
    output_fields: List[OutputField]
    example_queries: List[ExampleQuery] = Field(default_factory=list)
    prompts: Dict[str, str] = Field(default_factory=dict)
    evaluations: Dict[str, Any] = Field(default_factory=dict)
    best_prompt: Dict[str, Any] = Field(default_factory=dict)
    metadata: Dict[str, Any] = Field(default_factory=dict)

    @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)

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._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,
            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__)

    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"""
    
    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"""
    
    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__)
        
    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()