Code Velocity
Корпоративен ИИ

Управление на разходите за ИИ: Проекти на Amazon Bedrock за приписване на разходи

·5 мин четене·AWS·Оригинален източник
Сподели
Диаграма, показваща потока за приписване на разходи за проекти на Amazon Bedrock за управление на разходите за ИИ в различни работни натоварвания

След това използвайте предоставения Python скрипт, за да създадете проект, като се уверите, че вашият AWS регион е конфигуриран правилно и вашият API ключ на Amazon Bedrock е зададен като променлива на средата OPENAI_API_KEY.

import os
import requests

# Configuration
BASE_URL = "https://bedrock-mantle.<YOUR-REGION-HERE>.api.aws/v1"
API_KEY  = os.environ.get("OPENAI_API_KEY")  # Вашият API ключ на Amazon Bedrock

def create_project(name: str, tags: dict) -> dict:
    """Създаване на проект на Bedrock с тагове за разпределение на разходите."""
    response = requests.post(
        f"{BASE_URL}/organization/projects",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={"name": name, "tags": tags}
    )

    if response.status_code != 200:
        raise Exception(
            f"Неуспешно създаване на проект: {response.status_code} - {response.text}"
        )

    return response.json()

# Пример: Създаване на производствен проект с пълна таксономия на тагове
project = create_project(
    name="CustomerChatbot-Prod",
    tags={
        "Application": "CustomerChatbot",
        "Environment": "Production",
        "Team":        "CustomerExperience",
        "CostCenter":  "CC-1001",
        "Owner":       "alice"
    }
)
print(f"Създаден проект: {project['id']}")

Този скрипт ще върне детайлите на проекта, включително неговия уникален id (напр. proj_123) и ARN. Запазете този id, тъй като той ще бъде от решаващо значение за асоциирането на вашите заявки за извод. Можете да създадете до 1000 проекта на AWS акаунт, предлагайки достатъчна гъвкавост дори за най-големите организации.

Асоцииране на заявки за извод

След като вашият проект е създаден, интегрирайте неговия ИД във вашите API повиквания на Bedrock. Например, използвайки Responses API:

from openai import OpenAI

client = OpenAI(
    base_url="https://bedrock-mantle.<YOUR-REGION-HERE>.api.aws/v1",
    project="<ВАШИЯ-ИД-НА-ПРОЕКТ>", # ИД, върнат при създаването на проекта
)
response = client.responses.create(
    model="openai.gpt-oss-120b",
    input="Summarize the key findings from our Q4 earnings report."
)
print(response.output_text)

Чрез постоянно включване на параметъра project осигурявате точно приписване на разходите за всеки извод. За по-напреднали приложения на Bedrock, помислете как това се интегрира с по-широки стратегии като изграждане на двигател за A/B тестване, задвижван от ИИ, използващ Amazon Bedrock.

Активиране и анализ на вашите ИИ разходи в AWS

Последната стъпка в осигуряването на цялостна видимост на разходите е активирането на вашите персонализирани тагове за проекти като тагове за разпределение на разходите в конзолата за AWS Billing. Това е еднократна конфигурация, която указва на AWS да включи тези тагове във вашите подробни отчети за таксуване.

Активиране на тагове за разпределение на разходите

Навигирайте до конзолата за AWS Billing and Cost Management и следвайте инструкциите за активиране на вашите персонализирани тагове. Препоръчително е да направите това веднага след създаването на първия си проект, за да избегнете пропуски във вашите данни за разходите. Имайте предвид, че може да отнеме до 24 часа, докато тези тагове се разпространят напълно и се появят в AWS Cost Explorer и AWS Data Exports.

Преглед на разходите за проекти в AWS Cost Explorer

