PHP前端开发

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

百变鹏仔 2周前 (01-18) #Python
文章标签 连接到
问题内容

我正在致力于将 openai 连接到 google dialogflow cx,并正在使用 google 云功能编写我的 webhook。我进行了研究并提出了一个代码,但每次它都没有部署。这对于云功能来说是不可能的吗,因为我需要从dialogflow cx获取用户查询?或者代码中缺少某些内容

我的云函数代码:entry_point是webhook

import openaiimport jsonimport requestsfrom google.cloud import secretmanager# Initialize the Secret Manager clientclient = secretmanager.SecretManagerServiceClient()# Store the conversation history if necessaryconvo = []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 Nonedef 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 = "".join(convo)    response = query_gpt(prompt)    result = response.get('choices')[0].get('text').strip('')    convo.append(result)        return json.dumps({        'fulfillment_response': {            'messages': [{                'text': {                    'text': [result],                    'redactedText': [result]                },                'responseType': 'HANDLER_PROMPT',                'source': 'VIRTUAL_AGENT'            }]        }    })

正确答案


query_gpt 函数中的代码有错误。您正在使用 requests 库向 openai 完成端点发出 post 请求,openai api 要求您使用 openai 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

通过这些修改,您的代码将可以正常工作