在Google云函数中创建一个连接到OpenAI的webhook

我正在尝试将OpenAI连接到Google Dialogflow CX,并使用Google云函数编写我的webhook。我研究了一些方法并编写了代码,但每次部署时都失败了。是因为云函数无法实现这一点,因为我需要从Dialogflow CX获取用户查询吗?还是我的代码中缺少了什么?

我的云函数代码:入口点是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 = "\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函数中有一个错误。你使用了requests库来向OpenAI完成端点发送POST请求,但OpenAI API要求你使用Python的openai库。

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

通过这些修改,你的代码将会正常工作

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注