Debug the below 
import os
from typing import TypedDict, List, Optional, Dict, Union, Any, Literal
from pydantic import BaseModel, Field
import json
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, END

# Define the state schema
class OutputField(TypedDict):
    name: str
    description: str
    type: str
    source: str
    required: bool

class WorkflowState(TypedDict):
    goal: str
    output_fields: List[OutputField]
    examples: List[str]
    improved_goal: Optional[str]
    grokked_output_fields: List[OutputField]
    generated_examples: List[str]
    chosen_prompt: Optional[str]
    enhance_goal_flag: bool
    enhance_output_fields_flag: bool
    enhance_examples_flag: bool
    candidates: Optional[List[str]]
    next_step: str

class PromptWorkflow:
    def __init__(self):
        self.llm = self._create_llm()
        self.workflow = self._create_workflow()

    def _create_llm(self):
        """Create and return LLM instance with proper error handling."""
        api_key = os.getenv("OPENAI_API_KEY")
        if not api_key:
            raise ValueError("OpenAI API key not found in environment variables")
        
        return ChatOpenAI(
            model_name="gpt-4",
            temperature=0,
            openai_api_key=api_key
        )

    def enhance_goal(self, state: WorkflowState) -> WorkflowState:
        """Improve or rephrase the goal using OpenAI API."""
        try:
            goal_prompt = ChatPromptTemplate.from_messages([
                SystemMessage(content="You are a goal improvement agent. Improve the following goal for clarity and effectiveness."),
                HumanMessage(content="Goal: {goal}")
            ])

            formatted_prompt = goal_prompt.format_messages(goal=state["goal"])
            response = self.llm(formatted_prompt)
            improved_goal = response.content.strip()
            
            state["improved_goal"] = improved_goal
            state["goal"] = improved_goal
            return state

        except Exception as e:
            print(f"Error during goal enhancement: {e}")
            return state

    def enhance_output_fields(self, state: WorkflowState) -> WorkflowState:
        """Enhance output fields with proper error handling and validation."""
        try:
            grok_prompt = ChatPromptTemplate.from_messages([
                SystemMessage(content=(
                    "You are a field augmentation agent. Suggest output fields based on the goal. "
                    "Respond with a JSON array of objects with structure: "
                    "{ name: string, description: string, type: string, source: string, required: boolean }"
                )),
                HumanMessage(content="Goal: {goal}")
            ])

            formatted_prompt = grok_prompt.format_messages(goal=state["goal"])
            response = self.llm(formatted_prompt)
            
            grokked_output_fields = json.loads(response.content)
            state["grokked_output_fields"] = grokked_output_fields
            state["output_fields"] = grokked_output_fields
            return state

        except Exception as e:
            print(f"Error during output fields enhancement: {e}")
            return state

    def enhance_examples(self, state: WorkflowState) -> WorkflowState:
        """Enhance examples with proper validation."""
        try:
            examples_str = json.dumps(state["examples"])
            examples_prompt = ChatPromptTemplate.from_messages([
                SystemMessage(content="You are an example generation agent. Refine the examples for clarity."),
                HumanMessage(content="Examples: {examples}")
            ])
            
            formatted_prompt = examples_prompt.format_messages(examples=examples_str)
            response = self.llm(formatted_prompt)
            
            refined_examples = json.loads(response.content.strip())
            state["generated_examples"] = refined_examples
            state["examples"] = refined_examples
            return state

        except Exception as e:
            print(f"Error during examples enhancement: {e}")
            return state

    def _route_next_step(self, state: WorkflowState) -> Literal["enhance_goal", "enhance_fields", "enhance_examples", "generate", "evaluate", "end"]:
        """Determine the next step in the workflow."""
        if not state.get("improved_goal"):
            return "enhance_goal"
        if not state.get("grokked_output_fields"):
            return "enhance_fields"
        if not state.get("generated_examples"):
            return "enhance_examples"
        if not state.get("candidates"):
            return "generate"
        if not state.get("chosen_prompt"):
            return "evaluate"
        return "end"

    def _generate_candidates(self, state: WorkflowState) -> WorkflowState:
        """Generate candidate prompts."""
        try:
            prompt_template = ChatPromptTemplate.from_messages([
                SystemMessage(content="Generate a complete prompt based on the inputs."),
                HumanMessage(content="Goal: {goal}\nOutput Fields: {fields}\nExamples: {examples}")
            ])

            candidates = []
            for _ in range(3):
                formatted_prompt = prompt_template.format_messages(
                    goal=state["goal"],
                    fields=json.dumps(state["output_fields"]),
                    examples=json.dumps(state["examples"])
                )
                response = self.llm(formatted_prompt)
                candidates.append(response.content.strip())

            state["candidates"] = candidates
            return state

        except Exception as e:
            print(f"Error generating candidates: {e}")
            state["candidates"] = []
            return state

    def _evaluate_prompts(self, state: WorkflowState) -> WorkflowState:
        """Evaluate and select the best prompt."""
        try:
            candidates = state.get("candidates", [])
            if candidates:
                # Simple scoring system
                state["chosen_prompt"] = candidates[0]  # For demonstration, choose first candidate
            return state

        except Exception as e:
            print(f"Error evaluating prompts: {e}")
            return state

    def _create_workflow(self) -> StateGraph:
        """Create and configure the workflow graph."""
        # Initialize StateGraph with the state schema
        workflow = StateGraph(WorkflowState)

        # Add nodes
        workflow.add_node("enhance_goal", self.enhance_goal)
        workflow.add_node("enhance_fields", self.enhance_output_fields)
        workflow.add_node("enhance_examples", self.enhance_examples)
        workflow.add_node("generate", self._generate_candidates)
        workflow.add_node("evaluate", self._evaluate_prompts)

        # Set conditional entry point
        workflow.set_entry_point(self._route_next_step)

        # Add conditional edges
        def should_continue_to_fields(state: WorkflowState) -> Union[Literal["enhance_fields"], Literal["enhance_examples"]]:
            return "enhance_fields" if not state.get("grokked_output_fields") else "enhance_examples"

        def should_continue_to_examples(state: WorkflowState) -> Union[Literal["enhance_examples"], Literal["generate"]]:
            return "enhance_examples" if not state.get("generated_examples") else "generate"

        def should_continue_to_evaluate(state: WorkflowState) -> Union[Literal["evaluate"], Literal["end"]]:
            return "evaluate" if not state.get("chosen_prompt") else "end"

        workflow.add_conditional_edges(
            "enhance_goal",
            should_continue_to_fields,
            {
                "enhance_fields": "enhance_fields",
                "enhance_examples": "enhance_examples"
            }
        )

        workflow.add_conditional_edges(
            "enhance_fields",
            should_continue_to_examples,
            {
                "enhance_examples": "enhance_examples",
                "generate": "generate"
            }
        )

        workflow.add_conditional_edges(
            "enhance_examples",
            lambda x: "generate",
            {"generate": "generate"}
        )

        workflow.add_conditional_edges(
            "generate",
            should_continue_to_evaluate,
            {
                "evaluate": "evaluate",
                "end": END
            }
        )

        workflow.add_edge("evaluate", END)

        return workflow

    def run(self, initial_state: Optional[Dict[str, Any]] = None) -> WorkflowState:
        """Run the workflow with proper error handling."""
        try:
            base_state = {
                "goal": "Create an AI agent that helps with task scheduling based on user availability.",
                "output_fields": [
                    {
                        "name": "task_name",
                        "description": "The name of the task to schedule.",
                        "type": "string",
                        "source": "user input",
                        "required": True
                    }
                ],
                "examples": [
                    "Input: Schedule a meeting for tomorrow at 10 AM."
                ],
                "enhance_goal_flag": True,
                "enhance_output_fields_flag": True,
                "enhance_examples_flag": True,
                "next_step": "enhance_goal"
            }
            
            if initial_state:
                base_state.update(initial_state)
                
            final_state = self.workflow.run(base_state)
            return final_state

        except Exception as e:
            print(f"Error running workflow: {e}")
            return base_state

# Usage
if __name__ == "__main__":
    try:
        workflow = PromptWorkflow()
        final_state = workflow.run()
        
        if final_state.get("chosen_prompt"):
            print("\nChosen Prompt for Inference:")
            print(final_state["chosen_prompt"])
        else:
            print("\nNo prompt was chosen. Check the logs for errors.")
            
    except Exception as e:
        print(f"Fatal error: {e}")