OCI Gen AI 연동하기
OCI Gen AI 연동하기 (OCI Gen AI Integration)
이 가이드에서는 Oracle Cloud Infrastructure(OCI)의 Generative AI 모델을 Ragas 평가에 사용하는 방법을 다뤄요. OCI 의존성 설치부터 인증 설정, 실제 평가까지 흐름을 따라가 볼게요.
출처: 문서
본문
설치
먼저 OCI 의존성을 설치해요.
pip install ragas[oci]
설정
1. OCI 인증 구성하기
다음 방법 중 하나로 OCI 설정을 구성해요.
방법 A: OCI CLI 설정
oci setup config
방법 B: 환경 변수
export OCI_CONFIG_FILE=~/.oci/config
export OCI_PROFILE=DEFAULT
방법 C: 수동 설정
config = {
"user": "ocid1.user.oc1..example",
"key_file": "~/.oci/private_key.pem",
"fingerprint": "your_fingerprint",
"tenancy": "ocid1.tenancy.oc1..example",
"region": "us-ashburn-1"
}
2. 필요한 ID 구하기
다음이 필요해요.
- 모델 ID (Model ID): OCI 모델 ID (예:
cohere.command,meta.llama-3-8b) - 컴파트먼트 ID (Compartment ID): OCI 컴파트먼트 OCID
- 엔드포인트 ID (Endpoint ID) (선택): 커스텀 엔드포인트를 사용할 경우
사용법
기본 사용법
from ragas.llms import oci_genai_factory
from ragas import evaluate
from datasets import Dataset
# Initialize OCI Gen AI LLM
llm = oci_genai_factory(
model_id="cohere.command",
compartment_id="ocid1.compartment.oc1..example"
)
# Your dataset
dataset = Dataset.from_dict({
"question": ["What is the capital of France?"],
"answer": ["Paris"],
"contexts": [["France is a country in Europe. Its capital is Paris."]],
"ground_truth": ["Paris"]
})
# Evaluate with OCI Gen AI
result = evaluate(
dataset,
llm=llm,
embeddings=None # You can use any embedding model
)
고급 설정
from ragas.llms import oci_genai_factory
from ragas.run_config import RunConfig
# Custom OCI configuration
config = {
"user": "ocid1.user.oc1..example",
"key_file": "~/.oci/private_key.pem",
"fingerprint": "your_fingerprint",
"tenancy": "ocid1.tenancy.oc1..example",
"region": "us-ashburn-1"
}
# Custom run configuration
run_config = RunConfig(
timeout=60,
max_retries=3
)
# Initialize with custom config and endpoint
llm = oci_genai_factory(
model_id="cohere.command",
compartment_id="ocid1.compartment.oc1..example",
config=config,
endpoint_id="ocid1.endpoint.oc1..example", # Optional
run_config=run_config
)
다른 모델과 함께 사용하기
# Cohere Command model
llm_cohere = oci_genai_factory(
model_id="cohere.command",
compartment_id="ocid1.compartment.oc1..example"
)
# Meta Llama model
llm_llama = oci_genai_factory(
model_id="meta.llama-3-8b",
compartment_id="ocid1.compartment.oc1..example"
)
# Using with different endpoints
llm_endpoint = oci_genai_factory(
model_id="cohere.command",
compartment_id="ocid1.compartment.oc1..example",
endpoint_id="ocid1.endpoint.oc1..example"
)
사용 가능한 모델
OCI Gen AI는 다양한 모델을 지원해요.
- Cohere:
cohere.command,cohere.command-light - Meta:
meta.llama-3-8b,meta.llama-3-70b - Mistral:
mistral.mistral-7b-instruct - 그 외: 최신 사용 가능 모델은 OCI 문서를 확인해요
오류 처리
OCI Gen AI 래퍼에는 포괄적인 오류 처리가 포함돼 있어요.
try:
result = evaluate(dataset, llm=llm)
except Exception as e:
print(f"Evaluation failed: {e}")
성능 고려 사항
- 속도 제한 (Rate Limits): OCI Gen AI에는 속도 제한이 있어요. 적절한 재시도 설정을 사용하세요.
- 타임아웃 (Timeout): 사용 사례에 맞는 타임아웃을 설정하세요.
- 배치 처리 (Batch Processing): 래퍼는 여러 응답에 대한 배치 처리를 지원해요.
트러블슈팅
흔한 문제
- 인증 오류 (Authentication Errors)
Error: OCI SDK authentication failed
해결책: OCI 설정과 자격 증명을 확인해요.
- 모델을 찾을 수 없음 (Model Not Found)
Error: Model not found in compartment
해결책: 컴파트먼트 안에 모델 ID가 존재하는지 확인해요.
- 권한 오류 (Permission Errors)
Error: Insufficient permissions
해결책: 사용자에게 Generative AI에 필요한 IAM 정책이 있는지 확인해요.
디버그 모드
문제를 진단하려면 디버그 로깅을 활성화해요.
import logging
logging.basicConfig(level=logging.DEBUG)
# Your OCI Gen AI code here
예제
완전한 평가 예제
from ragas import evaluate
from ragas.llms import oci_genai_factory
from ragas.metrics import faithfulness, answer_relevancy, context_precision
from datasets import Dataset
# Initialize OCI Gen AI
llm = oci_genai_factory(
model_id="cohere.command",
compartment_id="ocid1.compartment.oc1..example"
)
# Create dataset
dataset = Dataset.from_dict({
"question": [
"What is the capital of France?",
"Who wrote Romeo and Juliet?"
],
"answer": [
"Paris is the capital of France.",
"William Shakespeare wrote Romeo and Juliet."
],
"contexts": [
["France is a country in Europe. Its capital is Paris."],
["Romeo and Juliet is a play by William Shakespeare."]
],
"ground_truth": [
"Paris",
"William Shakespeare"
]
})
# Evaluate
result = evaluate(
dataset,
metrics=[faithfulness, answer_relevancy, context_precision],
llm=llm
)
print(result)
OCI Gen AI와 커스텀 지표
from ragas.metrics import MetricWithLLM
# Create custom metric using OCI Gen AI
class CustomMetric(MetricWithLLM):
def __init__(self):
super().__init__()
self.llm = oci_genai_factory(
model_id="cohere.command",
compartment_id="ocid1.compartment.oc1..example"
)
# Use in evaluation
result = evaluate(
dataset,
metrics=[CustomMetric()],
llm=llm
)
모범 사례
- 적절한 모델 사용: 평가 요구에 맞는 모델을 선택하세요.
- 비용 모니터링: OCI Gen AI 사용은 과금돼요. 사용량을 모니터링하세요.
- 오류 처리: 프로덕션에서는 적절한 오류 처리를 구현하세요.
- 캐싱 사용: 반복 평가에는 캐싱을 활성화하세요.
- 배치 작업: 가능하면 효율성을 위해 배치 작업을 사용하세요.
지원
OCI Gen AI 연동 관련 문제가 있다면: