ホームページ  >  記事  >  バックエンド開発  >  Google Cloud Functions で OpenAI に接続する Webhook を作成する

Google Cloud Functions で OpenAI に接続する Webhook を作成する

王林
王林転載
2024-02-10 23:42:041095ブラウズ

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

#質問内容

openai を Google Dialogflow cx に接続することに取り組んでおり、Google Cloud 関数を使用して 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 完了エンドポイントにポスト リクエストを行っています。openai API では、openai Python を使用する必要があります。図書館。 リーリー

これらの変更により、コードは適切に動作します

以上がGoogle Cloud Functions で OpenAI に接続する Webhook を作成するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はstackoverflow.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。