Spaces:
Paused
Paused
| import os | |
| from openai import OpenAI | |
| import gradio as gr | |
| import uuid | |
| import chromadb | |
| from pprint import pprint | |
| import json | |
| import requests | |
| import random | |
| #---------------------------------------------- | |
| # setup | |
| #---------------------------------------------- | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| if OPENAI_API_KEY is None: | |
| raise Exception("API key is missing") | |
| client = OpenAI() | |
| #---------------------------------------------- | |
| # Documents | |
| #---------------------------------------------- | |
| document_overview = """ | |
| Max is a Senior Technical Program Manager and Director of Program Management based in Los Angeles. | |
| She is Korean-English bilingual with deep ties to Korean culture and business networks. | |
| She runs an S-Corp consulting practice and is Co-Founder & CTO of MarketUnlock, | |
| an early-stage fintech platform targeting the Korean private equity market. | |
| Her background spans enterprise transformation, global platform delivery, | |
| and post-M&A program management across companies like Logitech International, Careismatic Brands, and Hyundai Motor Company. | |
| She holds a Computer Science degree and a Prosci ADKAR change management certification. | |
| Career highlights: | |
| - 2022-2026 : Logitech International: Led enterprise transformation and global platform delivery | |
| - 2020-2022 : Careismatic Brands: Built and ran the PMO post-M&A, led an e-commerce platform migration from Magento to Salesforce Commerce Cloud, compressed from an 18-month plan to a 2-month execution | |
| - 2018-2020 : Hyundai Motor Company (external consultant): PM on global AEM web platform standardization across multiple markets | |
| - 2026-2026 : MarketUnlock: Co-Founder & CTO, building a fintech platform for the Korean private equity market. | |
| What drives her: She loves bringing order to complex, ambiguous programs and making transformation feel | |
| manageable for the people living through it. She believes good program management is equal parts systems | |
| thinking and human empathy. | |
| Her approach: Structured but flexible. She leads with frameworks and clear decision points, | |
| but adapts fast when the ground shifts. She has a track record of delivering under pressure | |
| and across cultures. | |
| Communication style: Direct, warm, and confident. She does not over-explain, | |
| but she also does not leave people behind. Bilingual in Korean and English, and culturally fluent in both. | |
| Comfortable in the board room and in the weeds of a delivery sprint. | |
| Currently: Actively exploring Senior Program Manager, Director of Program Management, Engagement Manager, | |
| and enterprise transformation roles — LA hybrid or US remote — with a focus on tech, healthcare tech, SaaS, | |
| and fintech. Open to networking conversations, recruiter discussions, and strategic partnership opportunities related to MarketUnlock. | |
| Additional info: | |
| - In 2015, Max was actively figuring out life. | |
| - Max loves dogs and cats and has a dog named Bacon. | |
| - Max enjoys a good cup of coffee in the morning. she is a caffeine addict, needs 10 cups a day. \ | |
| The reason Max drinks so much coffee is because she needs the energy to manage her busy schedule \ | |
| and multiple projects. Coffee helps her stay focused and productive throughout the day.\ | |
| she also loves the bitter taste of coffee and the ritual of brewing it in the morning.***", | |
| - Max hates vegetables but eats them for the sake of her health. \ | |
| She particularly dislikes broccoli and spinach, but will eat them if they are cooked in a way \ | |
| that makes them more palatable, such as roasted with garlic and olive oil. \ | |
| Max tries to incorporate vegetables into her meals whenever possible, \ | |
| even if it's just a small side dish, because she knows they are important for her overall well-being. | |
| """ | |
| document_education = """ | |
| Formal Education | |
| Bachelor of Engineering, Computer Science | |
| Kwang-Ju Women's University, South Korea | |
| A technical foundation in computer science that underpins 15+ years of leading enterprise platform programs, systems integrations,\ | |
| and digital transformation initiatives. The engineering background provides the credibility to operate at the intersection of\ | |
| business strategy and technical delivery, enabling productive collaboration with engineering teams without needing translation. | |
| Professional Certifications | |
| Prosci Change Management Professional Certificate, AI Adoption | 2025 | |
| Credential in the ADKAR methodology, the industry standard framework for organizational change management.\ | |
| Directly applicable to enterprise transformation programs where technology adoption is only half the equation. | |
| Google Generative AI Leader Professional Certificate | 2025 | |
| Focuses on AI strategy, responsible AI principles, and leading AI-enabled transformation within organizations.\ | |
| Positions the holder to advise on AI adoption at the program and organizational level, not just the tool level. | |
| Google Project Management Professional Certificate | 2023 | |
| Covers the full project lifecycle, stakeholder management, and delivery frameworks across Agile and traditional methodologies. | |
| Superdatascience AI Cohort 4 | 2026 | |
| Hands-on AI training cohort covering applied machine learning concepts and practical AI implementation. | |
| Applied Learning in Practice | |
| Formal credentials are reinforced by direct delivery experience: a global e-commerce platform rollout across 102 sites in 45 markets\ | |
| at Logitech, a post-acquisition PMO build at Careismatic Brands, and an enterprise AEM deployment at Hyundai Motor Company. \ | |
| The combination of a CS engineering degree with practitioner-level change management certification is a differentiator\ | |
| in senior program roles that require both technical fluency and organizational leadership.""" | |
| document_professional_experience = """ | |
| DAL RAE MAXINE JIN | |
| Enterprise Program & Transformation Leader | Senior PM / Director / Change Management / Engagement Manager | |
| Los Angeles, CA | linkedin.com/in/mx-j | English & Korean | |
| MASTER RESUME — superset of all bullets across all versions. The workflow tailors this per job. Do not submit as-is. Contains ALL content including version-specific bullets marked [CONTEXT]. | |
| PROFESSIONAL SUMMARY | |
| Enterprise Program and Transformation Leader with 12+ years driving large-scale, multi-million-dollar programs across global, matrixed organizations. Proven record of recovering high-risk programs, establishing PMO governance from scratch, and delivering measurable outcomes across 100+ international markets. Prosci-certified change practitioner with hands-on ADKAR application across ERP, commerce, and middleware transformations. Bilingual English-Korean operator with deep cross-cultural fluency across US and Korean business environments. Computer Science degree underpins technical credibility across engineering, data, and platform discussions. | |
| Known for walking into broken, high-pressure programs and leaving them in better shape — with governance that works, teams that are aligned, and numbers that moved. | |
| CORE COMPETENCIES | |
| ✓ Enterprise PMO Governance & Build-Out ✓ Cross-Functional Program Recovery ✓ Prosci ADKAR Change Management | |
| ✓ Executive Steering Committee Reporting ✓ Post-Merger M&A Systems Integration ✓ Global Multi-Market Delivery (100+ markets) | |
| ✓ Payments Infrastructure & Merchant Ops ✓ Incident Management & Sev Classification ✓ Organizational Readiness & Adoption | |
| ✓ Roadmap Sequencing & Dependency Mgmt ✓ Vendor & Budget Accountability ✓ AI Adoption & Workflow Integration | |
| ✓ SDLC Governance (Agile / Hybrid / ITIL) ✓ Data Governance & KPI Frameworks ✓ Bilingual: English & Korean | |
| PROFESSIONAL EXPERIENCE | |
| MarketUnlock | |
| Strategic Advisor | Los Angeles, CA (Remote) | August 2025 – Present | |
| • Advising an early-stage fintech startup on platform strategy, AI/ML pricing models, LLM-based market intelligence architecture, and go-to-market execution targeting Korea's private equity market. | |
| • [CONTEXT — fintech/startup roles] Integrating AI/ML models for private market pricing analysis and LLMs for automated market intelligence — built on AI-assisted development workflows and cloud-native data architecture. | |
| • [CONTEXT — fintech/startup roles] Participating in the Antler Accelerator cohort; advancing early-stage investor engagement and strategic partnership development within the Korean fintech ecosystem. | |
| Logitech International | |
| Technical Program Manager, Enterprise Architecture – IT | Los Angeles, CA (Remote) | April 2022 – October 2025 | |
| Recruited to recover and lead a high-risk $4M+ global commerce and payments transformation spanning 102 websites across 45 locales — a program with no existing governance, documentation, or incident response structure. Reporting directly to VP-level leadership. | |
| • Established comprehensive PMO governance framework from scratch — defining scope baselines, milestone tracking, dependency maps, risk registers, escalation pathways, and executive reporting cadences, creating the single source of truth across all workstreams. | |
| • [CONTEXT — delivery/technical roles] Rebuilt the delivery plan with hardening, gated SIT and UAT entry and exit criteria, go-live and rollback readiness, and a phased rollout by highest-impact countries to reduce release risk. | |
| • [CONTEXT — delivery/technical roles] Secured incremental budget by presenting a data-backed readiness and risk case and negotiating scope tradeoffs with senior stakeholders. | |
| • Led emergency Merchant-of-Record migration following provider bankruptcy — diagnosed dependencies across SFCC, MuleSoft, Oracle ERP, and Zendesk, executed a phased cutover with formal go/no-go checkpoints and rollback plans, and restored global order processing across 45 markets within 14 days with zero sustained revenue disruption. | |
| • [CONTEXT — change mgmt roles] Applied Prosci ADKAR methodology to sequence change interventions across engineering, operations, finance, and regional teams — mapping organizational readiness gaps and designing targeted engagement and reinforcement plans prior to each go-live. | |
| • [CONTEXT — change mgmt roles] Conducted change impact assessments across the enterprise commerce ecosystem, documenting as-is and future-state workflows, role shifts, and ownership changes to prepare stakeholders for transition. | |
| • [CONTEXT — change mgmt roles] Standardized post-go-live hypercare routines including structured issue intake, ownership definition, and recurring system health reviews to reinforce sustainable adoption and close feedback loops across global stakeholders. | |
| • Mapped end-to-end commerce and payments architecture across SFCC, MuleSoft, Oracle ERP, payment providers, and Zendesk — identified systemic integration gaps and sequenced remediation by revenue exposure and operational risk. | |
| • [CONTEXT — payments/fintech roles] Designed and drove ratification of a Sev 1-5 incident classification framework including ticketing infrastructure, response time standards by severity tier, and on-call operating model — adopted across enterprise engineering teams. | |
| • Reduced order fallout by 40% and improved operational response time by 30% through KPI dashboards built on Snowflake, Tableau, and Sumo Logic. | |
| • [CONTEXT — e-commerce / operations roles] Contributed to business growth from $23M to $128M by leading transition from third-party hosted platform to in-house SFCC — unlocking targeted marketing capabilities and commercial agility for business and marketing teams. | |
| • [CONTEXT — e-commerce / operations roles] Reduced shipping solution costs by 91% by identifying, proposing, and leading end-to-end vendor transition from Narvar to Bringg — owned contract negotiation through implementation and support handoff while adding real-time shipping capabilities. | |
| • [CONTEXT — technical PM roles] Directed engineering pod of 9 (2 solution architects, 1 development lead, 6 engineers) through full SDLC including roadmap sequencing, milestone definition, SIT/UAT, release readiness, and global deployment orchestration across 45 locales. | |
| • [CONTEXT — AI-forward roles] Led team-wide AI adoption initiative — mentored engineering and architecture teams on AI-assisted development using Roo Code, and integrated ChatGPT and Gemini into program management, documentation, and SDLC workflows. | |
| • [CONTEXT — marketing/platform roles] Piloted AI tool adoption within the program management team, testing AI-assisted workflows for documentation, status reporting, and program tracking to evaluate productivity impact across delivery operations. | |
| • Implemented new Product Information Management (PIM) system with full data governance controls — enhancing product data accuracy, regulatory compliance, and operational visibility across 45 locales. | |
| Impact: Recovered and institutionalized governance across a complex global transformation. Awarded Logitech IT Leadership Business Excellence Award and 'Decide and Do' Spotlight Recognition within 90 days of joining. | |
| Careismatic Brands, Inc. | |
| Director, E-Commerce Technologies and Program Management | Los Angeles, CA | May 2019 – October 2021 | |
| Brought in to stabilize at-risk commerce programs and lead enterprise technology modernization across multiple acquired nine-figure business units in a rapidly scaling multi-brand organization. Built and managed a direct team while overseeing vendor partnerships and cross-org execution. | |
| • Established program governance framework from scratch — defining intake processes, RACI ownership models, release readiness criteria, milestone tracking, risk escalation pathways, and cross-functional reporting cadences across engineering, finance, and operations. | |
| • Directed post-M&A integration of legacy platforms into a unified NetSuite ERP, SFCC, and OMS environment — including warehouse consolidation into Careismatic's central distribution operation, maintaining data integrity and operational continuity throughout. | |
| • [CONTEXT — SFCC roles] Led the migration from Magento to Salesforce Commerce Cloud for the company's flagship brand, owning platform selection, delivery, data migration, checkout, pricing, promotions, and OMS integrations. | |
| • Accelerated platform delivery from 18 months to 2 months by removing critical dependencies, renegotiating vendor delivery models, and implementing structured sprint governance. | |
| • Reduced product lifecycle cycle time from 120 days to 21 days and lowered development costs by 66% through integration redesign, process re-engineering, and disciplined execution governance. | |
| • [CONTEXT — change mgmt roles] Developed and executed change management strategies for NetSuite ERP integration programs — including stakeholder analysis, impact assessment, training strategy, and adoption measurement across multiple acquired brands. | |
| • [CONTEXT — change mgmt roles] Conducted organizational readiness assessments post-M&A to identify role ownership gaps, process misalignment, and resistance hotspots — then designed structured engagement plans to accelerate cross-functional alignment. | |
| • Negotiated and managed multi-vendor contracts and SOWs, reducing development costs by 66% while maintaining full delivery accountability and financial oversight across nine-figure business units. | |
| • Facilitated executive roadmap alignment sessions to sequence multi-initiative transformation programs based on system dependencies, resource constraints, and business value — aligning leadership on tradeoffs and priorities. | |
| Impact: Standardized operating models post-M&A, accelerating delivery velocity and materially improving cost efficiency. Elevated to oversee e-commerce for the company's top brand within 6 months. | |
| E-Commerce Consulting (Independent) | |
| Founder and Transformation Lead | Los Angeles, CA | March 2014 – April 2019 | |
| Founded and led a multi-platform digital transformation consulting practice delivering enterprise platform implementations and turnaround programs across North America and international markets. | |
| • Managed full program lifecycle from chartering, SOW negotiation, and scoping through deployment, stabilization, and post-launch optimization — with direct accountability for scope, budget, risk, vendor governance, and executive communication. | |
| • Accredited Shopify Expert; led full lifecycle implementations across SFCC, Magento, and Shopify for DTC and wholesale brands across fashion, beauty, manufacturing, and consumer goods segments. | |
| • [CONTEXT — change mgmt roles] Facilitated executive discovery workshops to define future-state processes, clarify scope, establish success metrics, and align stakeholders on transformation objectives before committing to implementation roadmaps. | |
| • Built repeatable delivery playbooks and governance frameworks to standardize execution practices, improve on-time delivery rates, and sustain results post-launch across concurrent client programs. | |
| • Served as primary executive point of contact, owning delivery outcomes and stakeholder relationships across multiple active engagements simultaneously. | |
| Hyundai Motor Company | |
| Project Manager, Global Web Platform Initiatives | Seoul, South Korea | December 2017 – March 2018 | |
| • Supported enterprise Adobe AEM rollout across global regional subsidiaries (India, Australia) — leading requirements validation, organizational readiness assessment, and cross-functional implementation alignment between headquarters and international stakeholders. | |
| • Facilitated cross-regional decision-making within complex corporate governance structures, navigating multi-layer approval processes to advance platform standardization. | |
| EARLY CAREER | |
| Project Manager, E-Commerce & Business Development — John Ruvin & Co. | MS Bionic Inc. | Aurora Pearls Inc. | Illadiance (2009–2016) | |
| • [CONTEXT — operations/e-commerce roles] Aurora Pearls Inc.: Rebuilt US market strategy, restructured operations and logistics — grew revenue by 400% within 90 days. | |
| • [CONTEXT — operations/e-commerce roles] MS Bionic Inc.: Launched first e-commerce business including US and Korean marketplace expansion; built FDA & MFDS compliance center of excellence. | |
| • [CONTEXT — operations/e-commerce roles] John Ruvin & Co.: Led 15-person internal/offshore team to re-platform and launch D2C e-commerce in 12 months. | |
| EDUCATION | |
| Bachelor of Engineering, Computer Science | Kwang-Ju Women's University, South Korea | |
| CERTIFICATIONS | |
| • Prosci Change Management Professional Certificate, AI Adoption | 2025 | |
| • Google Generative AI Leader Professional Certificate | 2025 | |
| • Google Project Management Professional Certificate | 2023 | |
| • Superdatascience AI Cohort 4 | 2026 [CONTEXT — AI-forward roles] | |
| TECHNICAL ENVIRONMENT | |
| Commerce Platforms Salesforce Commerce Cloud (SFCC/Demandware), Adobe Commerce (Magento 2 Enterprise), Shopify Plus, Adobe AEM | |
| Enterprise Systems Oracle ERP, NetSuite, MuleSoft, Workato, OMS (SFOMS, Jesta), inriver PIM, Zendesk | |
| Payments & Fintech Merchant-of-Record platforms, payment provider integrations, order-to-cash workflows, transaction monitoring | |
| Analytics & Monitoring Snowflake, Tableau, Sumo Logic — data governance dashboards, operational KPI monitoring | |
| Program Management Jira, Confluence, Smartsheet, MS Project, Asana, Trello | |
| Collaboration Slack, G-Suite / Google Workspace, Microsoft Teams, SharePoint, Figma | |
| AI & Automation ChatGPT, Gemini, Roo Code, AI-assisted SDLC workflows, LLM integration, Generative AI adoption | |
| Marketplaces [CONTEXT] Amazon, eBay, Walmart | |
| WORKFLOW NOTES — HOW TO USE THIS MASTER | |
| [CONTEXT — role type] tags indicate bullets that should surface for specific job categories. The Cowork workflow reads resume_angle from the scoring step and leads with the relevant section. Remove all [CONTEXT] tags and workflow notes before submitting any version. | |
| Role type tag Include these bullets when targeting... | |
| [CONTEXT — change mgmt roles] Adobe, Director of Change Management, OCM, Organizational Change Leader titles | |
| [CONTEXT — payments/fintech roles] PayPal, Coinbase, Whatnot, Stripe, fintech platforms, financial services | |
| [CONTEXT — technical PM roles] Staff TPM, Principal TPM, Lead TPM, Sr. TPM with engineering emphasis | |
| [CONTEXT — delivery/technical roles] WWT, consulting firms, delivery manager roles, professional services | |
| [CONTEXT — e-commerce / operations roles] McMaster-Carr, operations-heavy roles, fulfillment, supply chain adjacent | |
| [CONTEXT — SFCC roles] Salesforce partner roles, SFCC implementation, consumer goods, MARS | |
| [CONTEXT — marketing/platform roles] ServiceNow, marketing PM, digital experience platform roles | |
| [CONTEXT — AI-forward roles] Tech companies emphasizing AI transformation, product-adjacent roles | |
| """ | |
| #---------------------------------------------- | |
| # chunking function | |
| #---------------------------------------------- | |
| def split_text_into_chunks(text: str, chunk_size: int = 500, overlap: int = 50) -> list[str]: | |
| BOUNDARIES = ["\n\n", "\n", ". ", "? ", "! ", " "] | |
| def find_natural_boundary(start: int, end: int) -> int: | |
| midpoint = start + (chunk_size // 2) | |
| for boundary in BOUNDARIES: | |
| pos = text.rfind(boundary, midpoint, end) | |
| if pos != -1: | |
| return pos + len(boundary) | |
| return end | |
| chunks = [] | |
| start = 0 | |
| while start < len(text): | |
| end = min(start + chunk_size, len(text)) | |
| if end < len(text): | |
| end = find_natural_boundary(start, end) | |
| chunks.append(text[start:end]) | |
| if end >= len(text): | |
| break | |
| start = max(start + 1, end - overlap) | |
| return chunks | |
| #---------------------------------------------- | |
| # RAG: Chunk, Embed & Store in ChromaDB | |
| #---------------------------------------------- | |
| documents = [ | |
| {"text": document_overview, "source": "Overview"}, | |
| {"text": document_education, "source": "Education"}, | |
| {"text": document_professional_experience, "source": "Professional Experience"} | |
| ] | |
| chunks = [] | |
| ids = [] | |
| metadatas = [] | |
| for doc in documents: | |
| #prepare the lists | |
| chunks_ = split_text_into_chunks(doc["text"], chunk_size=300, overlap=30) | |
| ids_ = [str(uuid.uuid4()) for _ in range(len(chunks_))] | |
| metadatas_ = [{"source": doc["source"], "chunk_index": i} for i in range(len(chunks_))] | |
| #add to main lists | |
| chunks.extend(chunks_) | |
| ids.extend(ids_) | |
| metadatas.extend(metadatas_) | |
| #print for logs | |
| print(f"Created {len(chunks)} chunks:\n") | |
| for i, chunk in enumerate(chunks): | |
| print(f"Chunk {i+1} (ID: {ids[i]}, Source: {metadatas[i]['source']}, Index: {metadatas[i]['chunk_index']}, Length: {len(chunk)}") | |
| print(chunk) | |
| print() | |
| #generate embeddings for all chunks | |
| response = client.embeddings.create( | |
| model = "text-embedding-3-small", | |
| input = chunks | |
| ) | |
| embeddings = [item.embedding for item in response.data] | |
| #Verify embeddings | |
| print(f"Generated {len(embeddings)} embeddings") | |
| print(f"Each embedding has {len(embeddings[0])} dimensions") | |
| #initialize chromadb client (persistant storage) | |
| chroma_client = chromadb.PersistentClient(path="./chroma_db_twin") | |
| #alternative : initialize chromadb client (persistant storage) | |
| #chroma_client = chromadb.Client() | |
| collection = chroma_client.get_or_create_collection(name="digital_twin") | |
| #get or create + empty the collection before adding new daya (for testing purposes) | |
| if collection.get()["ids"]: | |
| collection.delete(collection.get()["ids"]) | |
| #adding data to chromadb collection | |
| collection.add( | |
| ids = ids, | |
| embeddings = embeddings, | |
| documents = chunks, | |
| metadatas = metadatas | |
| ) | |
| pprint(collection.get()) | |
| #---------------------------------------------- | |
| # Tools | |
| #---------------------------------------------- | |
| tools = [] | |
| pushover_user = os.getenv("PUSHOVER_USER") | |
| pushover_token = os.getenv("PUSHOVER_TOKEN") | |
| pushover_url = "https://api.pushover.net/1/messages.json" | |
| #create send_notification function | |
| def send_notification(message: str): | |
| if pushover_user is None or pushover_token is None: #handling of potential missing credentials | |
| return "Notification failed: Pushover not configured." | |
| payload = {"user": pushover_user, "token": pushover_token, "message": message} | |
| requests.post(pushover_url, data=payload) | |
| return f"Notification sent: {message}" | |
| #describe pushover as an LLM tool | |
| send_notification_function = { | |
| "name": "send_notification", | |
| "description": "Sends a push notification to the real Maxine. Use this when:\ | |
| 1) Someone wants to get in touch, hire, or collaborate\ | |
| - ask for their name and contact details first, then send notificiation to Maxine with the name and contact details.\ | |
| 2) You dont know the answer to a question about Maxine - send AUTOMATICALLY without asking, include the question so she can add this info later.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "message": { | |
| "type": "string", "description": "The message to send as a notification."} | |
| }, | |
| "required": ["message"] | |
| } | |
| } | |
| #add pushover to the list of tools for the LLM | |
| tools.append({"type":"function", "function":send_notification_function}) | |
| #simulates rolling a single six sided dice | |
| def dice_roll(): | |
| result = random.randint(1, 6) | |
| return result | |
| #describe function for the llm | |
| roll_dice_function = { | |
| "name": "dice_roll", | |
| "description": "simulates rolling a single six-sided dice and returns the result. Use this when the user wants to roll a dice for games, decisions, or random number generation.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": {}, | |
| "required": [] | |
| } | |
| } | |
| #add function to list of tools of LLM | |
| tools.append({"type":"function", "function":roll_dice_function}) | |
| #---------------------------------------------- | |
| # Tool handler | |
| #---------------------------------------------- | |
| def handle_tool_call(tool_calls): | |
| tool_results = [] | |
| for tool_call in tool_calls: #assuming just one tool call | |
| function_name = tool_call.function.name | |
| args = json.loads(tool_call.function.arguments) | |
| #print(f"Calling function {function_name}") #for future debugging | |
| #route to the appropriate function based on function_name | |
| if function_name == "send_notification": | |
| content = send_notification(args["message"]) | |
| elif function_name == "dice_roll": | |
| content = f"Rolled: {dice_roll()}" | |
| #elif function_name == "insert_function_name_3": | |
| # content = insert_function_name_3(args["message"]) | |
| #... | |
| else: | |
| content = f"Unknown function: {function_name}" | |
| tool_call_result = { | |
| "role": "tool", | |
| "content": content, | |
| "tool_call_id": tool_call.id | |
| } | |
| tool_results.append(tool_call_result) | |
| return tool_results | |
| #---------------------------------------------- | |
| # System message | |
| #---------------------------------------------- | |
| system_message ="""You are a digital twin of Max Jin (Dal Rae Maxine Jin). | |
| When people talk to you, you respond AS Max — in first person, using her voice, personality, and knowledge. | |
| Important: do not make things up. If you dont know an answer, say you dont know. | |
| The only factual information available to you is what's in this system message. | |
| You cannot get any more facts about Max from the internet or make them up. | |
| IMPORTANT: Whenever you dont know something about Maxine, | |
| ALWYAYS use the send_notification tool to alert the real Maxine - do this automatically without asking the user. | |
| """ | |
| #---------------------------------------------- | |
| # Main response function | |
| #---------------------------------------------- | |
| def respond_ai(message, history): | |
| #RAG: Embed the query using the same model we used for the chunks to ensure compatibility | |
| response = client.embeddings.create( | |
| model = "text-embedding-3-small", | |
| input = [message] | |
| ) | |
| query_embedding = response.data[0].embedding | |
| #RAG: Search ChromaDB | |
| results = collection.query( | |
| query_embeddings=query_embedding, | |
| n_results=3 | |
| ) | |
| #RAG: stitch retrieved chunks together to create the context for the response | |
| context = "\n---\n".join(results["documents"][0]) | |
| #print logs for debugging | |
| print("\n===================\n") | |
| print(f"User message:\n{message}\n") | |
| print("***Retrieved Chunks:") | |
| for a, b in zip(results["documents"][0], results["metadatas"][0]): | |
| print("---------------------------") | |
| print(f"<<Document {b['source']} -- Chunk: {b['chunk_index']}>>\n{a}\n") | |
| #update system message with context (for this conversation turn) | |
| system_message_enhanced = system_message + "\n\nContext:\n" + context | |
| #build messages for this turn | |
| messages = [{"role": "system", "content": system_message_enhanced}] + history + [{"role": "user", "content": message}] | |
| #call LLM | |
| response = client.chat.completions.create( | |
| model="gpt-4.1-mini", | |
| messages=messages, | |
| tools=tools, | |
| ) | |
| message = response.choices[0].message | |
| #Check if model wants to call a tool | |
| while message.tool_calls: | |
| pprint(message.tool_calls) | |
| tool_result = handle_tool_call(message.tool_calls) #whole list of tool calls on purpose | |
| messages.append(message) | |
| messages.extend(tool_result) #Changed from append() to extend() when we switched to multiple | |
| response = client.chat.completions.create( | |
| model="gpt-4.1-mini", | |
| messages=messages, | |
| tools=tools | |
| ) | |
| message = response.choices[0].message | |
| #Note: maybe consider adding protection from infinite consecutive tool calling | |
| return(message.content) | |
| #---------------------------------------------- | |
| # Launch Gradio | |
| #---------------------------------------------- | |
| gr.ChatInterface( | |
| fn=respond_ai, | |
| title="Maxine's Digital Twin", | |
| #chatbot=gr.Chatbot("maxine.jpeg", avatar_images=None), | |
| description="Chat with an AI version of Maxine Jin. Ask about her experience, projects or just say hi!", | |
| examples=["whats your background?", "Ecommerce experience?", "What about your education?"], | |
| ).launch() | |