Home >Backend Development >Python Tutorial >Create a webhook to connect to OpenAI in Google Cloud Functions
I am working on connecting openai to google dialogflow cx and am writing my webhook using google cloud functions. I did research and came up with a code, but every time it didn't deploy. Is this not possible with cloud functions since I need to get the user query from dialogflow cx? Or something is missing in the code
My cloud function code: entry_point is webhook
import openai import json import requests from google.cloud import secretmanager # Initialize the Secret Manager client client = secretmanager.SecretManagerServiceClient() # Store the conversation history if necessary convo = [] def get_secret(secret_name, project_id, version_id='latest'): """ Retrieve a secret from Google Cloud Secret Manager. """ resource_name = f"projects/{project_id}/secrets/{secret_name}/versions/{version_id}" try: # Access the secret version response = client.access_secret_version(request={"name": resource_name}) # Return the payload of the secret return response.payload.data.decode("UTF-8") except Exception as e: print(f"Error accessing secret '{secret_name}':", e) return None def query_gpt(prompt): """ Query the OpenAI completion endpoint with a prompt. """ body = { "model": "text-davinci-003", "prompt": prompt, "max_tokens": 200, "temperature": 0.9, "top_p": 1, "n": 1, "frequency_penalty": 0, "presence_penalty": 0.6 } header = {"Authorization": f"Bearer {get_secret('openai-api-key', 'my-project-id')}"} res = requests.post('https://api.openai.com/v1/completions', json=body, headers=header) return res.json() def webhook(request): """ HTTP Cloud Function entry point. """ if request.method != 'POST': return ('Only POST method is accepted', 405) request_json = request.get_json(silent=True) if not request_json or 'text' not in request_json: return ('Missing "text" in request', 400) query = request_json['text'] convo.append(f'User: {query}') convo.append("Addie:") prompt = "\n".join(convo) response = query_gpt(prompt) result = response.get('choices')[0].get('text').strip('\n') convo.append(result) return json.dumps({ 'fulfillment_response': { 'messages': [{ 'text': { 'text': [result], 'redactedText': [result] }, 'responseType': 'HANDLER_PROMPT', 'source': 'VIRTUAL_AGENT' }] } })
query_gpt
There is an error in the code in the function. You are using the requests
library to make post requests to the openai completion endpoint, the openai api requires you to use the openai
python library.
def query_gpt(prompt): openai.api_key = get_secret('openai-api-key', 'my-project-id') response = openai.Completion.create(model="text-davinci-003", prompt=prompt, max_tokens=200, temperature=0.9, top_p=1, n=1, frequency_penalty=0, presence_penalty=0.6) return response
With these modifications, your code will work properly
The above is the detailed content of Create a webhook to connect to OpenAI in Google Cloud Functions. For more information, please follow other related articles on the PHP Chinese website!