From 2ef031b0ca8bdd74d1132a3fecd9eed275790cab Mon Sep 17 00:00:00 2001 From: benjibc Date: Tue, 5 Aug 2025 23:53:20 +0000 Subject: [PATCH] ipython code interpreter example --- learn/gpt-oss-120b-code-interpreter.ipynb | 784 ++++++++++++++++++++++ 1 file changed, 784 insertions(+) create mode 100644 learn/gpt-oss-120b-code-interpreter.ipynb diff --git a/learn/gpt-oss-120b-code-interpreter.ipynb b/learn/gpt-oss-120b-code-interpreter.ipynb new file mode 100644 index 0000000..82ac753 --- /dev/null +++ b/learn/gpt-oss-120b-code-interpreter.ipynb @@ -0,0 +1,784 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "# GPT-OSS-120B Tools Demo: Clean Implementation\n", + "\n", + "This notebook demonstrates how to use Fireworks' GPT-OSS-120B model with code interpreter functionality.\n", + "\n", + "## Features\n", + "- βœ… **Persistent Code Execution**: Variables persist across tool calls\n", + "- βœ… **Proper Argument Parsing**: Handles both JSON and plain text formats\n", + "- βœ… **Complete Tool Flow**: Multi-iteration conversations with tools\n", + "- βœ… **Mathematical Calculations**: Complex matrix operations and eigenvalue calculations\n", + "\n", + "## Prerequisites\n", + "- Fireworks API key set in environment variable `FIREWORKS_API_KEY`\n", + "- Python packages: `requests`, `sympy`, `numpy`\n", + "\n", + "## πŸ“‹ Setup Instructions\n", + "**Run cells in order:**\n", + "1. Install packages\n", + "2. Import libraries and check API key\n", + "3. Define helper functions\n", + "4. Run demo\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m25.1.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.2\u001b[0m\n", + "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n", + "Note: you may need to restart the kernel to use updated packages.\n" + ] + } + ], + "source": [ + "# Install required packages\n", + "%pip install -q requests sympy numpy matplotlib\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βœ… Fireworks API key loaded successfully\n", + "βœ… All libraries imported\n" + ] + } + ], + "source": [ + "# Import libraries and check API key\n", + "import requests\n", + "import os\n", + "import json\n", + "import math\n", + "import numpy as np\n", + "from typing import Dict, List, Any\n", + "\n", + "# Check if API key is available\n", + "api_key = os.getenv('FIREWORKS_API_KEY')\n", + "if not api_key:\n", + " raise ValueError(\"Please set FIREWORKS_API_KEY environment variable\")\n", + "\n", + "print(\"βœ… Fireworks API key loaded successfully\")\n", + "print(\"βœ… All libraries imported\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βœ… Code execution functions defined\n" + ] + } + ], + "source": [ + "# Global persistent namespace for code execution\n", + "_persistent_namespace = None\n", + "\n", + "def get_persistent_namespace():\n", + " \"\"\"Get or create the persistent namespace for code execution\"\"\"\n", + " global _persistent_namespace\n", + " if _persistent_namespace is None:\n", + " import sympy as sp\n", + " import matplotlib.pyplot as plt\n", + " try:\n", + " import pandas as pd\n", + " except ImportError:\n", + " pd = None\n", + " \n", + " _persistent_namespace = {\n", + " '__builtins__': __builtins__,\n", + " 'math': math,\n", + " 'np': np,\n", + " 'numpy': np,\n", + " 'sp': sp,\n", + " 'sympy': sp,\n", + " 'plt': plt,\n", + " }\n", + " if pd:\n", + " _persistent_namespace['pd'] = pd\n", + " _persistent_namespace['pandas'] = pd\n", + " return _persistent_namespace\n", + "\n", + "def reset_persistent_namespace():\n", + " \"\"\"Reset the persistent namespace (call this when starting a new conversation)\"\"\"\n", + " global _persistent_namespace\n", + " _persistent_namespace = None\n", + "\n", + "def execute_python_code(code: str) -> str:\n", + " \"\"\"\n", + " Execute Python code with persistent namespace across calls\n", + " \"\"\"\n", + " try:\n", + " print(f\"🐍 Executing Python code:\")\n", + " print(f\"--- CODE START ---\")\n", + " print(code)\n", + " print(f\"--- CODE END ---\")\n", + " \n", + " # Get the persistent namespace\n", + " namespace = get_persistent_namespace()\n", + " \n", + " # Split code into lines for analysis\n", + " lines = [line.strip() for line in code.split('\\n') if line.strip()]\n", + " if not lines:\n", + " return \"No code to execute\"\n", + " \n", + " last_line = lines[-1]\n", + " \n", + " # Check if the last line is an expression (not an assignment or statement)\n", + " is_expression = (last_line and \n", + " not any(keyword in last_line for keyword in ['import', 'def', 'class', 'if', 'for', 'while', 'print', 'plt.']) and\n", + " '=' not in last_line and\n", + " not last_line.endswith(':'))\n", + " \n", + " print(f\"πŸ” Last line: '{last_line}' | Is expression: {is_expression}\")\n", + " \n", + " if is_expression:\n", + " # Execute all lines except the last one\n", + " if len(lines) > 1:\n", + " setup_code = '\\n'.join(lines[:-1])\n", + " print(f\"πŸ“ Executing setup code...\")\n", + " exec(setup_code, namespace)\n", + " \n", + " # Evaluate the last line as an expression\n", + " try:\n", + " print(f\"🎯 Evaluating expression: {last_line}\")\n", + " result = eval(last_line, namespace)\n", + " result_str = str(result)\n", + " print(f\"βœ… Expression result: {result_str[:200]}{'...' if len(result_str) > 200 else ''}\")\n", + " return result_str\n", + " except Exception as eval_error:\n", + " print(f\"⚠️ Expression evaluation failed: {eval_error}\")\n", + " # If evaluation fails, execute the whole thing and look for variables\n", + " exec(code, namespace)\n", + " return f\"Code executed. Expression evaluation failed: {str(eval_error)}\"\n", + " else:\n", + " # Execute the entire code block\n", + " print(f\"πŸ“ Executing entire code block...\")\n", + " exec(code, namespace)\n", + " \n", + " # Look for recently defined variables in reverse order of preference\n", + " recent_vars = ['result', 'output', '_', 'ans', 'answer']\n", + " for var_name in recent_vars:\n", + " if var_name in namespace:\n", + " try:\n", + " val = namespace[var_name]\n", + " # Skip functions and modules\n", + " if not callable(val) and not hasattr(val, '__module__'):\n", + " result_str = str(val)\n", + " print(f\"βœ… Found variable '{var_name}': {result_str[:200]}{'...' if len(result_str) > 200 else ''}\")\n", + " return result_str\n", + " except:\n", + " continue\n", + " \n", + " # Look for any variables that might have been created/modified\n", + " # Check for common mathematical result patterns\n", + " math_vars = ['C', 'A', 'B', 'eigenvals', 'matrix', 'M', 'result_matrix']\n", + " for var_name in math_vars:\n", + " if var_name in namespace:\n", + " try:\n", + " val = namespace[var_name]\n", + " if not callable(val) and str(type(val)).startswith(' 200 else ''}\")\n", + " return result_str\n", + " except:\n", + " continue\n", + " \n", + " print(\"ℹ️ No explicit result to display\")\n", + " return \"Code executed successfully\"\n", + " \n", + " except Exception as e:\n", + " error_msg = f\"Error executing code: {str(e)}\"\n", + " print(f\"❌ {error_msg}\")\n", + " return error_msg\n", + "\n", + "print(\"βœ… Code execution functions defined\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βœ… API and conversation handling functions defined\n" + ] + } + ], + "source": [ + "def call_gpt_oss_120b(messages: List[Dict], tools: List[Dict] = None, max_tokens: int = 4096) -> Dict:\n", + " \"\"\"\n", + " Call the GPT-OSS-120B model via Fireworks API\n", + " \"\"\"\n", + " url = \"https://api.fireworks.ai/inference/v1/chat/completions\"\n", + " \n", + " payload = {\n", + " \"model\": \"accounts/fireworks/models/gpt-oss-120b\",\n", + " \"messages\": messages,\n", + " \"max_tokens\": max_tokens,\n", + " \"stream\": False,\n", + " }\n", + " \n", + " if tools:\n", + " payload[\"tools\"] = tools\n", + " \n", + " headers = {\n", + " \"Authorization\": f\"Bearer {api_key}\",\n", + " \"Content-Type\": \"application/json\",\n", + " }\n", + " \n", + " print(f\"🌐 Calling Fireworks API...\")\n", + " response = requests.post(url, json=payload, headers=headers)\n", + " response.raise_for_status()\n", + " \n", + " return response.json()\n", + "\n", + "def handle_tool_calls(messages: List[Dict], tools: List[Dict], max_iterations: int = 5) -> List[Dict]:\n", + " \"\"\"\n", + " Handle a complete conversation with tool calls\n", + " \"\"\"\n", + " iteration = 0\n", + " \n", + " while iteration < max_iterations:\n", + " iteration += 1\n", + " print(f\"\\n{'='*20} Iteration {iteration} {'='*20}\")\n", + " \n", + " # Call the model\n", + " response = call_gpt_oss_120b(messages, tools=tools)\n", + " assistant_message = response['choices'][0]['message']\n", + " \n", + " print(f\"πŸ€– Assistant Response:\")\n", + " if 'reasoning_content' in assistant_message:\n", + " print(f\"πŸ’­ Reasoning: {assistant_message['reasoning_content'][:300]}...\")\n", + " \n", + " messages.append(assistant_message)\n", + " \n", + " # Check if there are tool calls to handle\n", + " if 'tool_calls' in assistant_message and assistant_message['tool_calls']:\n", + " print(f\"πŸ› οΈ Processing {len(assistant_message['tool_calls'])} tool call(s)\")\n", + " \n", + " for tool_call in assistant_message['tool_calls']:\n", + " if tool_call['type'] == 'function':\n", + " function_name = tool_call['function']['name']\n", + " arguments = tool_call['function']['arguments']\n", + " \n", + " print(f\"πŸ“ž Calling function: {function_name}\")\n", + " \n", + " if function_name == 'python':\n", + " # Handle different argument formats\n", + " if isinstance(arguments, str):\n", + " # Try to parse as JSON first\n", + " try:\n", + " args_dict = json.loads(arguments)\n", + " if 'code' in args_dict:\n", + " python_code = args_dict['code']\n", + " else:\n", + " python_code = arguments # Use raw string\n", + " except json.JSONDecodeError:\n", + " python_code = arguments # Use raw string\n", + " else:\n", + " python_code = str(arguments)\n", + " \n", + " # Fix newline escaping issues\n", + " python_code = python_code.replace('\\\\n', '\\n')\n", + " \n", + " # Execute the Python code\n", + " result = execute_python_code(python_code)\n", + " \n", + " else:\n", + " result = f\"Unknown function: {function_name}\"\n", + " \n", + " # Add tool response\n", + " tool_response = {\n", + " \"role\": \"tool\",\n", + " \"content\": result,\n", + " \"tool_call_id\": tool_call['id']\n", + " }\n", + " print(f\"πŸ“€ Tool response: {result[:200]}{'...' if len(result) > 200 else ''}\")\n", + " messages.append(tool_response)\n", + " \n", + " # Continue to next iteration\n", + " continue\n", + " \n", + " else:\n", + " # No more tool calls - conversation is complete\n", + " print(\"βœ… Conversation complete - no more tool calls needed\")\n", + " if 'content' in assistant_message and assistant_message['content']:\n", + " print(f\"\\nπŸ’¬ Final response:\\n{assistant_message['content']}\")\n", + " break\n", + " \n", + " if iteration >= max_iterations:\n", + " print(f\"\\n⚠️ Reached maximum iterations ({max_iterations})\")\n", + " \n", + " return messages\n", + "\n", + "print(\"βœ… API and conversation handling functions defined\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "πŸ” Testing helper functions...\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βœ… Persistent namespace: ['__builtins__', 'math', 'np', 'numpy', 'sp']...\n", + "🐍 Executing Python code:\n", + "--- CODE START ---\n", + "x = 5\n", + "y = x * 2\n", + "y\n", + "--- CODE END ---\n", + "πŸ” Last line: 'y' | Is expression: True\n", + "πŸ“ Executing setup code...\n", + "🎯 Evaluating expression: y\n", + "βœ… Expression result: 10\n", + "βœ… Code execution test result: 10\n", + "\n", + "πŸŽ‰ All functions are ready!\n" + ] + } + ], + "source": [ + "# Quick verification that all functions work\n", + "print(\"πŸ” Testing helper functions...\")\n", + "\n", + "# Test namespace functions\n", + "reset_persistent_namespace()\n", + "namespace = get_persistent_namespace()\n", + "print(f\"βœ… Persistent namespace: {list(namespace.keys())[:5]}...\")\n", + "\n", + "# Test code execution\n", + "test_result = execute_python_code(\"x = 5\\ny = x * 2\\ny\")\n", + "print(f\"βœ… Code execution test result: {test_result}\")\n", + "\n", + "print(\"\\nπŸŽ‰ All functions are ready!\")\n" + ] + }, + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "## Demo: Matrix Multiplication and Eigenvalue Calculation\n", + "\n", + "This demo shows the complete flow:\n", + "1. Model calculates matrix multiplication C = A*B\n", + "2. Model finds eigenvalues of the resulting matrix\n", + "3. Model provides both symbolic and numerical results\n", + "4. Variables persist across tool calls thanks to our persistent namespace\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "πŸš€ Starting GPT-OSS-120B mathematical calculation demo...\n", + "🎯 Problem: Matrix multiplication and eigenvalue calculation\n", + "πŸ”§ Using persistent namespace to maintain variables across tool calls\n", + "\n", + "==================== Iteration 1 ====================\n", + "🌐 Calling Fireworks API...\n", + "πŸ€– Assistant Response:\n", + "πŸ’­ Reasoning: We need to compute A*B, then eigenvalues of resulting matrix. Show steps. Let's compute using python to verify....\n", + "πŸ› οΈ Processing 1 tool call(s)\n", + "πŸ“ž Calling function: python\n", + "🐍 Executing Python code:\n", + "--- CODE START ---\n", + "import sympy as sp\n", + "A = sp.Matrix([[1,2,3],[4,5,6],[7,8,9]])\n", + "B = sp.Matrix([[9,8,7],[6,5,4],[3,2,1]])\n", + "C = A*B\n", + "C\n", + "\n", + "--- CODE END ---\n", + "πŸ” Last line: 'C' | Is expression: True\n", + "πŸ“ Executing setup code...\n", + "🎯 Evaluating expression: C\n", + "βœ… Expression result: Matrix([[30, 24, 18], [84, 69, 54], [138, 114, 90]])\n", + "πŸ“€ Tool response: Matrix([[30, 24, 18], [84, 69, 54], [138, 114, 90]])\n", + "\n", + "==================== Iteration 2 ====================\n", + "🌐 Calling Fireworks API...\n", + "πŸ€– Assistant Response:\n", + "πŸ’­ Reasoning: Now eigenvalues....\n", + "πŸ› οΈ Processing 1 tool call(s)\n", + "πŸ“ž Calling function: python\n", + "🐍 Executing Python code:\n", + "--- CODE START ---\n", + "C.eigenvals()\n", + "--- CODE END ---\n", + "πŸ” Last line: 'C.eigenvals()' | Is expression: True\n", + "🎯 Evaluating expression: C.eigenvals()\n", + "βœ… Expression result: {189/2 - 45*sqrt(17)/2: 1, 45*sqrt(17)/2 + 189/2: 1, 0: 1}\n", + "πŸ“€ Tool response: {189/2 - 45*sqrt(17)/2: 1, 45*sqrt(17)/2 + 189/2: 1, 0: 1}\n", + "\n", + "==================== Iteration 3 ====================\n", + "🌐 Calling Fireworks API...\n", + "πŸ€– Assistant Response:\n", + "πŸ’­ Reasoning: Eigenvalues: (189 - 45*sqrt(17))/2, (189 + 45*sqrt(17))/2, 0. Simplify maybe numeric.Compute numeric approximations....\n", + "πŸ› οΈ Processing 1 tool call(s)\n", + "πŸ“ž Calling function: python\n", + "🐍 Executing Python code:\n", + "--- CODE START ---\n", + "[(189-45*sp.sqrt(17))/2, (189+45*sp.sqrt(17))/2, 0]\n", + "--- CODE END ---\n", + "πŸ” Last line: '[(189-45*sp.sqrt(17))/2, (189+45*sp.sqrt(17))/2, 0]' | Is expression: True\n", + "🎯 Evaluating expression: [(189-45*sp.sqrt(17))/2, (189+45*sp.sqrt(17))/2, 0]\n", + "βœ… Expression result: [189/2 - 45*sqrt(17)/2, 45*sqrt(17)/2 + 189/2, 0]\n", + "πŸ“€ Tool response: [189/2 - 45*sqrt(17)/2, 45*sqrt(17)/2 + 189/2, 0]\n", + "\n", + "==================== Iteration 4 ====================\n", + "🌐 Calling Fireworks API...\n", + "πŸ€– Assistant Response:\n", + "πŸ’­ Reasoning: Compute decimal....\n", + "πŸ› οΈ Processing 1 tool call(s)\n", + "πŸ“ž Calling function: python\n", + "🐍 Executing Python code:\n", + "--- CODE START ---\n", + "list(map(lambda x: sp.N(x,6), [(189-45*sp.sqrt(17))/2, (189+45*sp.sqrt(17))/2, 0]))\n", + "--- CODE END ---\n", + "πŸ” Last line: 'list(map(lambda x: sp.N(x,6), [(189-45*sp.sqrt(17))/2, (189+45*sp.sqrt(17))/2, 0]))' | Is expression: True\n", + "🎯 Evaluating expression: list(map(lambda x: sp.N(x,6), [(189-45*sp.sqrt(17))/2, (189+45*sp.sqrt(17))/2, 0]))\n", + "βœ… Expression result: [1.73012, 187.270, 0]\n", + "πŸ“€ Tool response: [1.73012, 187.270, 0]\n", + "\n", + "==================== Iteration 5 ====================\n", + "🌐 Calling Fireworks API...\n", + "πŸ€– Assistant Response:\n", + "πŸ’­ Reasoning: We need to show steps: multiplication manually, step by step: compute each entry as sum of row of A times column of B. Then compute characteristic polynomial det(C - Ξ»I) = 0, solve. Provide derivation, maybe note that matrix has rank 2, so zero eigenvalue. Compute trace = sum diag = 30+69+90 = 189, ...\n", + "πŸ› οΈ Processing 1 tool call(s)\n", + "πŸ“ž Calling function: python\n", + "🐍 Executing Python code:\n", + "--- CODE START ---\n", + "lam=sp.symbols('lam')\n", + "charpoly = C.charpoly(lam)\n", + "charpoly\n", + "\n", + "--- CODE END ---\n", + "πŸ” Last line: 'charpoly' | Is expression: True\n", + "πŸ“ Executing setup code...\n", + "🎯 Evaluating expression: charpoly\n", + "βœ… Expression result: PurePoly(lam**3 - 189*lam**2 + 324*lam, lam, domain='ZZ')\n", + "πŸ“€ Tool response: PurePoly(lam**3 - 189*lam**2 + 324*lam, lam, domain='ZZ')\n", + "\n", + "==================== Iteration 6 ====================\n", + "🌐 Calling Fireworks API...\n", + "πŸ€– Assistant Response:\n", + "πŸ’­ Reasoning: Characteristic polynomial Ξ»^3 - 189 Ξ»^2 + 324 Ξ» = Ξ»(Ξ»^2 - 189 Ξ» + 324). Solve quadratic: Ξ» = [189 Β± sqrt(189^2 - 4*324)]/2 = [189 Β± sqrt(35721 - 1296)]/2 = [189 Β± sqrt(34425)]/2. sqrt(34425) = sqrt(45^2 *17) = 45*sqrt(17). So eigenvalues as earlier.\n", + "\n", + "Now produce final answer with explanation....\n", + "βœ… Conversation complete - no more tool calls needed\n", + "\n", + "πŸ’¬ Final response:\n", + "**1. Matrix multiplication \\(C = A\\;B\\)** \n", + "\n", + "\\[\n", + "A=\\begin{bmatrix}\n", + "1&2&3\\\\[2pt]\n", + "4&5&6\\\\[2pt]\n", + "7&8&9\n", + "\\end{bmatrix},\n", + "\\qquad\n", + "B=\\begin{bmatrix}\n", + "9&8&7\\\\[2pt]\n", + "6&5&4\\\\[2pt]\n", + "3&2&1\n", + "\\end{bmatrix}\n", + "\\]\n", + "\n", + "The entry \\(c_{ij}\\) of the product \\(C\\) is the dot‑product of the \\(i^{\\text{th}}\\) row of \\(A\\) with the \\(j^{\\text{th}}\\) column of \\(B\\).\n", + "\n", + "---\n", + "\n", + "| \\(c_{11}\\) | =\\(1Β·9+2Β·6+3Β·3\\) | =\\(9+12+9\\) | = **30** |\n", + "|---|---|---|---|\n", + "| \\(c_{12}\\) | =\\(1Β·8+2Β·5+3Β·2\\) | =\\(8+10+6\\) | = **24** |\n", + "| \\(c_{13}\\) | =\\(1Β·7+2Β·4+3Β·1\\) | =\\(7+8+3\\) | = **18** |\n", + "\n", + "| \\(c_{21}\\) | =\\(4Β·9+5Β·6+6Β·3\\) | =\\(36+30+18\\) | = **84** |\n", + "|---|---|---|---|\n", + "| \\(c_{22}\\) | =\\(4Β·8+5Β·5+6Β·2\\) | =\\(32+25+12\\) | = **69** |\n", + "| \\(c_{23}\\) | =\\(4Β·7+5Β·4+6Β·1\\) | =\\(28+20+6\\) | = **54** |\n", + "\n", + "| \\(c_{31}\\) | =\\(7Β·9+8Β·6+9Β·3\\) | =\\(63+48+27\\) | = **138** |\n", + "|---|---|---|---|\n", + "| \\(c_{32}\\) | =\\(7Β·8+8Β·5+9Β·2\\) | =\\(56+40+18\\) | = **114** |\n", + "| \\(c_{33}\\) | =\\(7Β·7+8Β·4+9Β·1\\) | =\\(49+32+9\\) | = **90** |\n", + "\n", + "Hence \n", + "\n", + "\\[\n", + "\\boxed{C = A B = \n", + "\\begin{bmatrix}\n", + "30 & 24 & 18\\\\[2pt]\n", + "84 & 69 & 54\\\\[2pt]\n", + "138&114& 90\n", + "\\end{bmatrix}}\n", + "\\]\n", + "\n", + "---\n", + "\n", + "**2. Eigenvalues of \\(C\\)** \n", + "\n", + "The eigenvalues \\(\\lambda\\) satisfy the characteristic equation \n", + "\n", + "\\[\n", + "\\det(C-\\lambda I)=0 .\n", + "\\]\n", + "\n", + "---\n", + "\n", + "### 2.1 Characteristic polynomial\n", + "\n", + "\\[\n", + "C-\\lambda I=\n", + "\\begin{bmatrix}\n", + "30-\\lambda & 24 & 18\\\\\n", + "84 & 69-\\lambda & 54\\\\\n", + "138&114& 90-\\lambda\n", + "\\end{bmatrix}\n", + "\\]\n", + "\n", + "Computing the determinant (expansion or using a CAS) gives \n", + "\n", + "\\[\n", + "\\det(C-\\lambda I)=\\lambda^3-189\\lambda^2+324\\lambda .\n", + "\\]\n", + "\n", + "Factorising:\n", + "\n", + "\\[\n", + "\\det(C-\\lambda I)=\\lambda\\bigl(\\lambda^2-189\\lambda+324\\bigr).\n", + "\\]\n", + "\n", + "---\n", + "\n", + "### 2.2 Solving for \\(\\lambda\\)\n", + "\n", + "* One root is immediately \\(\\boxed{\\lambda_1 = 0}\\) (the matrix is singular; indeed \\(\\text{rank}(C)=2\\)). \n", + "\n", + "* The remaining roots come from the quadratic \n", + "\n", + "\\[\n", + "\\lambda^2-189\\lambda+324=0.\n", + "\\]\n", + "\n", + "Using the quadratic formula \n", + "\n", + "\\[\n", + "\\lambda_{2,3}= \\frac{189\\pm\\sqrt{189^2-4\\cdot324}}{2}.\n", + "\\]\n", + "\n", + "Calculate the discriminant:\n", + "\n", + "\\[\n", + "\\begin{aligned}\n", + "189^2-4\\cdot324 &= 35721-1296\\\\\n", + " &= 34425\\\\\n", + " &= 45^2\\cdot 17.\n", + "\\end{aligned}\n", + "\\]\n", + "\n", + "Thus \n", + "\n", + "\\[\n", + "\\sqrt{34425}=45\\sqrt{17}.\n", + "\\]\n", + "\n", + "Hence \n", + "\n", + "\\[\n", + "\\boxed{\\displaystyle\n", + "\\lambda_{2}= \\frac{189-45\\sqrt{17}}{2}},\\qquad\n", + "\\boxed{\\displaystyle\n", + "\\lambda_{3}= \\frac{189+45\\sqrt{17}}{2}}.\n", + "\\]\n", + "\n", + "---\n", + "\n", + "### 2.3 Numerical check\n", + "\n", + "\\[\n", + "\\begin{aligned}\n", + "\\lambda_{2}&\\approx \\frac{189-45\\cdot4.1231}{2}\n", + " \\approx \\frac{189-185.54}{2}\n", + " \\approx 1.730\\;,\\\\[4pt]\n", + "\\lambda_{3}&\\approx \\frac{189+185.54}{2}\n", + " \\approx \\frac{374.54}{2}\n", + " \\approx 187.27\\;,\\\\[4pt]\n", + "\\lambda_{1}&=0.\n", + "\\end{aligned}\n", + "\\]\n", + "\n", + "---\n", + "\n", + "### 2.4 Consistency checks \n", + "\n", + "* **Trace:** \\(\\operatorname{tr}(C)=30+69+90=189\\). \n", + " Sum of eigenvalues \\(=0+\\lambda_{2}+\\lambda_{3}=0+189=189\\) – matches.\n", + "\n", + "* **Determinant:** \\(\\det(C)=0\\) (because one eigenvalue is zero). Direct computation also yields \\(0\\).\n", + "\n", + "* **Rank:** Since exactly one eigenvalue is zero, \\(\\operatorname{rank}(C)=2\\), which aligns with the row‑dependence \\((\\text{row}_3=2\\,\\text{row}_2-\\text{row}_1)\\).\n", + "\n", + "---\n", + "\n", + "## Final answer\n", + "\n", + "\\[\n", + "\\boxed{\n", + "C=\n", + "\\begin{bmatrix}\n", + "30 & 24 & 18\\\\\n", + "84 & 69 & 54\\\\\n", + "138&114& 90\n", + "\\end{bmatrix}}\n", + "\\]\n", + "\n", + "Eigenvalues of \\(C\\):\n", + "\n", + "\\[\n", + "\\boxed{\n", + "\\lambda_1 = 0,\\qquad\n", + "\\lambda_2 = \\frac{189-45\\sqrt{17}}{2}\\;\\approx\\;1.73012,\\qquad\n", + "\\lambda_3 = \\frac{189+45\\sqrt{17}}{2}\\;\\approx\\;187.26988.\n", + "}\n", + "\\]\n", + "\n", + "All intermediate stepsβ€”row‑column products, formation of the characteristic polynomial, factorisation, and the quadratic solutionβ€”have been shown, and the results have been verified by trace, determinant, and rank checks.\n", + "\n", + "🏁 Demo completed! Total messages: 12\n" + ] + } + ], + "source": [ + "# Define the code interpreter tool\n", + "code_interpreter_tool = {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"python\",\n", + " \"description\": \"Execute Python code and return the result\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"code\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"Python code to execute\"\n", + " }\n", + " },\n", + " \"required\": [\"code\"]\n", + " }\n", + " }\n", + "}\n", + "\n", + "# Mathematical problem for the model to solve\n", + "math_query = \"\"\"\n", + "Calculate the following complex mathematical expression and show your work:\n", + "\n", + "1. Compute the matrix multiplication of two 3x3 matrices:\n", + " A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", + " B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]\n", + "2. Find the eigenvalues of the resulting matrix\n", + "\n", + "Please show all intermediate steps and verify your calculations.\n", + "\"\"\"\n", + "\n", + "# Reset namespace for fresh start\n", + "reset_persistent_namespace()\n", + "\n", + "# Initial message\n", + "messages = [{\"role\": \"user\", \"content\": math_query}]\n", + "\n", + "print(\"πŸš€ Starting GPT-OSS-120B mathematical calculation demo...\")\n", + "print(\"🎯 Problem: Matrix multiplication and eigenvalue calculation\")\n", + "print(\"πŸ”§ Using persistent namespace to maintain variables across tool calls\")\n", + "\n", + "# Handle the complete conversation\n", + "final_messages = handle_tool_calls(messages, [code_interpreter_tool], max_iterations=10)\n", + "\n", + "print(f\"\\n🏁 Demo completed! Total messages: {len(final_messages)}\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "## Additional Examples\n", + "\n", + "Here are some other mathematical problems you can try:\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}