我正在致力於將 openai 連接到 google dialogflow cx,並且正在使用 google 雲端功能編寫我的 webhook。我進行了研究並提出了一個程式碼,但每次它都沒有部署。這對雲端功能來說是不可能的嗎,因為我需要從dialogflow cx取得使用者查詢?或程式碼中缺少某些內容
我的雲端函數程式碼:entry_point是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' }] } })
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
透過這些修改,您的程式碼將可以正常運作
以上是建立 webhook 以連接到 Google 雲端功能中的 OpenAI的詳細內容。更多資訊請關注PHP中文網其他相關文章!