이 자습서에서는 자습서 시리즈의 2부에서 빌드한 채팅 앱을 평가합니다. 여러 메트릭에서 앱의 품질을 평가한 다음 개선 사항을 반복합니다. 이 부분에서는 다음을 수행합니다.
- 평가 데이터 세트 만들기
- Azure AI 평가자를 사용하여 채팅 앱 평가
- 앱 반복 및 개선
이 자습서는 2부: Microsoft Foundry SDK를 사용하여 사용자 지정 채팅 앱을 빌드합니다.
필수 조건
중요합니다
이 문서에서는 허브 기반 프로젝트에 대한 레거시 지원을 제공합니다. Foundry 프로젝트에는 작동하지 않을 것입니다. 어떤 유형의 프로젝트를 가지고 있는지 어떻게 알 수 있나요?
SDK 호환성 참고: 코드 예제에는 특정 Microsoft Foundry SDK 버전이 필요합니다. 호환성 문제가 발생하는 경우 허브 기반에서 Foundry 프로젝트로 마이그레이션하는 것이 좋습니다.
- 활성 구독이 있는 Azure 계정. 계정이 없는 경우 평가판 구독을 포함하는 무료 Azure 계정을 만듭니다.
- 없는 경우 허브 기반 프로젝트를 만듭니다.
- 자습서 시리즈의 2부를 완료하여 채팅 애플리케이션을 빌드합니다.
- 1부에서 만든 것과 동일한 허브 기반 프로젝트를 사용합니다.
- Azure AI 권한: 모델 엔드포인트 속도 제한을 수정하고 평가 작업을 실행하는 소유자 또는 기여자 역할입니다.
- 2부에서 원격 분석 로깅을 추가하는 단계를 완료해야 합니다.
평가 데이터 세트 만들기
예제 질문과 예상 답변이 포함된 다음 평가 데이터 세트를 사용합니다. 평가자 및 대상 함수와 get_chat_response() 함께 이 데이터 세트를 사용하여 관련성, 근거 및 일관성 메트릭에서 채팅 앱의 성능을 평가합니다.
assets 폴더에 chat_eval_data.jsonl 이름의 파일을 만듭니다.
다음 데이터 세트를 파일에 붙여넣습니다.
{"query": "Which tent is the most waterproof?", "truth": "The Alpine Explorer Tent has the highest rainfly waterproof rating at 3000m"} {"query": "Which camping table holds the most weight?", "truth": "The Adventure Dining Table has a higher weight capacity than all of the other camping tables mentioned"} {"query": "How much do the TrailWalker Hiking Shoes cost? ", "truth": "The Trailewalker Hiking Shoes are priced at $110"} {"query": "What is the proper care for trailwalker hiking shoes? ", "truth": "After each use, remove any dirt or debris by brushing or wiping the shoes with a damp cloth."} {"query": "What brand is TrailMaster tent? ", "truth": "OutdoorLiving"} {"query": "How do I carry the TrailMaster tent around? ", "truth": " Carry bag included for convenient storage and transportation"} {"query": "What is the floor area for Floor Area? ", "truth": "80 square feet"} {"query": "What is the material for TrailBlaze Hiking Pants?", "truth": "Made of high-quality nylon fabric"} {"query": "What color does TrailBlaze Hiking Pants come in?", "truth": "Khaki"} {"query": "Can the warrenty for TrailBlaze pants be transfered? ", "truth": "The warranty is non-transferable and applies only to the original purchaser of the TrailBlaze Hiking Pants. It is valid only when the product is purchased from an authorized retailer."} {"query": "How long are the TrailBlaze pants under warranty for? ", "truth": " The TrailBlaze Hiking Pants are backed by a 1-year limited warranty from the date of purchase."} {"query": "What is the material for PowerBurner Camping Stove? ", "truth": "Stainless Steel"} {"query": "Is France in Europe?", "truth": "Sorry, I can only queries related to outdoor/camping gear and equipment"}
Azure AI 평가자를 사용하여 평가
대상 함수 래퍼를 생성하고, 데이터 세트를 로드하고, 평가를 실행하고, 결과를 Foundry 프로젝트에 기록하는 평가 스크립트를 만듭니다.
주 폴더에 evaluate.py 파일을 만듭니다.
다음 코드를 추가하여 필요한 라이브러리를 가져오고, 프로젝트 클라이언트를 만들고, 일부 설정을 구성합니다.
import os import pandas as pd from azure.ai.projects import AIProjectClient from azure.ai.projects.models import ConnectionType from azure.ai.evaluation import evaluate, GroundednessEvaluator from azure.identity import DefaultAzureCredential from chat_with_products import chat_with_products # load environment variables from the .env file at the root of this repo from dotenv import load_dotenv load_dotenv() # create a project client using environment variables loaded from the .env file project = AIProjectClient.from_connection_string( conn_str=os.environ["AIPROJECT_CONNECTION_STRING"], credential=DefaultAzureCredential() ) connection = project.connections.get_default(connection_type=ConnectionType.AZURE_OPEN_AI, include_credentials=True) evaluator_model = { "azure_endpoint": connection.endpoint_url, "azure_deployment": os.environ["EVALUATION_MODEL"], "api_version": "2024-06-01", "api_key": connection.key, } groundedness = GroundednessEvaluator(evaluator_model)참조: AIProjectClient, DefaultAzureCredential, azure-ai-evaluation.
쿼리 및 응답 평가를 위해 평가 인터페이스를 구현하는 래퍼 함수를 만드는 코드를 추가합니다.
def evaluate_chat_with_products(query): response = chat_with_products(messages=[{"role": "user", "content": query}]) return {"response": response["message"].content, "context": response["context"]["grounding_data"]}참조: azure-ai-evaluation, 평가 대상 함수.
마지막으로, 평가를 실행하고, 결과를 로컬로 보고, Foundry 포털에서 평가 결과에 대한 링크를 가져오는 코드를 추가합니다.
# Evaluate must be called inside of __main__, not on import if __name__ == "__main__": from config import ASSET_PATH # workaround for multiprocessing issue on linux from pprint import pprint from pathlib import Path import multiprocessing import contextlib with contextlib.suppress(RuntimeError): multiprocessing.set_start_method("spawn", force=True) # run evaluation with a dataset and target function, log to the project result = evaluate( data=Path(ASSET_PATH) / "chat_eval_data.jsonl", target=evaluate_chat_with_products, evaluation_name="evaluate_chat_with_products", evaluators={ "groundedness": groundedness, }, evaluator_config={ "default": { "query": {"${data.query}"}, "response": {"${target.response}"}, "context": {"${target.context}"}, } }, azure_ai_project=project.scope, output_path="./myevalresults.json", ) tabular_result = pd.DataFrame(result.get("rows")) pprint("-----Summarized Metrics-----") pprint(result["metrics"]) pprint("-----Tabular Result-----") pprint(tabular_result) pprint(f"View evaluation results in AI Studio: {result['studio_url']}")
평가 모델 구성
평가 스크립트는 모델을 여러 번 호출합니다. 평가 모델의 분당 토큰 수를 늘리는 것이 좋습니다.
이 자습서 시리즈의 1부에서는 평가 모델의 이름을 지정하는 .env 파일을 만들었습니다. 사용 가능한 할당량이 있는 경우 이 모델에 대한 분당 토큰 제한을 늘려 보세요. 값을 늘릴 할당량이 충분하지 않은 경우 걱정하지 마세요. 스크립트는 제한 오류를 처리하도록 설계되었습니다.
- Foundry 포털의 프로젝트에서 모델 + 엔드포인트를 선택합니다.
- gpt-4o-mini를 선택합니다.
- 편집을 선택합니다.
- 할당량이 있는 경우 분당 토큰 속도 제한을 30 이상으로 늘입니다.
- 저장 후 닫기를 선택합니다.
평가 스크립트 실행
콘솔에서 Azure CLI를 사용하여 Azure 계정에 로그인합니다.
az login필요한 패키지를 설치합니다.
pip install openai pip install azure-ai-evaluation[remote]참조: azure-ai-evaluation SDK, Evaluation SDK 설명서.
평가 설정 확인
전체 평가(5~10분 소요)를 실행하기 전에 이 빠른 테스트를 실행하여 SDK 및 프로젝트 연결이 작동하는지 확인합니다.
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
# Test that you can connect to your project
project = AIProjectClient.from_connection_string(
conn_str=os.environ["AIPROJECT_CONNECTION_STRING"], credential=DefaultAzureCredential()
)
print("Evaluation SDK is ready! You can now run evaluate.py")
표시되는 "Evaluation SDK is ready!"경우 설정이 완료되었으며 계속 진행할 수 있습니다.
참조: AIProjectClient, DefaultAzureCredential.
평가 시작
평가 스크립트를 실행합니다.
python evaluate.py
평가를 완료하는 데 5~10분이 걸립니다. 시간 제한 경고 및 속도 제한 오류가 표시될 수 있습니다. 스크립트는 이러한 오류를 자동으로 처리하고 처리를 계속합니다.
평가 출력 해석
콘솔 출력에서 각 질문에 대한 답변과 관련성, 근거 및 일관성 점수를 보여 주는 요약된 메트릭이 있는 테이블이 표시됩니다. GPT 지원 메트릭의 점수 범위는 0(최악)에서 4(최상)입니다. 근거점수가 낮은 응답을 찾아 참조 문서에서 잘 지원되지 않는 응답을 식별하고, 관련성 점수가 낮은 응답을 찾아 동떨어진 항목을 식별합니다.
많은 WARNING:opentelemetry.attributes: 메시지와 시간 제한 오류가 표시될 수 있습니다. 이러한 메시지는 무시해도 됩니다. 평가 결과에는 영향을 주지 않습니다. 평가 스크립트는 속도 제한 오류를 처리하고 처리를 계속하도록 설계되었습니다.
평가 결과 출력에는 Foundry 포털에서 자세한 결과를 볼 수 있는 링크도 포함되어 있습니다. 여기에서 평가 실행을 나란히 비교하고 시간에 따른 개선 사항을 추적할 수 있습니다.
====================================================
'-----Summarized Metrics-----'
{'groundedness.gpt_groundedness': 1.6666666666666667,
'groundedness.groundedness': 1.6666666666666667}
'-----Tabular Result-----'
outputs.response ... line_number
0 Could you specify which tent you are referring... ... 0
1 Could you please specify which camping table y... ... 1
2 Sorry, I only can answer queries related to ou... ... 2
3 Could you please clarify which aspects of care... ... 3
4 Sorry, I only can answer queries related to ou... ... 4
5 The TrailMaster X4 Tent comes with an included... ... 5
6 (Failed) ... 6
7 The TrailBlaze Hiking Pants are crafted from h... ... 7
8 Sorry, I only can answer queries related to ou... ... 8
9 Sorry, I only can answer queries related to ou... ... 9
10 Sorry, I only can answer queries related to ou... ... 10
11 The PowerBurner Camping Stove is designed with... ... 11
12 Sorry, I only can answer queries related to ou... ... 12
[13 rows x 8 columns]
('View evaluation results in Foundry portal: '
'https://xxxxxxxxxxxxxxxxxxxxxxx')
반복 및 개선
평가 결과에 따르면 응답이 참조 문서에 잘 맞지 않는 경우가 많습니다. 기본 기능을 향상하려면 assets/grounded_chat.prompty 파일에서 시스템 프롬프트를 수정하여 모델이 참조 문서를 보다 직접 사용하도록 장려합니다.
현재 프롬프트(문제):
If the question is not related to outdoor/camping gear and clothing, just say 'Sorry, I only can answer queries related to outdoor/camping gear and clothing. So, how can I help?'
If the question is related to outdoor/camping gear and clothing but vague, ask clarifying questions.
향상된 프롬프트:
If the question is related to outdoor/camping gear and clothing, answer based on the reference documents provided.
If you cannot find information in the reference documents, say: 'I don't have information about that specific topic. Let me help with related products or try a different question.'
For vague questions, ask clarifying questions to better assist.
프롬프트를 업데이트한 후:
파일을 저장합니다.
평가 스크립트를 다시 실행합니다.
python evaluate.py새 평가 결과를 이전 실행과 비교합니다. 개선된 기반성 점수를 확인할 수 있습니다.
다음과 같은 추가 수정을 시도합니다.
- 완전성에 대한 정확도에 집중하도록 시스템 프롬프트 변경
- 다른 모델을 사용하여 테스트(예
gpt-4-turbo: 사용 가능한 경우) - 더 관련성이 큰 문서를 반환하도록 컨텍스트 검색 조정
각 반복은 특정 메트릭을 개선하는 변경 내용을 이해하는 데 도움이 됩니다.
자원을 정리하세요
불필요한 Azure 비용이 발생하지 않도록 하려면 더 이상 필요하지 않은 경우 이 자습서에서 만든 리소스를 삭제합니다. 리소스를 관리하려면 Azure Portal을 사용하면 됩니다.