Appearance
第68天:国内平台深度对比(上)
学习目标
- 了解百度文心一言
- 掌握阿里通义千问
- 学习腾讯混元
- 理解智谱AI(ChatGLM)
- 掌握平台特点对比
百度文心一言
平台概述
python
class BaiduERNIEBot:
def __init__(self, api_key: str, secret_key: str):
self.api_key = api_key
self.secret_key = secret_key
self.access_token = None
self.base_url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat"
def get_access_token(self) -> str:
import requests
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {
"grant_type": "client_credentials",
"client_id": self.api_key,
"client_secret": self.secret_key
}
response = requests.post(url, params=params)
self.access_token = response.json()["access_token"]
return self.access_token
def chat(self, messages: List[Dict],
model: str = "ernie-bot-4") -> Dict:
import requests
if not self.access_token:
self.get_access_token()
url = f"{self.base_url}/{model}?access_token={self.access_token}"
payload = {
"messages": messages
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
return response.json()
def stream_chat(self, messages: List[Dict],
model: str = "ernie-bot-4"):
import requests
if not self.access_token:
self.get_access_token()
url = f"{self.base_url}/{model}?access_token={self.access_token}"
payload = {
"messages": messages,
"stream": True
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers, stream=True)
for line in response.iter_lines():
if line:
yield line.decode("utf-8")平台特点
python
class BaiduPlatformFeatures:
def __init__(self):
self.features = {
"model_variety": {
"description": "模型多样性",
"models": [
"ERNIE-Bot-4",
"ERNIE-Bot-3.5",
"ERNIE-Bot-turbo",
"ERNIE-Speed",
"ERNIE-Lite"
],
"score": 5
},
"performance": {
"description": "性能表现",
"metrics": {
"response_time": "< 1s",
"accuracy": "高",
"context_length": "128K"
},
"score": 4
},
"cost": {
"description": "成本",
"pricing": {
"ERNIE-Bot-4": "0.12元/千tokens",
"ERNIE-Bot-3.5": "0.008元/千tokens",
"ERNIE-Bot-turbo": "0.008元/千tokens"
},
"score": 4
},
"ecosystem": {
"description": "生态支持",
"features": [
"SDK支持",
"API文档完善",
"社区活跃",
"企业级支持"
],
"score": 4
},
"compliance": {
"description": "合规性",
"certifications": [
"ISO27001",
"等保三级",
"数据本地化"
],
"score": 5
}
}
def get_feature(self, feature_name: str) -> Dict:
return self.features.get(feature_name, {})
def get_all_features(self) -> Dict:
return self.features
def calculate_overall_score(self) -> float:
scores = [feature["score"] for feature in self.features.values()]
return sum(scores) / len(scores)阿里通义千问
平台概述
python
class AlibabaTongyiQianwen:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
def chat(self, messages: List[Dict],
model: str = "qwen-max") -> Dict:
import requests
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"input": {
"messages": messages
}
}
response = requests.post(
self.base_url,
json=payload,
headers=headers
)
return response.json()
def stream_chat(self, messages: List[Dict],
model: str = "qwen-max"):
import requests
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"input": {
"messages": messages
},
"parameters": {
"incremental_output": True
}
}
response = requests.post(
self.base_url,
json=payload,
headers=headers,
stream=True
)
for line in response.iter_lines():
if line:
yield line.decode("utf-8")平台特点
python
class AlibabaPlatformFeatures:
def __init__(self):
self.features = {
"model_variety": {
"description": "模型多样性",
"models": [
"Qwen-Max",
"Qwen-Plus",
"Qwen-Turbo",
"Qwen-Long",
"Qwen-VL"
],
"score": 5
},
"performance": {
"description": "性能表现",
"metrics": {
"response_time": "< 1s",
"accuracy": "高",
"context_length": "100K"
},
"score": 4
},
"cost": {
"description": "成本",
"pricing": {
"Qwen-Max": "0.04元/千tokens",
"Qwen-Plus": "0.008元/千tokens",
"Qwen-Turbo": "0.003元/千tokens"
},
"score": 5
},
"ecosystem": {
"description": "生态支持",
"features": [
"SDK支持",
"API文档完善",
"社区活跃",
"企业级支持"
],
"score": 5
},
"compliance": {
"description": "合规性",
"certifications": [
"ISO27001",
"等保三级",
"数据本地化"
],
"score": 5
}
}
def get_feature(self, feature_name: str) -> Dict:
return self.features.get(feature_name, {})
def get_all_features(self) -> Dict:
return self.features
def calculate_overall_score(self) -> float:
scores = [feature["score"] for feature in self.features.values()]
return sum(scores) / len(scores)腾讯混元
平台概述
python
class TencentHunyuan:
def __init__(self, secret_id: str, secret_key: str):
self.secret_id = secret_id
self.secret_key = secret_key
self.base_url = "https://hunyuan.tencentcloudapi.com"
def chat(self, messages: List[Dict],
model: str = "hunyuan-pro") -> Dict:
import requests
import json
import time
import hashlib
import hmac
timestamp = int(time.time())
payload = {
"Model": model,
"Messages": messages
}
payload_str = json.dumps(payload)
hashed = hashlib.sha256(payload_str.encode("utf-8")).hexdigest()
authorization = self._generate_authorization(
timestamp,
hashed
)
headers = {
"Authorization": authorization,
"Content-Type": "application/json",
"Host": "hunyuan.tencentcloudapi.com",
"X-TC-Timestamp": str(timestamp),
"X-TC-Action": "ChatCompletions",
"X-TC-Version": "2023-09-01"
}
response = requests.post(
f"{self.base_url}/",
json=payload,
headers=headers
)
return response.json()
def _generate_authorization(self, timestamp: int,
hashed_payload: str) -> str:
import hmac
import hashlib
date = time.strftime("%Y-%m-%d", time.gmtime(timestamp))
credential_scope = f"{date}/hunyuan/tc3_request"
string_to_sign = f"TC3-HMAC-SHA256\n{timestamp}\n{date}/hunyuan/tc3_request\n{hashed_payload}"
secret_date = hmac.new(
self.secret_key.encode("utf-8"),
date.encode("utf-8"),
hashlib.sha256
).digest()
secret_service = hmac.new(
secret_date,
"hunyuan".encode("utf-8"),
hashlib.sha256
).digest()
secret_signing = hmac.new(
secret_service,
"tc3_request".encode("utf-8"),
hashlib.sha256
).digest()
signature = hmac.new(
secret_signing,
string_to_sign.encode("utf-8"),
hashlib.sha256
).hexdigest()
authorization = f"TC3-HMAC-SHA256 Credential={self.secret_id}/{credential_scope}, SignedHeaders=content-type;host;x-tc-timestamp;x-tc-action;x-tc-version, Signature={signature}"
return authorization平台特点
python
class TencentPlatformFeatures:
def __init__(self):
self.features = {
"model_variety": {
"description": "模型多样性",
"models": [
"Hunyuan-Pro",
"Hunyuan-Standard",
"Hunyuan-Lite",
"Hunyuan-Role"
],
"score": 4
},
"performance": {
"description": "性能表现",
"metrics": {
"response_time": "< 1s",
"accuracy": "高",
"context_length": "32K"
},
"score": 4
},
"cost": {
"description": "成本",
"pricing": {
"Hunyuan-Pro": "0.1元/千tokens",
"Hunyuan-Standard": "0.06元/千tokens",
"Hunyuan-Lite": "0.01元/千tokens"
},
"score": 4
},
"ecosystem": {
"description": "生态支持",
"features": [
"SDK支持",
"API文档完善",
"社区活跃",
"企业级支持"
],
"score": 4
},
"compliance": {
"description": "合规性",
"certifications": [
"ISO27001",
"等保三级",
"数据本地化"
],
"score": 5
}
}
def get_feature(self, feature_name: str) -> Dict:
return self.features.get(feature_name, {})
def get_all_features(self) -> Dict:
return self.features
def calculate_overall_score(self) -> float:
scores = [feature["score"] for feature in self.features.values()]
return sum(scores) / len(scores)智谱AI(ChatGLM)
平台概述
python
class ZhipuAIChatGLM:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
def chat(self, messages: List[Dict],
model: str = "glm-4") -> Dict:
import requests
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": messages
}
response = requests.post(
self.base_url,
json=payload,
headers=headers
)
return response.json()
def stream_chat(self, messages: List[Dict],
model: str = "glm-4"):
import requests
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": messages,
"stream": True
}
response = requests.post(
self.base_url,
json=payload,
headers=headers,
stream=True
)
for line in response.iter_lines():
if line:
yield line.decode("utf-8")平台特点
python
class ZhipuAIPlatformFeatures:
def __init__(self):
self.features = {
"model_variety": {
"description": "模型多样性",
"models": [
"GLM-4",
"GLM-4-Air",
"GLM-4-Flash",
"GLM-3-Turbo",
"GLM-4V"
],
"score": 5
},
"performance": {
"description": "性能表现",
"metrics": {
"response_time": "< 1s",
"accuracy": "高",
"context_length": "128K"
},
"score": 5
},
"cost": {
"description": "成本",
"pricing": {
"GLM-4": "0.1元/千tokens",
"GLM-4-Air": "0.01元/千tokens",
"GLM-4-Flash": "0.0001元/千tokens"
},
"score": 5
},
"ecosystem": {
"description": "生态支持",
"features": [
"SDK支持",
"API文档完善",
"社区活跃",
"企业级支持"
],
"score": 4
},
"compliance": {
"description": "合规性",
"certifications": [
"ISO27001",
"等保三级",
"数据本地化"
],
"score": 5
}
}
def get_feature(self, feature_name: str) -> Dict:
return self.features.get(feature_name, {})
def get_all_features(self) -> Dict:
return self.features
def calculate_overall_score(self) -> float:
scores = [feature["score"] for feature in self.features.values()]
return sum(scores) / len(scores)平台对比
综合对比
python
class DomesticPlatformComparator:
def __init__(self):
self.platforms = {
"baidu": {
"name": "百度文心一言",
"features": BaiduPlatformFeatures()
},
"alibaba": {
"name": "阿里通义千问",
"features": AlibabaPlatformFeatures()
},
"tencent": {
"name": "腾讯混元",
"features": TencentPlatformFeatures()
},
"zhipu": {
"name": "智谱AI",
"features": ZhipuAIPlatformFeatures()
}
}
def compare_platforms(self) -> Dict:
comparison = {}
for platform_id, platform_info in self.platforms.items():
features = platform_info["features"]
comparison[platform_id] = {
"name": platform_info["name"],
"overall_score": features.calculate_overall_score(),
"features": features.get_all_features()
}
return comparison
def compare_by_feature(self, feature_name: str) -> Dict:
comparison = {}
for platform_id, platform_info in self.platforms.items():
features = platform_info["features"]
comparison[platform_id] = {
"name": platform_info["name"],
"feature": features.get_feature(feature_name)
}
return comparison
def rank_platforms(self) -> List[Dict]:
comparison = self.compare_platforms()
ranked = sorted(
comparison.items(),
key=lambda x: x[1]["overall_score"],
reverse=True
)
return [
{
"platform_id": platform_id,
**platform_info
}
for platform_id, platform_info in ranked
]
def generate_comparison_report(self) -> str:
comparison = self.compare_platforms()
ranked = self.rank_platforms()
report = f"""
国内AI平台对比报告
平台排名:
"""
for i, platform in enumerate(ranked, 1):
report += f"""
{i}. {platform['name']} - 综合得分: {platform['overall_score']:.2f}
"""
report += """
详细对比:
"""
for platform_id, platform_info in comparison.items():
report += f"""
{platform_info['name']}:
- 综合得分: {platform_info['overall_score']:.2f}
- 模型多样性: {platform_info['features']['model_variety']['score']}
- 性能表现: {platform_info['features']['performance']['score']}
- 成本: {platform_info['features']['cost']['score']}
- 生态支持: {platform_info['features']['ecosystem']['score']}
- 合规性: {platform_info['features']['compliance']['score']}
"""
return report实践练习
练习1:调用百度文心一言
python
def call_baidu_ernie(api_key, secret_key, messages):
client = BaiduERNIEBot(api_key, secret_key)
response = client.chat(messages, model="ernie-bot-4")
return response练习2:调用阿里通义千问
python
def call_alibaba_qwen(api_key, messages):
client = AlibabaTongyiQianwen(api_key)
response = client.chat(messages, model="qwen-max")
return response练习3:对比国内平台
python
def compare_domestic_platforms():
comparator = DomesticPlatformComparator()
comparison = comparator.compare_platforms()
ranked = comparator.rank_platforms()
report = comparator.generate_comparison_report()
return comparison, ranked, report总结
本节我们学习了国内平台深度对比(上):
- 百度文心一言平台
- 阿里通义千问平台
- 腾讯混元平台
- 智谱AI(ChatGLM)平台
- 平台特点对比
国内平台各有优势,需要根据具体需求选择。
