I try to run the python script below to make a request to the OpenAI API.
I installed the openai module in Python, but I get this error: Python Error (ModuleNotFoundError) - Method: module.exec: No module named 'openai'
What I'm doing wrong?
Thanks in advance.
Code:
B4X:
Private Sub Button3_Click
Py.ImportModule("openai")
Dim script As String = $"
openai.api_key = "YOUR_API_KEY"
prompt = f'What is the capital of Brazil??'
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=[{"role": "user", "content": prompt}]
)
result = response.choices[0].message.content.strip()
"$
Py.RunStatement(script).Print
End Sub
Logs:
B4X:
Server is listening on port: 65474
Python path: C:\Program Files\Anywhere Software\B4J\libraries\Python\python\python.exe
Call B4XPages.GetManager.LogEvents = True to enable logging B4XPages events.
connected
starting PyBridge v0.70
watchdog set to 30 seconds
Connecting to port: 65474
This will be printed by B4J process: 45
Python version: 3.12.8 (tags/v3.12.8:2dc476b, Dec 3 2024, 19:30:04) [MSC v.1942 64 bit (AMD64)]
30
The value of sum: 45
Error occurred on line: 109 (B4XMainPage)
(b4xmainpage._button3_click) - Python Error (ModuleNotFoundError) - Method: module.exec: No module named 'openai'
PyBridge disconnected
The 'import openai" line is in the original script (created by ChatGPT).
I changed after to "Py.ImportModule("openai")".
Both rises the same error message:
Python Error (ModuleNotFoundError) - Method: module.exec: No module named 'openai'
I imported the openai module again, using the link in IDE (before I installed it using the command prompt on Windows).
The error message could be related to correct Python environment, like @stevel05 say.
Now I get another error: (b4xmainpage._button3_click) - Python Error (SyntaxError) - Method: module.eval: invalid syntax (<string>, line 2)
Maybe the script is not correct.
I'll check again.
Private Sub Button3_Click
Py.ImportModule("openai")
Dim script As String = $"
openai.api_key = "YOUR_API_KEY"
prompt = f'What is the capital of Brazil??'
response = openai.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": prompt}
]
)
print(response.choices[0].message.content)"$
Py.RunNoArgsCode(script)
End Sub