from dotenv import load_dotenv from langchain.agents import AgentExecutor from langchain.agents.openai_assistant import OpenAIAssistantRunnable from langchain.tools import BaseTool, StructuredTool import openai from liveplan_theme import LivePlanTheme from openai import OpenAI from supabase import create_client, Client from typing import List from utils import * import gradio as gr import json import logging import pdb import tools_langchain logging.disable(logging.CRITICAL) client = OpenAI() supabase: Client = create_client( os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_KEY")) load_dotenv() system_prompt = "You are the LivePlan Assistant, embedded in LivePlan by Palo Alto Software. You combine the speed, flexibility, and sophistication of various AI models with over 40+ years of extensive business planning expertise. You address many of the challenges LivePlan customers share around what makes business planning difficult, and ensures their business plans are the best that they can be. Use Markdown formatting to style your text. The forecast periods vary by company, so always call getCompanyForecastPeriods function to fetch the correct list of forecast periods to be used when calling createRevenueStream function." tools = [] for attr_name in dir(tools_langchain): attr = getattr(tools_langchain, attr_name) if isinstance(attr, (BaseTool, StructuredTool)): tools.append(attr) tool_names = "\n".join(sorted([tool.name for tool in tools])) print(f"Found {len(tools)} tools:") print(tool_names) agent = OpenAIAssistantRunnable.create_assistant( name="LivePlan Assistant", instructions=system_prompt, tools=tools, model="gpt-4-1106-preview", # model="gpt-3.5-turbo-1106", as_agent=True, ) agent_executor = AgentExecutor(agent=agent, tools=tools) with gr.Blocks(theme=LivePlanTheme(), css=GRADIO_CUSTOM_CSS) as demo: exponential_backoff = 2 thread = None user_info = gr.JSON({}, visible=False, label="User Info") chatbot = gr.Chatbot(layout="panel", elem_id="chatbot", show_label=False) msg = gr.Textbox( value="What are the details and risks for my industry, as well as the revenue streams for my company?", show_label=False) clear_button = gr.Button("Clear Chat") def get_messages(chat_history: List) -> List[str]: global thread if thread is None: raise ValueError( ".get_messages called before thread is initialized") messages = client.beta.threads.messages.list( limit=100, order="asc", thread_id=thread.id ) # Process messages and organize into user-assistant pairs user_messages, assistant_messages, message_response_pairs = [], [], [] for message in messages: for content in message.content: if message.role == "user": if assistant_messages: # If there are pending assistant messages, pair them with the last user message message_response_pairs.append( (user_messages[-1], " ".join(assistant_messages))) assistant_messages.clear() user_messages.append(content.text.value) elif message.role == "assistant": assistant_messages.append(content.text.value) # If there are assistant messages left without a user message, pair them with the last user message if assistant_messages and user_messages: message_response_pairs.append( (user_messages[-1], " ".join(assistant_messages))) # Extend, not append, to add pairs, not a list of pairs chat_history.extend(message_response_pairs) return message_response_pairs def respond(message: gr.Textbox, chat_history: gr.Chatbot, user_info) -> (str, gr.Chatbot): global exponential_backoff, thread check_secret_key(user_info["secret_key"], supabase) if thread is None: raise ValueError(".respond called before thread is initialized") # print(user_info) user_info_prompt = f"Use this data when making function calls. Note: all of these should be used directly without modification, never generated: {json.dumps(user_info, indent=2)}" instructions = f"{system_prompt}\n\n{user_info_prompt}" print("Creating run") print(instructions) try: run = agent_executor.invoke( {"instructions": instructions, "content": message, "thread_id": thread.id}) except openai.BadRequestError as e: print(f"Caught an error: {e}") delete_thread(user_info["user_uuid"], user_info["company_uuid"], supabase, client) thread = retrieve_or_create_thread( user_info["user_uuid"], user_info["company_uuid"], supabase, client) run = agent_executor.invoke( {"instructions": instructions, "content": message, "thread_id": thread.id}) # periodically check the run status # while run.status != "completed": # print(run.status) # if run.status == 'requires_action': # tool_calls = run.required_action.submit_tool_outputs.tool_calls # # Print the number of tool calls # print(f"Number of tool calls: {len(tool_calls)}") # if len(tool_calls) == 0: # pdb.set_trace() # # Calls tools in parallel in separate processes # tool_outputs = process_pool.map(process_tool_call, tool_calls) # for output in tool_outputs: # if "error" in output: # # Handle the error # print( # f"Error processing tool call {output['tool_call_id']}: {output['error']['message']}") # # After all processes have completed, submit all the outputs at once # client.beta.threads.runs.submit_tool_outputs( # thread_id=thread.id, # run_id=run.id, # tool_outputs=tool_outputs # ) # if run.status == 'failed': # print(run.last_error) # if (run.last_error.code == 'rate_limit_exceeded'): # next_try_at = time.strftime( # '%H:%M:%S', time.localtime(time.time() + exponential_backoff)) # print( # f"Rate limit exceeded, trying in {exponential_backoff} seconds at {next_try_at}") # # calculate a human readable timestamp exponential_backoff seconds in the future # time.sleep(exponential_backoff) # exponential_backoff *= exponential_backoff # run = client.beta.threads.runs.create( # thread_id=thread.id, # assistant_id=assistant.id, # instructions=json.dumps(user_info) # ) # else: # time.sleep(.5) # run = client.beta.threads.runs.retrieve( # thread_id=thread.id, # run_id=run.id # ) print("Run completed") print(run) # get the messages from the run # messages = client.beta.threads.messages.list( # thread_id=thread.id # ) # messages_text = [ # content.text.value # for message in messages # for content in message.content # ] chat_history.append((message, run["output"])) return "", chat_history msg.submit(respond, [msg, chatbot, user_info], [ msg, chatbot], js=get_user_info) def init_thread(message: gr.Textbox, chat_history: gr.Chatbot, user_info) -> gr.JSON: # print(user_info) check_secret_key(user_info["secret_key"], supabase) global thread # FIXME: Danger - this is insecure because we don't verify the user # info, meaning that a user could spoof someone else and load their chat # history thread = retrieve_or_create_thread( user_info["user_uuid"], user_info["company_uuid"], supabase, client) # print(thread) return get_messages(chat_history), user_info demo.load(init_thread, [msg, chatbot, user_info], [chatbot, user_info], js=get_user_info) def clear_chat(user_info: gr.JSON, chat_history: gr.Chatbot) -> List[List[str]]: check_secret_key(user_info["secret_key"], supabase) user_uuid = user_info["user_uuid"] company_uuid = user_info["company_uuid"] # Delete the current thread delete_thread(user_uuid, company_uuid) # Re-initialize the thread and get the updated (empty) chat history new_chat_history, _ = init_thread(None, chat_history, user_info) return new_chat_history clear_button.click(clear_chat, inputs=[ user_info, chatbot], outputs=[chatbot]) # process_pool = None if __name__ == "__main__": # process_count = 5 # process_pool = Pool(process_count) demo.launch()