실제 비즈니스 시나리오에서는 다음과 같은 문제에 직면하는 경우가 많습니다.
이상적인 솔루션은 작업 복잡성에 따라 적절한 모델을 동적으로 선택하여 비용을 제어하면서 성능을 보장하는 것입니다.
from langchain.chat_models import ChatOpenAI from langchain.chains import LLMChain from langchain.prompts import ChatPromptTemplate from langchain.callbacks import get_openai_callback from typing import Dict, List, Optional import json # Initialize models class ModelPool: def __init__(self): self.gpt4 = ChatOpenAI( model_name="gpt-4", temperature=0.7, max_tokens=1000 ) self.gpt35 = ChatOpenAI( model_name="gpt-3.5-turbo", temperature=0.7, max_tokens=1000 )
class ComplexityAnalyzer: def __init__(self): self.complexity_prompt = ChatPromptTemplate.from_template( "Analyze the complexity of the following task, return a score from 1-10:\n{task}" ) self.analyzer_chain = LLMChain( llm=ChatOpenAI(model_name="gpt-3.5-turbo"), prompt=self.complexity_prompt ) async def analyze(self, task: str) -> int: result = await self.analyzer_chain.arun(task=task) return int(result.strip())
class ModelRouter: def __init__(self, complexity_threshold: int = 7): self.complexity_threshold = complexity_threshold self.model_pool = ModelPool() self.analyzer = ComplexityAnalyzer() async def route(self, task: str) -> ChatOpenAI: complexity = await self.analyzer.analyze(task) if complexity >= self.complexity_threshold: return self.model_pool.gpt4 return self.model_pool.gpt35
class CostController: def __init__(self, budget_limit: float): self.budget_limit = budget_limit self.total_cost = 0.0 def track_cost(self, callback_data): cost = callback_data.total_cost self.total_cost += cost if self.total_cost > self.budget_limit: raise Exception("Budget exceeded") return cost
class MultiModelSystem: def __init__(self, budget_limit: float = 10.0): self.router = ModelRouter() self.cost_controller = CostController(budget_limit) async def process(self, task: str) -> Dict: model = await self.router.route(task) with get_openai_callback() as cb: response = await model.agenerate([[task]]) cost = self.cost_controller.track_cost(cb) return { "result": response.generations[0][0].text, "model": model.model_name, "cost": cost }
고객 서비스 예시를 통해 시스템을 살펴보겠습니다.
async def customer_service_demo(): system = MultiModelSystem(budget_limit=1.0) # Simple query - should route to GPT-3.5 simple_query = "What are your business hours?" simple_result = await system.process(simple_query) # Complex query - should route to GPT-4 complex_query = """ I'd like to understand your return policy. Specifically: 1. If the product has quality issues but has been used for a while 2. If it's a limited item but the packaging has been opened 3. If it's a cross-border purchase How should these situations be handled? What costs are involved? """ complex_result = await system.process(complex_query) return simple_result, complex_result
실제 테스트에서는 다양한 전략을 비교했습니다.
Strategy | Avg Response Time | Avg Cost/Query | Accuracy |
---|---|---|---|
GPT-4 Only | 2.5s | .06 | 95% |
GPT-3.5 Only | 1.0s | .004 | 85% |
Hybrid Strategy | 1.5s | .015 | 92% |
다중 모델 협업 시스템은 높은 서비스 품질을 유지하면서 운영 비용을 대폭 절감할 수 있습니다. 핵심은 다음과 같습니다.
위 내용은 비용 효율적인 다중 모델 시스템 구축: GPT- GPT- 구현 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!