Loading
Loading
Azure OpenAI Service يتيح الوصول إلى نماذج OpenAI (GPT-4) ضمن بنية Azure الآمنة.
import json
from dataclasses import dataclass, field
from typing import List, Dict, Optional
# ─── محاكاة Azure OpenAI SDK ───────────────────────────────
@dataclass
class AzureOpenAIDeployment:
name: str
model: str
capacity: int # 1 capacity unit = 1000 TPM
mode: str = "Standard" # Standard, Provisioned
MODELS_PRICING = {
"gpt-4o": {"in": 0.005, "out": 0.015, "ctx": "128K"},
"gpt-4-turbo": {"in": 0.01, "out": 0.03, "ctx": "128K"},
"gpt-35-turbo": {"in": 0.0005, "out": 0.0015, "ctx": "16K"},
"text-embedding-3-large": {"in": 0.00013, "out": 0, "ctx": "8K"},
}
class AzureOpenAIClient:
"""محاكاة openai.AzureOpenAI SDK"""
def __init__(self, endpoint: str, api_version: str = "2024-02-01"):
self.endpoint = endpoint
self.api_version = api_version
self.deployments: Dict[str, AzureOpenAIDeployment] = {}
self._total_cost = 0.0
self._calls = 0
def create_deployment(self, name: str, model: str, capacity: int = 1):
d = AzureOpenAIDeployment(name, model, capacity)
self.deployments[name] = d
ctx = MODELS_PRICING.get(model, {}).get("ctx", "?")
print(f" ✅ Deployment: {name} ({model}, ctx={ctx})")
return d
def chat(self, deployment: str, messages: List[Dict],
system: str = "", temperature: float = 0.7) -> Dict:
if deployment not in self.deployments:
raise ValueError(f"Deployment '{deployment}' غير موجود")
d = self.deployments[deployment]
mdl = MODELS_PRICING.get(d.model, {"in": 0.01, "out": 0.03})
# محاكاة الرد
last_msg = messages[-1].get("content", "") if messages else ""
response = f"[{d.model}] ردّي على: {last_msg[:55]}..."
in_tok = int(sum(len(m.get("content","").split()) * 1.3 for m in messages))
out_tok = 60
cost = (in_tok / 1000) * mdl["in"] + (out_tok / 1000) * mdl["out"]
self._total_cost += cost
self._calls += 1
return {
"content": response,
"usage": {"prompt_tokens": in_tok, "completion_tokens": out_tok},
"cost_usd": round(cost, 7),
"model": d.model,
"deployment": deployment,
}
def embed(self, deployment: str, text: str) -> List[float]:
"""توليد Embedding"""
import math
# محاكاة embedding 8-dimensional
embed = [math.sin(i * hash(text) % 100 * 0.1) for i in range(8)]
mag = math.sqrt(sum(x**2 for x in embed))
return [x / mag for x in embed]
def cost_summary(self):
total_str = "$" + f"{self._total_cost:.6f}"
print(f"\n📊 ملخص الاستخدام:")
print(f" المكالمات : {self._calls}")
print(f" التكلفة : {total_str}")
# ─── إعداد Azure OpenAI ────────────────────────────────────
print("🔵 Azure OpenAI Service:")
print("=" * 52)
client = AzureOpenAIClient(
endpoint="https://my-openai.openai.azure.com/",
api_version="2024-02-01",
)
print("\n1️⃣ إنشاء Deployments:")
client.create_deployment("gpt4o-prod", "gpt-4o", capacity=10)
client.create_deployment("gpt35-fast", "gpt-35-turbo", capacity=50)
client.create_deployment("embed-large", "text-embedding-3-large", capacity=5)
# ─── استخدام Chat Completions ──────────────────────────────
print(f"\n2️⃣ اختبار Chat Completions:")
convos = [
("gpt4o-prod", "ما هو Azure OpenAI؟ أجب في جملتين"),
("gpt35-fast", "اعطني مثالاً على use case لـ Azure OpenAI"),
("gpt4o-prod", "كيف أختار بين Standard و Provisioned deployments؟"),
]
for dep, msg in convos:
resp = client.chat(dep, [{"role": "user", "content": msg}],
system="أجب بالعربية باختصار")
cost_s = "$" + f"{resp['cost_usd']:.7f}"
print(f"\n [{dep}] {msg[:50]}")
print(f" 💬 {resp['content']}")
print(f" 🔢 {resp['usage']['prompt_tokens']}in+{resp['usage']['completion_tokens']}out | {cost_s}")
# ─── Embeddings ────────────────────────────────────────────
print(f"\n\n3️⃣ Embeddings للبحث الدلالي:")
texts = ["Azure OpenAI للمؤسسات", "AWS Bedrock لـ Amazon", "GCP Vertex AI لـ Google"]
embeddings = {t: client.embed("embed-large", t) for t in texts}
import math
def cosine_sim(a, b):
dot = sum(x*y for x,y in zip(a,b))
norm = math.sqrt(sum(x**2 for x in a)) * math.sqrt(sum(x**2 for x in b))
return dot / norm if norm > 0 else 0.0
query = "خدمة AI سحابية"
q_emb = client.embed("embed-large", query)
print(f" الاستعلام: '{query}'")
for text, emb in embeddings.items():
sim = cosine_sim(q_emb, emb)
bar = "█" * int(sim * 10)
print(f" {sim:.3f} {bar} {text}")
client.cost_summary()
print(f"\n✅ Azure OpenAI Service جاهز!")