Getting Started with RunPod's Serverless Python SDK
RunPod's serverless library enables you to create and deploy scalable functions without managing infrastructure. This tutorial will walk you through creating a simple serverless function that determines whether a number is even.
Creating a Basic Serverless Function
Let's start by building a function that checks if a given number is even.
Import the RunPod library
Create a new python file called is_even.py
.
Import the RunPod library:
import runpod
Define your function
Create a function that takes a job
argument:
def is_even(job):
job_input = job["input"]
the_number = job_input["number"]
if not isinstance(the_number, int):
return {"error": "Please provide an integer."}
return the_number % 2 == 0
This function:
- Extracts the input from the
job
dictionary - Checks if the input is an integer
- Returns an error message if it's not an integer
- Determines if the number is even and returns the result
Start the Serverless function
Wrap your function with runpod.serverless.start()
:
runpod.serverless.start({"handler": is_even})
This line initializes the serverless function with your specified handler.
Complete code example
Here's the full code for our serverless function:
import runpod
def is_even(job):
job_input = job["input"]
the_number = job_input["number"]
if not isinstance(the_number, int):
return {"error": "Please provide an integer."}
return the_number % 2 == 0
runpod.serverless.start({"handler": is_even})
Testing your Serverless Function
To test your function locally, use the following command:
python is_even.py --test_input '{"input": {"number": 2}}'
When you run the test, you'll see output similar to this:
--- Starting Serverless Worker | Version 1.6.2 ---
INFO | test_input set, using test_input as job input.
DEBUG | Retrieved local job: {'id': 'some-id', 'input': {'number': 2}}
INFO | some-id | Started.
DEBUG | some-id | Handler output: True
DEBUG | some-id | run_job return: {'output': True}
INFO | Job some-id completed successfully.
INFO | Job result: {'output': True}
INFO | Local testing complete, exiting.
This output indicates that:
- The serverless worker started successfully
- It received the test input
- The function processed the input and returned
True
(as 2 is even) - The job completed successfully
Conclusion
You've now created a basic serverless function using RunPod's Python SDK. This approach allows for efficient, scalable deployment of functions without the need to manage infrastructure.
To further explore RunPod's serverless capabilities, consider:
- Creating more complex functions
- Implementing error handling and input validation
- Exploring RunPod's documentation for advanced features and best practices
RunPod's serverless library provides a powerful tool for a wide range of applications, from simple utilities to complex data processing tasks.