След като бъдат активирани, можете да използвате AWS Cost Explorer, за да визуализирате и анализирате разходите си за Amazon Bedrock с безпрецедентна детайлност. Можете да филтрирате разходите си по Service (Amazon Bedrock) и след това да ги групирате по вашите персонализирани тагове за разпределение на разходите, като Application, Environment или CostCenter. Това ви позволява да:

  • Идентифицирате основните двигатели на разходите: Бързо да определите кои приложения или среди консумират най-много генеративни ИИ ресурси.
  • Извършвате префактуриране: Генерирате точни отчети за вътрешни модели за префактуриране, гарантирайки, че отделите са таксувани справедливо за тяхното използване на ИИ.
  • Оптимизирате разходите: Откривате области на неефективност, като например скъпи модели, използвани в некритични среди за разработка, и да вземате информирани решения за оптимизиране на разпределението на ресурсите.
  • Прогнозирате и бюджетирате: Подобрите точността на бъдещите прогнози за разходите за ИИ, като анализирате исторически данни, разбити по конкретни работни натоварвания.

Чрез възприемането на проектите на Amazon Bedrock и дисциплинирана стратегия за тагване, организациите могат да трансформират неясните разходи за ИИ в прозрачни, приложими прозрения. Това не само поддържа по-добро финансово управление, но и насърчава култура на осъзнатост на разходите, позволявайки на екипите да мащабират своите инициативи за генеративен ИИ отговорно и ефективно. Този детайлен контрол върху ресурсите е ключов и за ефективното интегриране на нови възможности като Amazon Bedrock AgentCore.

Често задавани въпроси

What are Amazon Bedrock Projects and how do they enhance AI cost management?
Amazon Bedrock Projects provide a logical boundary within the Amazon Bedrock service to represent specific AI workloads, such as applications, environments, or experiments. By associating inference requests with a project ID and attaching resource tags, organizations can gain granular visibility into their generative AI spending. This allows for precise cost attribution to individual teams, departments, or applications, facilitating accurate chargebacks, identifying cost spikes, and informing strategic optimization decisions, thereby enhancing overall financial governance and resource allocation for large-scale AI deployments.
Why is a robust tagging strategy crucial for effective cost attribution with Bedrock Projects?
A robust tagging strategy is crucial because the tags attached to Amazon Bedrock Projects become the primary dimensions for filtering and grouping cost data in AWS Cost Explorer and AWS Data Exports. By systematically tagging projects with attributes like 'Application,' 'Environment,' 'Team,' and 'CostCenter,' organizations can create a comprehensive taxonomy that mirrors their internal structure. This structured approach enables deep dives into spending patterns, helps identify high-cost areas, supports cross-departmental chargebacks, and ensures that financial reporting accurately reflects resource consumption by specific AI workloads, making cost analysis more actionable and transparent.
How do I activate cost allocation tags for Amazon Bedrock Projects in AWS Billing?
After defining your tagging strategy and creating projects with associated tags in Amazon Bedrock, you must activate these tags as cost allocation tags within the AWS Billing and Cost Management console. This crucial, one-time setup step ensures that the tags attached to your Bedrock Projects are recognized by the AWS billing pipeline. Once activated, it can take up to 24 hours for the tags to propagate and for cost data to become visible and filterable in tools like AWS Cost Explorer and AWS Data Exports. Activating these tags promptly after your initial project setup prevents gaps in your cost visibility and ensures continuous, accurate reporting.
Which Amazon Bedrock APIs support cost attribution through Project IDs?
Currently, Amazon Bedrock Projects support cost attribution via Project IDs for inference requests made through the OpenAI-compatible APIs, specifically the Responses API and the Chat Completions API. When making API calls using these endpoints, developers should include the designated Project ID to ensure that the associated costs are accurately attributed to the correct workload. It is a best practice to always explicitly specify a Project ID in API calls to avoid costs being automatically associated with the default project in your AWS account, which can hinder granular cost analysis and management efforts.
What are the benefits of using Amazon Bedrock Projects for large enterprises?
For large enterprises, Amazon Bedrock Projects offer significant benefits by providing a standardized, scalable mechanism for managing and optimizing generative AI costs. They enable granular visibility into AI spending across diverse teams, applications, and environments, supporting precise financial forecasting and budgeting. This capability is vital for complex organizational structures requiring chargebacks or detailed departmental cost allocation. Furthermore, it empowers businesses to identify inefficient workloads, optimize model usage, and make data-driven decisions to reduce overall AI infrastructure expenses, aligning technology investments with business value and ensuring responsible AI scaling.

Бъдете информирани

Получавайте последните AI новини по имейл.

Сподели