使用Alexa Skill Kit SDK时如何导入Python第三方库(如numpy)?
import numpy Runtime Error in Alexa Skill Development Hey there, let's clear up the confusion here! While it might feel like this issue has nothing to do with the Alexa Skill Kit (ASK), the root cause is actually tied to where your skill code runs—AWS Lambda, which is the default backend execution environment for ASK skills. Lambda's base Python environment doesn't come pre-installed with numpy (or most third-party libraries), so trying to import it directly will throw a runtime error.
Here's a step-by-step fix that's more straightforward than uploading numpy source code:
Set up a local virtual environment to isolate your skill's dependencies
- Create a virtual environment:
python -m venv alexa-skill-env - Activate it:
- Windows:
alexa-skill-env\Scripts\activate - Mac/Linux:
source alexa-skill-env/bin/activate
- Windows:
- Install both
numpyand the ASK SDK:pip install numpy ask-sdk-core
- Create a virtual environment:
Package your code and dependencies together
- Navigate to the
site-packagesfolder inside your virtual environment (this is wherenumpyand other libraries are installed):- Windows:
alexa-skill-env\Lib\site-packages - Mac/Linux:
alexa-skill-env/lib/python3.x/site-packages(replace3.xwith your Python version)
- Windows:
- Copy all files and folders from
site-packagesinto the same directory as your skill's main code file (usuallylambda_function.py) - Select your skill code file + all the copied dependency files, then zip them up directly (don't put everything inside a nested folder—Lambda needs the files at the root of the ZIP)
- Navigate to the
Upload the ZIP to Lambda
- Open the AWS Lambda console and find the function linked to your Alexa skill
- Go to the "Code" tab, click "Upload from" > ".zip file"
- Upload your packaged ZIP, save the function, and test your skill again
The reason you found solutions mentioning uploading numpy source code is that Lambda needs access to the library files to run your code—packaging the installed version (not raw source) is just a more reliable way to do this. ASK handles the skill's voice interaction logic, but your custom code (including numpy usage) runs on Lambda, so the two are connected behind the scenes.
内容的提问来源于stack exchange,提问作者Quynh Vo

