Connect chatGPT with Azure Function
Assuming you have VSCode and Python running. Also active Azure subscription.
Create a Default Boilerplate function
1. Install Azure Functions Core Tools.
2. Install Azure Function Extension and do the login
3. Go to Azure extension and under Resources > Function App Right click to create a new azure function> give a name like "vinGPTAPI" > choose folder >
choose httptrigger and give a name like "triggerGPT", "Function" access.
only 2 files, init.py and requirement.txt are important
5. Now deploy the function in azure. Click deploy in workspace
6. Now expand your function as shown and right click to copy execution url.
7. Paste it into browser and hit enter to see results.
INJECT CHATGPT code
Your default azure function is working properly. Now we will inject the chatGPT API code
only 2 files, init.py and requirement.txt are important and we will edit both.
1. In init.py add
import openai
it will give error.
2. so add openai in requirement.txt
azure-functions
openai
3 use this code
import logging
import openai
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
#get params from http requesrt
prompt = req.params.get('prompt')
if not prompt:
try:
req_body = req.get_json()
except ValueError:
pass
else:
prompt = req_body.get('prompt')
if prompt:
secret_key = 'sk-2s1QbkZp4qgPsssdcsHxkgcOsyBT3BlbkFJBQp85bgeYsi6JxxFItVP'
openai.api_key = secret_key
# call caht GPT API
response = openai.Completion.create(
model='text-davinci-003',
prompt=prompt,
temperature=0.9,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
#format the response
answer = response['choices'][0]['text']
return func.HttpResponse(f"Your answer, {answer}. ")
else:
return func.HttpResponse(
"This HTTP triggered function executed successfully.
Pass a name in the query string or in the request body for a personalized response.",
status_code=200
)
4. Deploy the code again
5. use url and pass the prompt = "any question for gpt" as parameter
-
5. use url and pass the prompt = "any question for gpt" as parameter
-
Written By
Vinod Kotiya
Comments