from rich.console import Console from dotenv import load_dotenv from openai import OpenAI import json import gradio as gr load_dotenv(override=True) openai = OpenAI() projects = [] issues = [] todos = [] completed = [] output_text = "" def show(text): global output_text def audit_project(project_data: str) -> str: prompt = f""" You are a workflow audit assistant for creative agencies. Analyze the project workflow below and identify issues. Focus on: - missed deadlines - unclear ownership - fragmented communication - bottlenecks - delays Return a JSON list of issues. Each issue should have: - title - description - severity (low, medium, high) Format all responses using clean markdown. Do NOT use: - [red], [bold], [green] - Rich console formatting Use: - headings (##) - short paragraphs - bullet points - numbered lists Project data: {project_data} """ response = openai.chat.completions.create( model="gpt-5.2", messages=[{"role": "user", "content": prompt}], response_format={"type": "json_object"}, reasoning_effort="low" ) result = json.loads(response.choices[0].message.content) new_issues = result.get("issues", []) for issue in new_issues: issues.append(issue) output = "[bold]Audit Results:[/bold]\n" for i, issue in enumerate(new_issues, 1): output += f"{i}. [red]{issue['title']}[/red] ({issue['severity']})\n" output += f" {issue['description']}\n" show(output) return json.dumps(new_issues) def create_todos(descriptions: list[str]) -> str: todos.extend(descriptions) completed.extend([False] * len(descriptions)) return get_todo_report() def mark_complete(index: int, completion_notes: str) -> str: if 1 <= index <= len(todos): completed[index - 1] = True else: return "No todo at this index." show(completion_notes) return get_todo_report() def get_todo_report() -> str: result = "" for index, todo in enumerate(todos): if completed[index]: result += f"Todo #{index + 1}: [green][strike]{todo}[/strike][/green]\n" else: result += f"Todo #{index + 1}: {todo}\n" show(result) return result audit_project_json = { "name": "audit_project", "description": "Analyze a project workflow and identify bottlenecks and issues", "parameters": { "type": "object", "properties": { "project_data": {"type": "string"} }, "required": ["project_data"], "additionalProperties": False } } create_todos_json = { "name": "create_todos", "description": "Add new todos from a list of descriptions", "parameters": { "type": "object", "properties": {"descriptions": {"type": "array","items": {"type": "string"}}}, "required": ["descriptions"], "additionalProperties": False } } mark_complete_json = { "name": "mark_complete", "description": "Mark complete the todo at the given position", "parameters": { "type": "object", "properties": { "index": {"type": "integer"}, "completion_notes": {"type": "string"} }, "required": ["index","completion_notes"], "additionalProperties": False } } tools = [ {"type": "function", "function": audit_project_json}, {"type": "function", "function": create_todos_json}, {"type": "function", "function": mark_complete_json} ] def handle_tool_calls(tool_calls): results = [] for tool_call in tool_calls: tool_name = tool_call.function.name arguments = json.loads(tool_call.function.arguments) tool = globals().get(tool_name) result = tool(**arguments) if tool else {} results.append({ "role": "tool", "content": json.dumps(result), "tool_call_id": tool_call.id }) return results def loop(messages): """ Handles a single LLM call, including any tool calls. Returns the assistant's reply as a string. """ done = False while not done: response = openai.chat.completions.create( model="gpt-5.2", messages=messages, tools=tools, reasoning_effort="none" ) choice = response.choices[0] finish_reason = choice.finish_reason if finish_reason == "tool_calls": # The model wants to call a tool message = choice.message tool_calls = message.tool_calls results = handle_tool_calls(tool_calls) # Add tool call message and results to conversation messages.append(message) messages.extend(results) else: # Model finished generating content done = True # Return only the final assistant content return choice.message.content system_message = """ You are a Workflow Rescue agent. Your job is to: 1. Audit the project workflow using the audit tool 2. Identify key issues 3. Create a plan using todos to fix them 4. Mark steps complete as you simulate execution 5. Present a clear final summary You operate in two modes: 1. Conversation mode (default): - If the user sends a greeting or vague message, respond naturally and flow with their conversation. - Ask simple, direct questions to understand their workflow. - Do NOT call any tools yet. 2. Audit mode: - Only call the audit tool when the user provides enough workflow detail (tasks, tools, delays, communication, ownership, etc.). - If the user does not provide specific details you need for your report, ask them to provide it and tell them why. - After auditing, explain findings clearly and suggest fixes. Guidelines: - Be conversational and clear. - Do not force an audit if there is not enough information. - Ask 1-2 focused follow-up questions when needed, one at a time. - Format responses cleanly (no Rich markup). Use plain markdown. No Rich console markup. Do not create todos or run tools unless clearly needed. Start by understanding the user's situation first. """ def run_agent(message, history): """ Prepares messages in OpenAI-style format, appends user input, and calls the loop to get the assistant's response. """ # Start with system prompt messages = [{"role": "system", "content": system_message}] # Append conversation history (already in {'role':..., 'content':...} format) messages.extend(history) # Append current user message messages.append({"role": "user", "content": message}) # Call the loop to get assistant response return loop(messages) iface = gr.ChatInterface( fn=run_agent, type="messages", textbox=gr.Textbox( placeholder="Describe your project workflow or the issues you're facing...", lines=3 ), title="Workflow Rescue Agent" ) iface.launch(share=True)