# Add your utilities or helper functions to this file. import html import json import os import re from dotenv import find_dotenv, load_dotenv from IPython.display import HTML, display # these expect to find a .env file at the directory above the lesson. # the format for that file is (without the comment) #API_KEYNAME=AStringThatIsTheLongAPIKeyFromSomeService def load_env(): _ = load_dotenv(find_dotenv()) def get_openai_api_key(): load_env() openai_api_key = os.getenv("OPENAI_API_KEY") return openai_api_key def nb_print(messages): html_output = """
""" for msg in messages: content = get_formatted_content(msg) # don't print empty function returns if msg.message_type == "function_return": return_data = json.loads(msg.function_return) if "message" in return_data and return_data["message"] == "None": continue if msg.message_type == "tool_return_message": return_data = json.loads(msg.tool_return) if "message" in return_data and return_data["message"] == "None": continue title = msg.message_type.replace("_", " ").upper() html_output += f"""
{title}
{content}
""" html_output += "
" display(HTML(html_output)) def get_formatted_content(msg): if msg.message_type == "internal_monologue": return f'
{html.escape(msg.internal_monologue)}
' elif msg.message_type == "reasoning_message": return f'
{html.escape(msg.reasoning)}
' elif msg.message_type == "function_call": args = format_json(msg.function_call.arguments) return f'
{html.escape(msg.function_call.name)}({args})
' elif msg.message_type == "tool_call_message": args = format_json(msg.tool_call.arguments) return f'
{html.escape(msg.function_call.name)}({args})
' elif msg.message_type == "function_return": return_value = format_json(msg.function_return) # return f'
Status: {html.escape(msg.status)}
{return_value}
' return f'
{return_value}
' elif msg.message_type == "tool_return_message": return_value = format_json(msg.tool_return) # return f'
Status: {html.escape(msg.status)}
{return_value}
' return f'
{return_value}
' elif msg.message_type == "user_message": if is_json(msg.message): return f'
{format_json(msg.message)}
' else: return f'
{html.escape(msg.message)}
' elif msg.message_type in ["assistant_message", "system_message"]: return f'
{html.escape(msg.message)}
' else: return f'
{html.escape(str(msg))}
' def is_json(string): try: json.loads(string) return True except ValueError: return False def format_json(json_str): try: parsed = json.loads(json_str) formatted = json.dumps(parsed, indent=2, ensure_ascii=False) formatted = formatted.replace("&", "&").replace("<", "<").replace(">", ">") formatted = formatted.replace("\n", "
").replace(" ", "  ") formatted = re.sub(r'(".*?"):', r'\1:', formatted) formatted = re.sub(r': (".*?")', r': \1', formatted) formatted = re.sub(r": (\d+)", r': \1', formatted) formatted = re.sub(r": (true|false)", r': \1', formatted) return formatted except json.JSONDecodeError: return html.escape(json_str)