OpenAI API error: "AttributeError: module 'openai' has no attribute 'Embedding'" - python

I was running a python script with the openai library. Whenever I run this function on my local machine it throws the following error
def gpt3_embedding(content, engine='text-embedding-ada-002'):
#delay_print('Making a vector')
content = content.encode(encoding='ASCII',errors='ignore').decode()
response = openai.Embedding.create(input=content,model=engine)
vector = response['data'][0]['embedding'] # this is a normal list
#delay_print('Vector returned')
return vector
AttributeError: module 'openai' has no attribute 'Embedding
NB : I am using the latest openai package and python 3.11.1
If all goes well, the error shouldnt appear at all.

I tested your code with:
Python 3.11.1 and OpenAI Python library 0.25.0
Python 3.11.1 and OpenAI Python library 0.26.3 (latest version)
In both cases I ran test.py and the OpenAI API returned the following completion (everything worked as expected):
[-0.01456643920391798, -0.00019150535808876157, 0.0035678150597959757,
-0.002183361677452922, -0.0118199922144413, 0.005178465507924557, -0.02064969204366207, -0.011248884722590446, -0.006718529388308525, -0.0322900116443634, 0.01849360205233097, 0.01343705877661705, -0.016196340322494507, -0.006872536148875952, 0.004013792145997286, -0.005172048695385456, 0.03131463751196861, -0.0071099624037742615, -0.005255468655377626, -0.006561314687132835, 0.014502270147204399, -0.004713237751275301, -0.005095045082271099, 0.012506603263318539, -0.0344204306602478, -0.020662525668740273, 0.008669277653098106, -0.02086786739528179, 0.009317387826740742, -0.009156964719295502, 0.01845510117...
test.py
import openai
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'
def gpt3_embedding(content, engine='text-embedding-ada-002'):
#delay_print('Making a vector')
content = content.encode(encoding='ASCII',errors='ignore').decode()
response = openai.Embedding.create(input=content,model=engine)
vector = response['data'][0]['embedding'] # this is a normal list
#delay_print('Vector returned')
return vector
print(gpt3_embedding('Say this is a test'))

Related

Use Data Subscription through python in TDengine

I'm trying data subscription feature of TDengine.
I tested its Python demo.
from taos.tmq import TaosConsumer
# Syntax: `consumer = TaosConsumer(*topics, **args)`
#
# Example:
consumer = TaosConsumer('topic1', 'topic2', td_connect_ip = "127.0.0.1", group_id = "local")
...
When executing the script, there is an error information:
ImportError: cannot import name 'TaosConsumer'
Did I miss some steps?
I think you need to update the version of taospy on your system - taospy is the TDengine connector for Python.
Try running pip install -U taospy to update it and then do your test again.
Make sure you're running Python 3.7 or later.

How to get DDE server to work in python 3?

In 2015 I have posted a question on SO how to Create DDE server in python and send data continously. The answer and code posted by JayleoPlayGround to that question back then worked flawlessly in python 2.7 and I have used it until recently.
As Python 2 is no longer actively supported from January 2020, I want to move my code to python 3. I have installed pywin32 (version 227) using pip on python 3.7.6 and tried to use the same code as before:
# coded by JayleoPlayGround
# use Portable Python 2.7.5.1 + pywin32-214
import time
import win32ui, dde
from pywin.mfc import object
class DDETopic(object.Object):
def __init__(self, topicName):
self.topic = dde.CreateTopic(topicName)
object.Object.__init__(self, self.topic)
self.items = {}
def setData(self, itemName, value):
try:
self.items[itemName].SetData( str(value) )
except KeyError:
if itemName not in self.items:
self.items[itemName] = dde.CreateStringItem(itemName)
self.topic.AddItem( self.items[itemName] )
self.items[itemName].SetData( str(value) )
ddeServer = dde.CreateServer()
ddeServer.Create('Orbitron')
ddeTopic = DDETopic('Tracking')
ddeServer.AddTopic(ddeTopic)
while True:
yourData = time.ctime() + ' UP0 DN145000001 UMusb DMfm AZ040 EL005 SNNO SATELLITE'
ddeTopic.setData('Tracking', yourData)
win32ui.PumpWaitingMessages(0, -1)
time.sleep(0.1)
When running the above code in python 3.7.6 and using pywin32 (version 227), the external DDE client application that I interface with is able to connect to the DDE server, but the data string is not received correctly. As described before, if I am using Python 2.7 with pywin32 (version 214) this works fine however.
As there are no error messages shown I am lost what the problem is under python 3. I tried all available pywin32 versions for this python version (222 to 227) without success. Any ideas on how to get this to work would be much appreciated.

Use reticulate to call Python script and send email

I use Windows Task Scheduler to run an R Script several times a day. The script transforms some new data and adds it to an existing data file.
I want to use reticulate to call a Python script that will send me an email listing how many rows of data were added, and if any errors occurred. This works correctly when I run it line by line from within RStudio. The problem is that it doesn't work when the script runs on schedule. I get the following errors:
Error in py_run_file_impl(file, local, convert) :
Unable to open file 'setup_smtp.py' (does it exist?)
Error in py_get_attr_impl(x, name, silent) :
AttributeError: module '__main__' has no attribute 'message'
Calls: paste0 ... py_get_attr_or_item -> py_get_attr -> py_get_attr_impl
Execution halted
This github answer https://github.com/rstudio/reticulate/issues/232) makes it sound like reticulate can only be used within RStudio - at least for what I'm trying to do. Does anyone have suggestions?
Sample R script:
library(tidyverse)
library(reticulate)
library(lubridate)
n_rows <- 10
time_raw <- now()
result <- paste0("\nAdded ", n_rows,
" rows to data file at ", time_raw, ".")
try(source_python("setup_smtp.py"))
message_final <- paste0(py$message, result)
try(smtpObj$sendmail(my_email, my_email, message_final))
try(smtpObj$quit())
The Python script ("setup_smtp.py") is like this:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Call from reticulate to log in to email
"""
import smtplib
my_email = '...'
my_password = '...'
smtpObj = smtplib.SMTP('smtp.office365.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(my_email, my_password)
message = """From: My Name <email address>
To: My Name <email address>
Subject: Test successful!
"""
This execution problem
This works correctly when I run it line by line from within RStudio. The problem is that it doesn't work when the script runs on schedule
can stem from multiple reasons:
You have multiple Python versions where smtplib is installed on one version (e.g., Python 2.7 or Python 3.6) and not the other. Check which Python is being used at command line, Rscript -e "print(Sys.which("python"))" and RStudio, Sys.which("python"). Explicitly define which Python.exe to run with reticulate's use_python("/path/to/python").
You have multiple R versions where Rscript uses a different version than RStudio. Check R.home() variable in both: Rscript -e "print(R.home())" and call R.home() in RStudio. Explicitly call the required Rscript in appropriate R version bin folder: /path/to/R #.#/bin/Rscript "/path/to/code.R".
You have multiple reticulate packages installed on same R version, residing in different library locations, each calling a different Python version. Check with the matrix: installed.package(), locating the reticulate row. Explicitly call library(reticulate, lib.loc="/path/to/specific/library").

NameError: name 'AnsibleModule' is not defined in PyCharm

I am having a python script along with ansible modules integrated. While executing in PyCharm, getting AnsibleModule not defined and it is not recognizing any ansible keywords. Any idea? Do I need to install any additional plugins for PyCharm to execute ansible based Python scripts? Here is my code
def main():
module = AnsibleModule(
argument_spec = dict(
hostvars = dict(required=True, type='dict'),
topology = dict(required=True, type='list'),
my_hostname = dict(required=True)
)
)
try:
hostvars = module.params['hostvars']
topology = module.params['topology']
my_hostname = module.params['my_hostname']
facts = get_facts(hostvars, topology, my_hostname)
module.exit_json(changed=False, ansible_facts=facts)
except Exception as error:
module.fail_json(msg=str(error))
Thanks,
Sridhar A
You have to set up your project interpreter in pycharm. IIRC, this may be a feature only available in pycharm pro. You should point the interpreter at your virtualenv and that will get you up and moving.

AttributeError: 'DocsClient' object has no attribute 'GetDocumentListFeed'

I'm currently trying to build a Script that interacts with Google's API's, but I keep getting an Attribute error:
Traceback (most recent call last):
File "service_catalog_automation.py", line 18, in <module>
feed = client.GetDocumentListFeed()
AttributeError: 'DocsClient' object has no attribute 'GetDocumentListFeed'
This is the code I'm trying to use
import gdata.gauth
import gdata.docs.client
import sys
def sys_print(text):
sys.stdout.write(str(text))
sys.stdout.flush()
CONSUMER_KEY = 'domain.com'
CONSUMER_SECRET = 'abcde1234'
requestor_id = 'myuser#domain.com'
client = gdata.docs.client.DocsClient(source='my-script-v1')
client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
CONSUMER_KEY, CONSUMER_SECRET, requestor_id)
# Retrieve user's list of Google Docs
feed = client.GetDocumentListFeed()
for entry in feed.entry:
sys_print(entry.title.text)
sys_print('\n')
I've pulled client.getDocumentListFeed() portion of code from their sample code here and have even tried a bare minimum approach using their sample code under the 2LeggedOAuth section here. (I also have tried GetDocList() from that example with the same error)
I have downloaded Google's gdata-python-client to a linux vm's home directory and installed it by running python setup.py install and ran the test python all_tests.py with no errors.
Any help would be greatly apperciated
In the first example, they're assigning their client object as the return of gdata.docs.service.DocsService().
The second example also returns the client object as a DocsService type:
client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
This would seem to imply that gd_client is of type DocsService, not DocsClient

Categories

Resources