我正在尝试将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
通过这些修改,你的代码将会正常工作