Generate Python Functions with AI and Runtime Validation
Job to be done: Generate Python functions with runtime validation using AI
🇳🇬 Ways to use this in Nigeria
Ideas to get you started, adapt to your situation.
- 9-5 employee
As a data analyst, generate Python functions to transform raw sales data from various departmental spreadsheets into a standardized format for monthly reports, with AI validation ensuring data types and column names are consistent.
- Entrepreneur
For your e-commerce platform, use AI to create functions that extract product information from vendor APIs, ensuring data like price, stock, and description is correctly formatted before updating your inventory.
- Student
For your final year project, generate Python functions to parse sensor readings or research data from various files, ensuring the output DataFrame always matches your required schema for analysis.
What you’ll get
You will learn how to write Python functions by describing their purpose in plain English, and have an AI agent generate the code for you. This approach uses tests written before the code to ensure the AI-generated function works correctly, making it more reliable.
Tools you need
- Strands Labs (free): A framework that allows AI agents to generate and validate Python code based on natural language descriptions.
- Amazon Bedrock (paid): A service that provides access to AI models which the Strands Labs framework uses to generate your Python functions.
Steps
-
Set up your Python environment: Ensure you have Python installed on your system. You will also need to install the
strands-ai-functionslibrary. The author does not specify the exact installation command, but a common way to install Python packages is using pip:pip install strands-ai-functionsYou should see output indicating the package has been successfully installed.
-
Configure Amazon Bedrock: You need to set up access to Amazon Bedrock. This typically involves creating an AWS account and configuring your credentials so that the
strands-ai-functionslibrary can communicate with Bedrock. The exact steps for credential configuration are not provided by the author but usually involve setting environment variables or using AWS configuration files.You should have your AWS credentials configured, allowing programmatic access to AWS services.
-
Write your Python function description: Define your function using Python’s type hints and a docstring that clearly explains what the function should do, its parameters, and what it should return. The function body can be left empty.
The author provides an example for importing invoice data:
from pandas import DataFrame, api def check_invoice_dataframe(df: DataFrame): """Post-condition: validate DataFrame structure.""" assert {'product_name', 'quantity', 'price', 'purchase_date'}.issubset(df.columns) assert api.types.is_integer_dtype(df['quantity']), "quantity must be an integer" assert api.types.is_float_dtype(df['price']), "price must be a float" assert api.types.is_datetime64_any_dtype(df['purchase_date']), "purchase_date must be a datetime64" -
Decorate your function with
@ai_function: Use the@ai_functiondecorator from theai_functionslibrary. Specify thecode_execution_modeand anycode_executor_additional_importsneeded. Crucially, include your validation function (likecheck_invoice_dataframe) in thepost_conditionsargument.Here’s how the example function is decorated:
from ai_functions import ai_function @ai_function( code_execution_mode="local", code_executor_additional_imports=["pandas.*", "sqlite3", "json"], post_conditions=[check_invoice_dataframe], ) def import_invoice(path: str) -> DataFrame: """The file `{path}` contains purchase logs. Extract them in a DataFrame with columns: - product_name (str) - quantity (int) - price (float) - purchase_date (datetime) """ # The function body is empty, the AI will generate it. passAfter running this, you should see the Python code for
import_invoicegenerated by the AI within thestrands-ai-functionsframework. -
Call your AI-generated function: Now you can call your function as you normally would. The framework will use the AI to generate the implementation based on your docstring and then run your post-condition checks.
For example, to load a JSON file:
df = import_invoice('data/invoice.json')If the generated code for
import_invoicesuccessfully parses the JSON file and the resulting DataFrame meets the criteria defined incheck_invoice_dataframe, the function call will complete successfully. If it fails the post-condition, the framework will attempt to regenerate the code.
Original source
This workflow is based on a blog post by vishalcloud on DEV Community, explaining how to use AI Functions within the Strands Labs framework to generate Python code with built-in validation. The post highlights a novel approach to AI-assisted development where tests guide code generation.
Notes & variations
- Free tier alternative: Amazon Bedrock is a paid service. For a free alternative for AI model interaction, you might explore services like Groq or use local LLM models via tools like Ollama or LM Studio, though integrating them with Strands Labs might require custom code.
- Common mistake: Relying solely on the docstring without clear type hints or specific post-conditions can lead the AI to generate incorrect or incomplete code. Be as precise as possible in your specifications.
- Tip for better results: For complex functions, break down the requirements into smaller, more manageable functions. Define clear post-conditions for each part to ensure the AI generates accurate and robust code.