Python
Execute custom Python code within your AI workflows
Basic Usage
Python Code Runner blocks allow you to execute Python scripts within your Hunch canvas. This powerful feature enables you to process data, interact with external services, and create dynamic outputs.
Simple Example
Let’s start with a basic example. Assume we have a canvas with two input content blocks:
- A block titled “First Name”
- A block titled “Last Name”
We’ll create a Python Code Runner block that combines these inputs to greet the person.
This script will output: “Hello [First Name] [Last Name]!” where [First Name] and [Last Name] are replaced with the actual contents of those input blocks.
Using the hunch
Package
The hunch
package is a crucial part of working with Python Code Runner blocks. It provides several useful functions for interacting with your Hunch canvas.
Key Functions
-
hunch.output()
- Use this to send output from your script.
- Example:
hunch.output("This will be displayed in the output.")
-
hunch.block()
- Retrieves a specific block from your canvas.
- Example:
hunch.block(title="Block Title")
-
hunch.input()
- Loads all input data for the Code Runner block.
- Example:
input_data = hunch.input()
-
hunch.compiled_prompt()
- Gets the entire compiled prompt from upstream blocks.
- Example:
full_prompt = hunch.compiled_prompt()
Input Handling
Accessing Specific Blocks
To access the content of a specific block, use the hunch.block()
function:
Working with All Inputs
To work with all input blocks at once:
Output Handling
Text Output
Use hunch.output()
to send text output:
File Output
To output files, write them to the /output
directory:
Markdown Rendering
Output is rendered as Markdown. You can use Markdown syntax in your output:
Error Handling
Implement try-except blocks to handle potential errors:
Advanced Usage
Working with External Libraries
You can use many standard Python libraries and some additional libraries. Here’s an example using requests
:
Data Transformation
Python is excellent for data transformation. Here’s a simple example:
Best Practices
- Modular Code: Break your code into functions for better readability and reusability.
- Error Handling: Always include error handling to make your scripts more robust.
- Comments: Add comments to explain complex logic or non-obvious operations.
- Input Validation: Validate inputs to ensure your script can handle unexpected data.
Conclusion
Python Code Runner blocks offer a powerful way to extend the capabilities of your Hunch canvas. By combining Python’s versatility with Hunch’s AI-driven workflows, you can create sophisticated, dynamic, and intelligent applications.
Remember to explore the hunch
package documentation for more advanced features and always consider security and performance when writing your scripts.