I am just trying some simple functions in Python with OpenAI APIs but running into an error:
I have a valid API secret key which I am using.
Code:
>>> import os
>>> import openai
>>> openai.api_key = os.getenv("I have placed the key here")
>>> response = openai.Completion.create(model="text-davinci-003", prompt="Say this is a test", temperature=0, max_tokens=7)
Option 1: OpenAI API not as environmental variable
Change this...
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')
...to this.
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'
Option 2: OpenAI API as an environmental variable (recommended)
Change this...
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')
...to this...
openai.api_key = os.getenv('OPENAI_API_KEY')
How to set OpenAI API as an environment variable?
STEP 1: Open System properties and select Advanced system settings
STEP 2: Select Environment Variables
STEP 3: Select New
STEP 4: Add your name/key value pair
Variable name: OPENAI_API_KEY
Variable value: sk-xxxxxxxxxxxxxxxxxxxx
STEP 5: Restart your computer
Related
I'm trying to make a file within visual studio code that holds my API key and secret key. so when I do future codes I can just import that file into my code without having to write my API keys every time.
I've tried this
api key = 'cewhjhbdhbd'
secret key = 'jhewbduywevb'
tried to save it.. it saved in documents and when I tried to import it nothing happened.. where am I going wrong?
I am a beginner at coding so sorry if this is obvious.
You can use environment variables for this.
import os
# Set environment variables
os.environ['API_USER'] = 'username'
os.environ['API_PASSWORD'] = 'secret'
# Get environment variables
USER = os.getenv('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')
You can then import this file or use the above block of code in your files.
Use an environment file like .env to store your API keys. In a format like
ENVIRONMENT='DEVELOPMENT'
API_KEY='yourapikeygoeshere'
DEBUG=True
DB_NAME=''
DB_USER=''
DB_PASSWORD=''
DB_HOST='localhost'
DB_PORT='5432'
Then you can use packages like dotenv to access them.
from dotenv import load_dotenv
from pathlib import Path
dotenv_path = Path('path/to/.env')
load_dotenv(dotenv_path=dotenv_path)
API_KEY = os.getenv('API_KEY')
Getting error "Please set the default workspace with MLClient". How do I set the default workspace with MLClient? Trying to use data asset
https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-register-data-assets?tabs=Python-SDK
from azure.ai.ml.entities import Data
from azure.ai.ml.constants import AssetTypes
from azure.ai.ml import MLClient
#Enter details of your AzureML workspace
subscription_id = "<SUBSCRIPTION_ID>"
resource_group = "<RESOURCE_GROUP>"
workspace = "<AZUREML_WORKSPACE_NAME>"
ml_client = MLClient(subscription_id, resource_group, workspace)
data_location='path'
my_data = Data(
path=data_loacation,
type=AssetTypes.URI_FOLDER,
description="Data",
name="Data_test")
ml_client.data.create_or_update(my_data)
Getting error "Please set the default workspace with MLClient". How do I set the default workspace with MLClient?
Make sure you have installed Python SDK azure-ai-ml v2(preview) using pip install --pre azure-ai-ml
You can try following code snippets taken from workspace.ipynb to set the default workspace with MLClient:
Import required libraries:
from azure.ai.ml import MLClient
from azure.ai.ml.entities import Workspace
from azure.identity import DefaultAzureCredential
ml_client = MLClient(DefaultAzureCredential(), subscription_id, resource_group)
Creating a unique workspace name with current datetime to avoid conflicts:
import datetime
basic_workspace_name = "mlw-basic-prod-" + datetime.datetime.now().strftime(
"%Y%m%d%H%M"
)
ws_basic = Workspace(
name=basic_workspace_name,
location="eastus",
display_name="Basic workspace-example",
description="This example shows how to create a basic workspace",
hbi_workspace=False,
tags=dict(purpose="demo"),
)
ml_client.workspaces.begin_create(ws_basic)
Get a list of workspaces in a resource group:
for ws in my_ml_client.workspaces.list():
print(ws.name, ":", ws.location, ":", ws.description)
Load a specific workspace using parameters:
ws = MLClient(DefaultAzureCredential(), subscription_id='<SUBSCRIPTION_ID>', resource_group_name='<RESOURCE_GROUP>', workspace_name='<AML_WORKSPACE_NAME>')
I recommend to replace <SUBSCRIPTION_ID>, <RESOURCE_GROUP> and <AZUREML_WORKSPACE_NAME> with actual values.
If you do that, the MLClient constructor will set the workspace accordingly.
Abstract
I'm trying to test SageMaker Debugger examples in 'local mode' from amazon-sagemaker-examples. I'm trying to see the same debugging result in 'local mode' with AWS SageMaker Notebook instance.
What i've done
I put a few lines in one of the examples to use it in 'local mode' referenced from amazon-sagemaker-local-mode-example. The example is tf-mnist-builtin-rule.ipynb.
Commented line is original code in the example
import subprocess
# import boto3
from sagemaker.local import LocalSession
from sagemaker.tensorflow import TensorFlow
instance_type = 'local'
try:
if subprocess.call("nvidia-smi") == 0:
instance_type = "local_gpu"
except:
pass
session = LocalSession()
session.config = {'local': {'local_code': True}}
# session = boto3.session.Session()
# region = session.region_name
role = 'arn:aws:iam::111111111111:role/service-role/AmazonSageMaker-ExecutionRole-20200101T000001'
estimator = TensorFlow(
# role=sagemaker.get_execution_role(),
role=role,
instance_count=1,
# instance_type="ml.p3.8xlarge",
instance_type=instance_type,
# image_uri=f"763104351884.dkr.ecr.{region}.amazonaws.com/tensorflow-training:2.3.1-gpu-py37-cu110-ubuntu18.04",
framework_version='2.4.1',
py_version="py37",
max_run=3600,
source_dir="./src",
entry_point="tf-resnet50-cifar10.py",
# Debugger Parameters
rules=built_in_rules,
sagemaker_session=session,
)
Problem:
I can't see debugging report in realtime unlike AWS SageMaker Notebook instance.
The example said wait=false option (see the figure) makes notebook proceed though it is still running but not working in 'local mode'.
Question:
Any idea make wait=False option working in 'local mode'?
Thanks for reading.
I'm currently working on an academic project in my university and im trying to access IEX Cloud API (iexfinance) for financial data extraction using python but i keep running into an authentication error.
When i checked the documentation of the package it recommends to set Secret Authentication Key as an environmental variable using 'IEX_TOKEN' to authenticate my request which i dont know how to do.
Also, i should note that i'm very new to the world of programming so thank you in advance for any assistance.
Here's a snippet of the script i use:
tickerSymbol = input("Ticker Symbol: ")
companyInfo = Stock(tickerSymbol)
stockPrice = companyInfo.get_price()
start = datetime(sy,sm,sd)
end = datetime(ey, em,ed)
historicalPrices = get_historical_intraday(tickerSymbol, start, end)
stockHistoricals = pd.DataFrame(historicalPrices).T
Assuming you know the secret authentication key. Try:
#import os module in first line of your code
import os
#set the env vairable in 2nd line
os.environ['IEX_TOKEN'] = 'TheSecretAuthenticationKey'
#other imports
...
...
...
...
#remaining code
I'm using the python sdk for speaker recognition using Microsoft cognitive service [I'm working in the Identification Folder]; When I run the CreateProfile.py file I'm trying give a profile a user-name. So for example, I would run my main.py file and then I would try to pass the locale and name.
import sys
sys.path.append('./Identification')
from CreateProfile import create_profile
name="Jane Doe"
subscriptionKey = "<my subscription key>"
locale = "en-us"
create_profile(name, subscriptionKey, locale)
Once I run the get profile GetProfile.py I want it to output all the user's info including their user-name. But I get this returned in the terminal.
Profile Name = None
Profile ID = 93affed1-ceb2-4538-9e6b-f0bd22d123b0
Locale = en-us
Enrollments Speech Time = 0.0
Remaining Enrollment Time = 30.0
Created = 2017-10-07T02:03:51.956Z
Last Action = 2017-10-07T02:03:51.956Z
Enrollment Status = Enrolling
I've tried editing the IdentificationProfile.py by adding things like _PROFILE_NAME = 'identificationProfileName' in the class, I've added a change related to this in a lot of places but I still don't see the name returning when I run GetProfile.py
This is my IdentificationProfile.py
import IdentificationServiceHttpClientHelper
import sys
def get_profile(subscription_key, profile_id):
"""Get a speaker's profile with given profile ID
Arguments:
subscription_key -- the subscription key string
profile_id -- the profile ID of the profile to resets
"""
helper = IdentificationServiceHttpClientHelper.IdentificationServiceHttpClientHelper(
subscription_key)
profile = helper.get_profile(profile_id)
print('Profile Name = {0}\n Profile ID = {1}\nLocale = {2}\nEnrollments Speech Time = {3}\nRemaining Enrollment Time = {4}\nCreated = {5}\nLast Action = {6}\nEnrollment Status = {7}\nName\n'.format(
profile._profile_name,
profile._profile_id,
profile._locale,
profile._name,
profile._enrollment_speech_time,
profile._remaining_enrollment_time,
profile._created_date_time,
profile._last_action_date_time,
profile._enrollment_status))
if __name__ == "__main__":
if len(sys.argv) < 3:
print('Usage: python DeleteProfile.py <subscription_key> <profile_id> ')
print('\t<subscription_key> is the subscription key for the service')
print('\t<profile_id> the ID for a profile to delete from the sevice')
sys.exit('Error: Incorrect usage.')
get_profile(sys.argv[1], sys.argv[2])
You cannot give a name to a identification profile. The HTTP endpoint that the python SDK uses does not accept any parameters other than the locale for the voice.
You would have to map user names to identification profile IDs yourself. You can use a database for that, maybe an Azure MySQL db. Or if you're just testing things out, use an in-memory map (aka dictionary).