{"id":13465451,"url":"https://github.com/Azure-Samples/openai-python-enterprise-logging","last_synced_at":"2025-03-25T16:32:01.308Z","repository":{"id":144908466,"uuid":"599685376","full_name":"Azure-Samples/openai-python-enterprise-logging","owner":"Azure-Samples","description":null,"archived":false,"fork":false,"pushed_at":"2024-04-22T09:02:48.000Z","size":16644,"stargazers_count":169,"open_issues_count":3,"forks_count":56,"subscribers_count":15,"default_branch":"main","last_synced_at":"2024-07-31T15:01:28.663Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"HCL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Azure-Samples.png","metadata":{"files":{"readme":"README.ja.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-09T17:03:36.000Z","updated_at":"2024-07-29T19:59:25.000Z","dependencies_parsed_at":"2023-07-20T09:15:45.278Z","dependency_job_id":"09f06617-27ba-426b-bbe7-aec2e23f7bb5","html_url":"https://github.com/Azure-Samples/openai-python-enterprise-logging","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fopenai-python-enterprise-logging","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fopenai-python-enterprise-logging/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fopenai-python-enterprise-logging/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fopenai-python-enterprise-logging/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Azure-Samples","download_url":"https://codeload.github.com/Azure-Samples/openai-python-enterprise-logging/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":222088560,"owners_count":16928977,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T15:00:30.115Z","updated_at":"2024-10-29T17:31:05.592Z","avatar_url":"https://github.com/Azure-Samples.png","language":"HCL","readme":"# エンタープライズ向けAzure OpenAIアプリ基盤\n\nエンタープライズ向けAzure OpenAIアプリ基盤の参照アーキテクチャのデプロイ方法の詳細を示すリポジトリ。\n\n## ソリューションの主な利点:\n*\t\u003cb\u003e責任あるAI利用のためのプロンプトと応答監視。\u003c/b\u003e  ログ情報には、ユーザーがモデルに送信しているテキストと、モデルから受信されているテキストが含まれます。これにより、モデルが企業環境内およびサービスの承認されたユースケース内で責任を持って使用されるようになります。\n*\t\u003cb\u003e利用制御とスロットリング制御により、\u003c/b\u003e さまざまなユーザグループに対してきめ細かなアクセス制御が可能になります。\n*\t\u003cb\u003e高可用性構成により、\u003c/b\u003e トラフィックが 1 つの Azure OpenAI サービスの制限を超えた場合でも、ユーザー要求が満たされるようにします。\n*\t\u003cb\u003e高セキュリティ\u003c/b\u003eを実現するために、最小特権の原則に従ってAzure Active DirectoryのRBACを活用します。\n\n[![video](assets/video.png)](https://clipchamp.com/watch/WX92A7nDyR4 'link')\n\n## リファレンスアーキテクチャ\n![img](/assets/EnterpriseAOAI-Architecture.png)\n\n## 機能\n\nこのプロジェクト フレームワークは、次の機能を提供します:\n\n* OpenAI 使用状況メトリックのエンタープライズログ:\n   * トークン利用\n   * モデル利用\n   * プロンプト入力\n   * ユーザー統計\n   * プロンプト応答\n* リージョンのフェールオーバーによるOpenAI サービスの高可用性\n* 最新のOpenAIライブラリとの統合\n  *  [OpenAI](https://github.com/openai/openai-python/) \n  *  [LangChain](https://python.langchain.com/en/latest/)\n  *  [Llama-index](https://gpt-index.readthedocs.io/en/latest/)\n\n## はじめ方\n\n### 前提条件\n- [Azure サブスクリプション](https://azure.microsoft.com/en-us/get-started/)\n- [Azure OpenAI 利用許可](https://aka.ms/oai/access) \n- \n### インストール\nアーティファクトのプロビジョニングは、まず、次に示すソリューションアーティファクトをプロビジョニングします:\n\n-\t[Azure OpenAI Cognitive Service]( https://azure.microsoft.com/en-us/products/cognitive-services/openai-service/)\n-\t[Azure API Management](https://azure.microsoft.com/services/api-management/)\n-\t[Azure Monitor](https://azure.microsoft.com/services/monitor/)\n-\t[Azure Application Gateway](https://azure.microsoft.com/services/application-gateway/)\n-\t[Azure Virtual Network](https://azure.microsoft.com/services/virtual-network/)\n\n### マネージドサービス\n-\t[Azure Key Vault](https://azure.microsoft.com/services/key-vault/)\n-\t[Azure Storage](https://azure.microsoft.com/services/storage/)\n-\t[Azure Active Directory](https://azure.microsoft.com/services/active-directory/)\n\n## 構成\n\n### Azure OpenAI\n- まずは、Azure OpenAIのリソースをプロビジョニングします。\u003cb\u003e現在のプライマリリージョンは米国東部であり\u003c/b\u003e新しいモデルと容量は他のリージョンよりも先にこの場所でプロビジョニングされることに注意してください。 [リソースのプロビジョニング](https://portal.azure.com/?microsoft_azure_marketplace_ItemHideKey=microsoft_openai_tip#create/Microsoft.CognitiveServicesOpenAI)\n\n- リソースがプロビジョニングされたら、選択したモデルを使用してDeploymentを作成します: [モデルのデプロイ](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#deploy-a-model)\n\n- モデルがデプロイされたら、OpenAI スタジオに遷移して、新しく作成したモデルをスタジオのプレイグラウンドでテストします。 [oai.azure.com/portal](oai.azure.com/portal)\n\n\n### API Management\n\n- Azure ポータルを使用してプロビジョニングできます :[リソースのプロビジョニング](https://learn.microsoft.com/en-us/azure/api-management/get-started-create-service-instance) \n- API Management サービスがプロビジョニングされたら、サービスの OpenAPI 仕様を使用して OpenAI API レイヤーをインポートできます。\n  - [インポート手順](https://learn.microsoft.com/en-us/azure/api-management/import-and-publish#go-to-your-api-management-instance)\n  - [APIM - API] ブレードを開き、既存の API の [ インポート ] オプションを選択します。  \n  ![img](/assets/apim_config_0.0.png)\n  - [ 更新 ] オプションを選択して、API を現在の OpenAI 仕様に更新します。\n    - Completions OpenAPI -  https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cognitiveservices/data-plane/AzureOpenAI/inference/preview/2023-03-15-preview/inference.json\n  ![img](/assets/apim_config_0.1.png)\n- \u003cb\u003eすべての API 操作のために\u003c/b\u003e:\n  - \u003cb\u003e設定\u003c/b\u003e で、OpenAI ライブラリの仕様と一致するように サブスクリプション - \u003cb\u003eヘッダー名]\u003c/b\u003e を \"api-key\" に設定します。\n  ![img](assets/apim-config-apikey.png)\n  -  \"set-headers\" のinbound ruleを構成して、\"api-key\" ヘッダーパラメーターを OpenAI サービスからの API シークレットキーの値で追加/上書きします。OpenAIキーを見つけるための手順はここにあります: [キーを取得する](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/quickstart?pivots=programming-language-python#retrieve-key-and-endpoint)\n  ![img](/assets/apim_config_1.png)\n  - デプロイされたOpenAIサービスのエンドポイントにバックエンドサービスを`/openai`として構成し、既存のエンドポイントを必ず上書きしてください。 \n    - 例: \u003cb\u003ehttps://\u003c yourservicename \u003e.openai.azure.com\u003ci\u003e/openai\u003c/i\u003e\u003c/b\u003e\n    - [エンドポイントの取得](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/quickstart?pivots=programming-language-python#retrieve-key-and-endpoint)\n  ![img](/assets/apim_config_2.png)\n  - 診断ログの設定を構成します:\n    - Sampling rateを100%に設定します\n    - 「Number of payload bytes to log」を最大値に設定します。\n  ![img](/assets/apim_config_3.png)\n\n- APIのテスト\n  - \"デプロイ ID\"、\"API バージョン\"、およびサンプル プロンプトを指定して、エンドポイントをテストします:\n    ![img](/assets/apim_config_4.png)\n\n  \n#### サブスクリプションのアクセス制御\nAPI Management を使用すると、API プロバイダーは API を不正使用から保護し、さまざまな API 製品レベルの価値を生み出すことができます。API 管理レイヤーを使用して受信要求を調整することは、Azure API 管理の重要な役割です。要求の速度または転送された要求/データの合計を制御することによって。\n\u003cbr/\u003eAPIM レイヤーの構成の詳細: https://learn.microsoft.com/en-us/azure/api-management/api-management-sample-flexible-throttling\n\n### OpenAIのログ記録\n- API 管理レイヤーを構成したら、サブスクリプション キー パラメーターをcompletion要求に追加することで、API レイヤーを使用するように既存の OpenAI Python コードを構成できます。 例：\n```python\nimport openai\n\nopenai.api_type = \"azure\"\nopenai.api_base = \"https://xxxxxxxxx.azure-api.net/\" # APIM Endpoint\nopenai.api_version = \"2023-03-15-preview\"\nopenai.api_key = \"APIM SUBSCRIPTION KEY\" #DO NOT USE ACTUAL AZURE OPENAI SERVICE KEY\n\n\nresponse = openai.Completion.create(engine=\"modelname\",  \n                                    prompt=\"prompt text\", temperature=1,  \n                                    max_tokens=200,  top_p=0.5,  \n                                    frequency_penalty=0,  \n                                    presence_penalty=0,  \n                                    stop=None) \n\n```\n\n\u003c/code\u003e\n\n## デモ\n\n- OpenAI 要求が Azure Monitor サービスへのログ記録を開始したら、Log Analytics クエリを使用してサービスの使用状況の分析を開始できます。\n  - [Log Analytics チュートリアル](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/log-analytics-tutorial)\n- テーブルの名前は  \u003cb\u003e\"ApiManagementGatewayLogs\"\u003c/b\u003eテーブルの名前は \n- \u003cb\u003eBackendResponseBody\u003c/b\u003e フィールドには、テキスト補完、トークンおよびモデル情報を含む OpenAI サービスからの json 応答が含まれています。\n- IP とモデルによってトークンの使用状況を識別するクエリの例:\n```kusto\nApiManagementGatewayLogs\n| where OperationId == 'completions_create'\n| extend modelkey = substring(parse_json(BackendResponseBody)['model'], 0, indexof(parse_json(BackendResponseBody)['model'], '-', 0, -1, 2))\n| extend model = tostring(parse_json(BackendResponseBody)['model'])\n| extend prompttokens = parse_json(parse_json(BackendResponseBody)['usage'])['prompt_tokens']\n| extend completiontokens = parse_json(parse_json(BackendResponseBody)['usage'])['completion_tokens']\n| extend totaltokens = parse_json(parse_json(BackendResponseBody)['usage'])['total_tokens']\n| extend ip = CallerIpAddress\n| where model !=  ''\n| summarize\n    sum(todecimal(prompttokens)),\n    sum(todecimal(completiontokens)),\n    sum(todecimal(totaltokens)),\n    avg(todecimal(totaltokens))\n    by ip, model\n```\n![img](/assets/monitor_0.png)\n- プロンプトの完了を監視するクエリの例:\n```kusto\nApiManagementGatewayLogs\n| where OperationId == 'completions_create'\n| extend model = tostring(parse_json(BackendResponseBody)['model'])\n| extend prompttokens = parse_json(parse_json(BackendResponseBody)['usage'])['prompt_tokens']\n| extend prompttext = substring(parse_json(parse_json(BackendResponseBody)['choices'])[0], 0, 100)\n```\n![img](/assets/monitor_1.png)\n\n\n","funding_links":[],"categories":["**Section 2** : Azure OpenAI and Reference Architecture","Azure OpenAI Samples"],"sub_categories":["**Azure Reference Architectures**"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAzure-Samples%2Fopenai-python-enterprise-logging","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAzure-Samples%2Fopenai-python-enterprise-logging","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAzure-Samples%2Fopenai-python-enterprise-logging/lists"}