{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "guidance_response_ = \"\"\"\n", " Guidance from super intelligent code bot:\n", " {guidance_response}\n", " Please generate Python functions that satisfies the prompt and follows the provided guidance, while adhering to these coding standards:\n", " - Use descriptive and meaningful names for variables, functions, and classes.\n", " - Follow the naming conventions: lowercase with underscores for functions and variables, CamelCase for classes.\n", " - Keep functions small and focused, doing one thing well.\n", " - Use 4 spaces for indentation, and avoid mixing spaces and tabs.\n", " - Limit line length to 79 characters for better readability.\n", " - Use docstrings to document functions, classes, and modules, describing their purpose, parameters, and return values.\n", " - Use comments sparingly, and prefer descriptive names and clear code structure over comments.\n", " - Handle exceptions appropriately and raise exceptions with clear error messages.\n", " - Use blank lines to separate logical sections of code, but avoid excessive blank lines.\n", " - Import modules in a specific order: standard library, third-party, and local imports, separated by blank lines.\n", " - Use consistent quotes (single or double) for strings throughout the codebase.\n", " - Follow the PEP 8 style guide for more detailed coding standards and best practices.\n", "\"\"\"\n", "\n", "_plan_prompt = \"Please design coding instructions for the following prompt and provide guidance for the coder to follow.\"\n", "_write_prompt = \"Please write a Python function that satisfies the prompt and follows the provided guidance.\"\n", "_review_prompt = \"Please review the following code and remove any unnecessary markdown or descriptions:\\n\\n{code}\\n\"\n", "_modify_prompt = \"\"\"\n", "Please generate updated code based on the previous code and the additional request. \n", " ### Previous code: \\n\\n{code}\\n\n", " ### Additional request: \\n\\n{additional_request}\\n\n", "\"\"\"\n", "_debug_prompt = \"\"\"\n", "please debug the code, fix the error and provide the correctly updated code to satisfy the prompt according to the guidance provided.\n", " ### code: \\n\\n {code}\\n , ran into the following \n", " ### error: \\n\\n {error}\\n\n", "\"\"\"\n", "\n", "coder_prompts = {\n", " \"system\": guidance_response_,\n", " \"plan_code\": _plan_prompt,\n", " \"write_code\": _write_prompt,\n", " \"review_code\": _review_prompt,\n", " \"modify_code\": _modify_prompt,\n", " \"debug_code\": _debug_prompt,\n", "}\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "from lionagi.libs import SysUtil, ParseUtil\n", "from typing import Any\n", "from pydantic import Field\n", "from lionagi.core import Session\n", "from lionagi.core.form.action_form import ActionForm\n", "\n", "import importlib\n", "import subprocess\n", "import sys\n", "from os import getenv\n", "from dotenv import load_dotenv\n", "from pathlib import Path\n", "E2B_key_scheme = \"E2B_API_KEY\"\n", "\n", "\n", "def extract_code_blocks(code):\n", " # Extract code blocks from the generated code\n", " code_blocks = []\n", " lines = code.split('\\n')\n", " inside_code_block = False\n", " current_block = []\n", "\n", " for line in lines:\n", " if line.startswith('```'):\n", " if inside_code_block:\n", " code_blocks.append('\\n'.join(current_block))\n", " current_block = []\n", " inside_code_block = False\n", " else:\n", " inside_code_block = True\n", " elif inside_code_block:\n", " current_block.append(line)\n", "\n", " if current_block:\n", " code_blocks.append('\\n'.join(current_block))\n", "\n", " return '\\n\\n'.join(code_blocks)\n", "\n", "def install_dependencies(required_libraries):\n", " missing_libraries = []\n", "\n", " for library in required_libraries:\n", " try:\n", " importlib.import_module(library)\n", " except ImportError:\n", " missing_libraries.append(library)\n", "\n", " if missing_libraries:\n", " for library in missing_libraries:\n", " print(f\"Installing {library}...\")\n", " try:\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", library])\n", " except subprocess.CalledProcessError as e:\n", " print(f\"Error occurred while installing {library}: {str(e)}\")\n", " print(\"Please check the error message and ensure you have the necessary permissions to install packages.\")\n", " print(\"You may need to run the script with administrative privileges or use a virtual environment.\")\n", " print(\"Installation completed.\")\n", "\n", "class Coder:\n", " \n", " def __init__(self, prompts=None, session=None, session_kwargs={}, required_libraries=None) -> None:\n", " self.prompts = prompts or coder_prompts\n", " self.session = Session(system=self.prompts['system'], **session_kwargs) if not session else session\n", " self.required_libraries = required_libraries or [\"lionagi\"]\n", " \n", " def _set_up_interpreter(self, interpreter_provider=\"e2b\",key_scheme=E2B_key_scheme):\n", " \n", " if interpreter_provider == \"e2b\":\n", " SysUtil.check_import(\"e2b_code_interpreter\")\n", " from e2b_code_interpreter import CodeInterpreter\n", "\n", " return CodeInterpreter(api_key=getenv(key_scheme))\n", " \n", " else:\n", " raise ValueError(\"Invalid interpreter provider\")\n", " \n", " \n", " async def _plan_code(self, context):\n", " plans = await self.session.chat(self.prompts[\"plan_code\"], context=context)\n", " return plans\n", "\n", " async def _write_code(self, context=None):\n", " code = await self.session.chat(self.prompts[\"write_code\"], context=context)\n", " return extract_code_blocks(code)\n", " \n", " async def _review_code(self, context=None):\n", " code = await self.session.chat(self.prompts[\"review_code\"], context=context)\n", " return code\n", " \n", " async def _modify_code(self, context=None):\n", " code = await self.session.chat(self.prompts[\"modify_code\"], context=context)\n", " return code\n", " \n", " async def _debug_code(self, context=None):\n", " code = await self.session.chat(self.prompts[\"debug_code\"], context=context)\n", " return code\n", " \n", " def _handle_execution_error(self, execution, required_libraries=None):\n", " if execution.error and execution.error.name == 'ModuleNotFoundError':\n", " install_dependencies(required_libraries)\n", " return \"try again\"\n", " elif execution.error:\n", " return execution.error\n", " \n", " def execute_codes(self, code, **kwargs):\n", " interpreter = self._set_up_interpreter()\n", " with interpreter as sandbox:\n", " execution = sandbox.notebook.exec_cell(code, **kwargs)\n", " error = self._handle_execution_error(execution, required_libraries=kwargs.get('required_libraries'))\n", " if error == \"try again\":\n", " execution = sandbox.notebook.exec_cell(code, **kwargs)\n", " return execution\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = Coder()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "codes_ = '''\n", "write a pure python function that takes a list of integers and returns the sum of all the integers in the list. write a couple tests as well\n", "'''" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plans = await a._plan_code(context=codes_)\n", "code = await a._write_code()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "execution = a.execute_codes(code)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "### Coding Instructions for the Prompt\n", "\n", "#### Task Description\n", "You are required to write a Python function that calculates the sum of all integers in a provided list. The function should only process lists containing integers and handle any potential errors gracefully.\n", "\n", "#### Function Specifications\n", "\n", "1. **Function Name**: `sum_of_integers`\n", "2. **Input Parameter**: `numbers` (a list of integers)\n", "3. **Return Value**: The function should return an integer representing the sum of all integers in the list.\n", "\n", "#### Requirements and Constraints\n", "\n", "- The function must handle and validate the input data:\n", " - Ensure that the input is a list.\n", " - Verify that all elements in the list are integers.\n", "- If the input validation fails, the function should raise a `ValueError` with an appropriate error message.\n", "- If the list is empty, the function should return 0.\n", "\n", "#### Testing\n", "\n", "Write at least two test cases using Python's `assert` statement to validate the function:\n", "1. Test with a normal list of integers.\n", "2. Test with an empty list to ensure it returns 0.\n", "\n", "### Guidance for the Coder\n", "\n", "1. **Function Design**:\n", " - Start by defining the function `sum_of_integers` with one parameter.\n", " - Inside the function, first check if the input is indeed a list and if all elements are integers, raising a `ValueError` if any check fails.\n", " - Use Python’s built-in `sum()` function to calculate the sum of the list.\n", "\n", "2. **Error Handling**:\n", " - Include appropriate error messages in `ValueError` to inform the user about the specific input issue.\n", "\n", "3. **Testing**:\n", " - After defining the function, write test cases below the function definition.\n", " - Use the `assert` keyword to validate function behavior against expected outcomes.\n", "\n", "4. **Code Style**:\n", " - Follow the PEP 8 style guide.\n", " - Use clear and descriptive variable names.\n", " - Maintain proper documentation and comments where necessary, especially docstrings for the function.\n", "\n", "5. **Execution**:\n", " - Ensure your script can be run to directly test the function when executed.\n", "\n", "By following these instructions and adhering to good coding practices, you should be able to create a robust and efficient function to solve the given task." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from IPython.display import Markdown\n", "\n", "Markdown(plans)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "def sum_of_integers(numbers):\n", " \"\"\"\n", " Calculate the sum of all integers in a list.\n", "\n", " Parameters:\n", " numbers (list): A list of integers.\n", "\n", " Returns:\n", " int: The sum of all integers in the list.\n", "\n", " Raises:\n", " ValueError: If the input is not a list or contains non-integer elements.\n", " \"\"\"\n", " if not isinstance(numbers, list):\n", " raise ValueError(\"Input must be a list of integers.\")\n", " \n", " if not all(isinstance(num, int) for num in numbers):\n", " raise ValueError(\"All elements in the list must be integers.\")\n", " \n", " return sum(numbers)\n", "\n", "# Tests\n", "assert sum_of_integers([1, 2, 3, 4, 5]) == 15, \"Test failed for input [1, 2, 3, 4, 5]\"\n", "assert sum_of_integers([]) == 0, \"Test failed for an empty list\"\n", "# Additional test: handling negative numbers\n", "assert sum_of_integers([-1, -2, -3, -4, -5]) == -15, \"Test failed for input [-1, -2, -3, -4, -5]\"\n", "# Additional test: handling mix of positive and negative numbers\n", "assert sum_of_integers([-1, 2, -3, 4, -5]) == -3, \"Test failed for mixed positive and negative numbers\"\n", "\n", "# This will print nothing if all tests pass\n", "print(\"All tests passed!\")\n" ] } ], "source": [ "print(code)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Execution(results=[], logs=Logs(stdout=['All tests passed!\\n'], stderr=[]), error=None)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "execution" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }