pythongoogle-cloud-functionsopenai-apidialogflow-cx

Creating a webhook to connect to OpenAI in Google cloud functions


I working on connecting OpenAI to Google Dialogflow CX and am writing my webhook with Google cloud functions. I researched and I came up with a code but each time it does not deploy. Is that this is not possible with Cloud functions as I would need to get a user query from dialogflow cx? or there is something 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'
            }]
        }
    })

Solution

  • You have an error in your code in the query_gpt function. You are using the requests library to make a POST request to the OpenAI completion endpoint, OpenAI API requires you to use the openai library for Python.

    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
    

    Through these modifications, your code will work