search
HomeBackend DevelopmentPython TutorialCreate a webhook to connect to OpenAI in Google Cloud Functions

创建 webhook 以连接到 Google 云功能中的 OpenAI

Question content

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'
            }]
        }
    })

Correct answer


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!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.