Software Engineer Encyclopedia
0%
Domain 11 · LLM Engineering & AI Integration · Topic 11.3

دمج AI داخل ASP.NET Core باحتراف

AI Integration with .NET

Clean Architecture, Microsoft.Extensions.AI, IChatClient, structured output, tools, RAG, security and observability.

  • Advanced
  • ~18 min read
  • 20 sections
  • 18 code examples
  • 1 diagrams
  • 9 questions
  • Priority L2 · Essential
  • .NET 10+ · Microsoft.Extensions.AI · ASP.NET Core

بعد الدرس ده هتقدر

  • تقسّم المسؤوليات بين .NET backend وخدمة Python AI وتبرر التقسيم.
  • تبني inference service بـ FastAPI بـ contract واضح ونسخة موديل في كل رد.
  • تستهلكها من .NET بـ timeouts وretries وcircuit breaker وfallback.
  • تستخدم IChatClient للـ structured output والـ streaming مع validation.

المتطلبات قبل ما تبدأ

Backend بـ .NET + أساسيات الـ ML والـ embeddings من المجال 10.

مستوى التعمق المطلوب

PRACTICAL, AFTER FOUNDATIONSBuild reliable integrations and guardrails before pursuing advanced AI infrastructure.

01

مكان AI في Clean Architecture

Keep domain logic independent from providers
Deep dive

في ‎.NET، لا تجعل Controller يستدعي provider SDK مباشرة. صمم application abstraction مثل IAssistantService أو استخدم IChatClient abstraction من Microsoft.Extensions.AI خلف application service. Infrastructure تحتوي provider configuration، secrets، HTTP transport، retries، telemetry. Domain لا يعرف OpenAI أو Azure OpenAI.

الـ API يستقبل request validated، يطبق authorization/tenant policy، يحدد budget، يبني context، يستدعي AI service، يتحقق من output، ثم يرجع DTO. لا تسمح للنموذج بكتابة SQL أو تعديل domain state دون tool boundary وسياسات مستقلة.

C#Keep domain logic independent from providers
public sealed record AskRequest(string Question);
public sealed record GroundedAnswer(string Answer, IReadOnlyList<string> Citations);

public interface IKnowledgeAssistant
{
    Task<GroundedAnswer> AskAsync(
        string question, string tenantId, CancellationToken cancellationToken);
}

// Controller depends on IKnowledgeAssistant, not a vendor SDK.

AI Application Boundary in Clean Architecture

في ‎.NET، اجعل Application layer تعرف use-case abstraction مثل IAnswerGenerator أو IChatClient حسب مستوى coupling المقبول، واجعل provider configuration و HTTP clients و telemetry في Infrastructure/Composition Root. Domain لا يعرف vendor SDK ولا prompt transport. Application تنسق authorization و retrieval و policy و output validation.

لا تبالغ في abstraction: interface عامة جدًا مثل Generate(string) تخفي streaming/tools/usage. صمم capability-specific ports أو استخدم Microsoft.Extensions.AI abstractions مع adapter عند الحاجة. اجعل model capabilities صريحة حتى لا تعتمد feature على model لا يدعمها.

C#Keep provider details out of domain logic
public interface IAnswerGenerator
{
    Task<AnswerResult> GenerateAsync(
        AnswerRequest request,
        CancellationToken cancellationToken);
}

public sealed record AnswerRequest(string Question, string TenantId);
public sealed record AnswerResult(string Text, IReadOnlyList<string> EvidenceIds);
02

Microsoft.Extensions.AI و IChatClient

Provider abstraction, DI and middleware
Practical

Microsoft.Extensions.AI يقدم abstractions مثل IChatClient و IEmbeddingGenerator لتوحيد طريقة استهلاك chat/embedding providers. ده يسهل testing و provider swaps و middleware، لكنه لا يلغي اختلاف capabilities أو model semantics بين providers. تحقق من feature support مثل tools، multimodal، structured output، streaming، embeddings dimensions.

سجّل client عبر DI، خزّن keys في secret store، واستخدم named/configured clients. لا تخلط API keys في source code أو frontend. راجع package versions و preview labels قبل اعتمادها في production.

C#Provider abstraction, DI and middleware
// Conceptual registration: exact provider package/config depends on provider.
// builder.Services.AddChatClient(providerSpecificClient)
//     .UseOpenTelemetry()
//     .UseLogging();
// Application services consume IChatClient through DI.

// Keep provider-specific setup in Infrastructure/CompositionRoot.
03

Requests و Structured Output و Validation

Treat model output as untrusted input
Practical

حدد max input/output، message roles، timeout، cancellation token، و response format. Structured output/JSON schema يقلل format drift، لكنه لا يضمن business correctness. Deserialize إلى DTO ثم validate invariants و allowlists. عند malformed output، تعامل مع failure typed بدل محاولة تنفيذ النص.

لا تجعل response model يحدد price أو permission أو account owner. هذه قيم مصدرها DB/domain. لو النموذج اقترح action، اعتبره command proposal يحتاج authorization والتحقق وربما approval.

C#Treat model output as untrusted input
public sealed record RefundProposal(
    Guid OrderId,
    decimal RequestedAmount,
    string Reason);

static void ValidateProposal(RefundProposal proposal, decimal orderTotal)
{
    if (proposal.OrderId == Guid.Empty) throw new ValidationException("OrderId required");
    if (proposal.RequestedAmount <= 0 || proposal.RequestedAmount > orderTotal)
        throw new ValidationException("Refund amount is outside allowed range");
}
04

Streaming و Tool Calling و Background Work

Build interactive but bounded AI flows
Practical

Streaming يحسن perceived latency عبر إرسال chunks إلى client باستخدام SSE أو SignalR. لا يعني أن كل chunk صالح أو أن المستخدم حصل على final answer؛ صمم cancellation، disconnect handling، partial response semantics، و final completion event. لا تسجل كل token إذا كان ذلك يسرب PII.

Tool calling هو proposal من النموذج لاستدعاء function. نفّذ tool registry allowlisted، schema validation، user/tenant authorization، timeout، idempotency، audit، و approval للعمليات الحساسة. المهام الطويلة يجب أن تدخل queue مع job status بدل إبقاء HTTP request مفتوحًا.

C#Build interactive but bounded AI flows
public sealed record ToolCall(string Name, JsonElement Arguments);

public async Task<ToolResult> ExecuteToolAsync(
    ToolCall call, UserContext user, CancellationToken ct)
{
    if (!AllowedTools.Contains(call.Name))
        throw new SecurityException("Tool is not allowed");

    var args = ValidateToolArguments(call.Name, call.Arguments);
    await authorization.DemandAsync(user, call.Name, args, ct);
    return await dispatcher.ExecuteAsync(call.Name, args, ct);
}
05

Timeouts و Retries و Rate Limits و Fallbacks

Reliable provider calls
Deep dive

اضبط timeout أقل من request budget الإجمالي. Retry فقط للأخطاء المؤقتة مع exponential backoff + jitter واحترام Retry-After. لا تعِد محاولة non-idempotent tool execution بلا idempotency key. Rate limit داخليًا حسب tenant/user، وليس provider limit فقط. Circuit breaker يحمي التطبيق عند تدهور provider، و fallback model يجب أن يمر بنفس security/eval gates.

ضع token budgets و max context و per-user quotas. Cache النتائج فقط عندما semantics والخصوصية تسمحان، مع key يتضمن tenant، prompt/model version، context fingerprint، و authorization scope.

Timeouts, Retries, Rate Limits and Resilience

LLM call remote dependency: ضع connect/request timeout، cancellation propagation، concurrency limit، queue bound، و per-tenant budget. Retry فقط transient failures وبـbounded attempts و exponential backoff + jitter، واحترم Retry-After عند 429. لا retry على validation/auth errors. POST generation قد يستهلك التكلفة حتى لو client timeout؛ لا تفترض أن timeout يعني provider لم ينفذ.

Idempotency في generation قد لا تضمن نفس output، لكنها قد تمنع duplicate workflow billing/action حسب provider support. سجل operation ID و provider request ID و model ID. Circuit breaker يحمي downstream لكن fallback يجب أن يكون صريحًا ولا يقدم stale answer كأنه fresh.

C#LLM providers are remote dependencies
// Illustrative policy shape; configure actual library/version in the host.
var timeout = TimeSpan.FromSeconds(30);
var maxAttempts = 3;
// Retry only transient 429/5xx/network failures, with exponential backoff + jitter.
// Propagate HttpContext.RequestAborted into every provider/tool call.
// Enforce a separate semaphore/queue limit for expensive model operations.
06

RAG و Embeddings و Vector Stores

Ground answers in authorized evidence
Deep dive

RAG pipeline: query normalization/rewrite → authorization filters → lexical/vector retrieval → fusion → rerank → context packing → generation → citation validation. Embedding model و index dimensions وال metric لازم متوافقين. Hybrid search يجمع keyword search و vector search؛ reranking يعيد ترتيب candidates باستخدام model أدق لكنه يزيد latency/cost.

Vector store خياراته تشمل pgvector و Azure AI Search و Qdrant و Redis؛ الاختيار يعتمد على existing platform، filtering، scale، operations، hybrid features، backup، multi-tenancy. لا تعتبر similarity score probability للصحة. citations يجب أن ترتبط بالمقاطع التي استرجعتها فعلًا.

07

Privacy و Prompt Injection و Human Review

Security boundaries for production AI
Pitfalls

اعمل data classification قبل إرسال النص لمزود خارجي. Redact PII حيث يلزم، حدد retention و region و provider terms، ولا تضع secrets في prompts أو logs. Tool outputs و retrieved documents untrusted. استخدم least privilege، authorization في backend، allowlists، output validation، sandboxing، و human approval للقرارات المالية أو destructive actions.

Human review ليست زرًا شكليًا؛ يجب أن تعرض evidence، action preview، identity، reason، expiration، و audit trail. افصل recommendation عن execution، واجعل رفض الإنسان أو timeout يوقف العملية بأمان.

08

Observability و Testing و Cost per Task

Ship AI as a production capability
Practical

سجّل trace عبر API → retrieval → embedding → model → tool، مع latency لكل span، token usage، model/prompt version، retrieval IDs، result status. لا تسجل raw prompt/response تلقائيًا؛ استخدم redaction و sampling وسياسة access. Metrics: success rate، timeout/rate-limit، p95 latency، tokens، cost، citation coverage، refusal، tool errors.

اختبر provider contract، mock clients، golden prompts، RAG retrieval quality، injection cases، concurrency، cancellation، و fallback. ضع regression eval في CI، و runbook عند provider outage أو cost spike.

هل IChatClient وحده يجعل التكامل production-ready؟
لا. هو abstraction مفيد، لكنك ما زلت تحتاج authorization و validation و timeouts و budgets و observability و evaluation و security controls.
09

Reference Architecture: ASP.NET Core + Python Worker + RAG

One coherent end-to-end bridge
Deep dive

Architecture مقترحة: Angular/mobile → ASP.NET Core API (identity, tenant, quotas) → Application orchestration → IChatClient provider abstraction. Document upload يذهب إلى object storage ثم queue؛ Python worker ينفذ parsing/chunking/embeddings ويكتب index. Retrieval يتم عبر service يطبق ACL من مصدر موثوق. AI response يرجع citations و trace ID. ‎.NET يحتفظ business data و transactional truth؛ Python يملك compute/data-science worker responsibilities المحددة.

لا تجعل كل سؤال يمر عبر Python إذا كان ‎.NET قادرًا على orchestration. ولا تجعل worker يقرأ قاعدة business مباشرة دون contract. استخدم outbox عند نشر ingestion job بعد DB commit، و idempotency key للـ document version.

C#One coherent end-to-end bridge
// .NET application flow (conceptual)
var user = await currentUser.GetAsync(ct);
await quotas.DemandAsync(user.TenantId, "rag.ask", ct);
var evidence = await retrieval.SearchAuthorizedAsync(user, request.Question, ct);
var answer = await assistant.GenerateGroundedAsync(request.Question, evidence, ct);
await citations.ValidateAsync(user, answer.Citations, ct);
return Results.Ok(answer);
أي طبقة تملك قرار صلاحية قراءة المستند؟
Backend retrieval/application authorization قبل إدخال النص إلى prompt، وليس النموذج ولا prompt.
10

Testing Strategy: Mock, Contract, Integration, Eval

Different tests catch different failures
Practical

Unit tests تختبر domain policies و budget logic و output validators دون provider. Contract tests تتحقق من JSON/API schemas بين ‎.NET و Python. Integration tests تشغل vector store/queue عند الإمكان. Provider smoke tests صغيرة ومحدودة التكلفة تتحقق من credentials/connectivity. Eval tests تقيس quality على golden set ولا تستبدل unit tests.

لا تجعل CI يستدعي provider بمئات الطلبات في كل commit. استخدم deterministic fake client لمعظم الاختبارات، وجدولة provider eval، وسجل تكلفة الاختبارات. اختبر cancellation و timeout و rate-limit و malformed structured output و provider outage.

11

الرسم المعماري: ‎.NET هو المنتج و Python هو عامل البيانات

The .NET–Python–LLM bridge
Deep dive

الرسم يوضح فصل المسؤوليات: ‎.NET يملك الهوية والـ business policy، والـ queue تفصل ingestion الطويل، و Python worker يعالج المستندات، والـ retrieval يطبق ACL قبل بناء السياق، ثم IChatClient يتصل بمزود النموذج. لا تجعل الـ LLM مصدر الحقيقة للطلبات أو الصلاحيات.

Angular / AppUserASP.NET CoreIdentity · TenantPolicy · BudgetsOrchestrationQueueIngestion jobsPython WorkerParse · Chunk · EmbedVector / SearchACL-filtered indexIChatClientProvider abstraction
Reference architecture: trusted ‎.NET orchestration with isolated Python ingestion and retrieval

الأسهم في الرسم تبين اتجاهات عامة وليست بروتوكولًا إلزاميًا. قد يكون retrieval داخل ‎.NET أو خدمة مستقلة، وقد يكون worker Python منفصلًا أو job داخليًا حسب الحاجة. ابدأ بأقل عدد خدمات يحقق المتطلبات.

12

AI Endpoint Abuse Controls

Protect quotas, data and spend
Pitfalls

AI endpoints معرضة لـ denial-of-wallet: requests ضخمة، loops، prompt stuffing، repeated retries، uploads كبيرة، أو tool fan-out. طبّق auth قبل أي provider call، quotas per tenant/user، max input tokens، max output، concurrency semaphore، queue caps، upload limits، و budget circuit breaker. لا تعتمد على rate limiting بالـ IP فقط في multi-tenant SaaS.

اجعل cancellation تنتقل إلى provider حيث يدعم، وأوقف downstream work عند client disconnect إذا لم تعد له قيمة. أضف anomaly alerts للتكلفة والـ tokens. أخفِ provider error details عن المستخدم وسجل safe diagnostics داخليًا.

13

Structured Output Failure Recovery

Never trust a JSON-shaped answer blindly
Practical

حتى schema-constrained generation قد يفشل بسبب refusal، truncation، provider incompatibility، أو semantic invalidity. ميّز بين transport error و refusal و parse error و validation error. لا تعِد الطلب بلا حدود؛ retry واحد بإصلاح محدد قد يكون مقبولًا لبعض الحالات، وإلا اطلب clarification أو ارجع typed failure.

لا تستخدم fallback parser يتجاهل required fields أو يملأ قيمًا حساسة تلقائيًا. سجّل schema version و model ID و finish reason و validation errors دون تسريب raw PII.

14

معمارية ‎.NET + Python: مين مسؤول عن إيه

Responsibility split between the .NET backend and a Python AI service
Deep dive

السؤال اللي بيتكرر: «أكتب الـ AI في ‎.NET ولا أعمل خدمة Python؟». الإجابة مش ولاء للغة — هي إن كل جزء يعيش في المكان اللي الـ ecosystem بتاعه أقوى فيه، وإن الحد بينهم يكون API واضح.

المسؤولية‎.NET backendPython AI service
هوية المستخدم، الصلاحيات، الـ tenantهنا دايمًابيستقبل سياق موثوق من الـ backend، مش من الإنترنت
Business rules، transactions، قاعدة البيانات الأساسيةهنالأ
نداء LLM مستضاف (chat، tools، structured output)هنا بـ IChatClient — مفيش داعي لخدمة تانيةاختياري
تشغيل موديل محلي: scikit-learn، PyTorch، embeddings، rerankerممكن بـ ONNX Runtime لو الموديل اتصدّرهنا — المكتبات والأدوات كلها Python
تدريب، feature engineering، تقييملأهنا
Rate limiting، quotas، تكلفة لكل tenant، auditهنابيرجّع الاستهلاك في الرد
Document parsing/OCR/chunking التقيلبيحط job في queueworker هنا
إمتى خدمة Python منفصلة مبرَّرة؟
  • عندك موديل بتشغّله بنفسك (مش API مستضاف) ومكتباته Python.
  • الـ inference محتاج GPU أو scaling مختلف عن الـ API.
  • فريق ML بيطوّر وينشر الموديل بمعدل مختلف عن فريق الـ backend.

لو كل اللي عندك نداءات لـ LLM مستضاف: خليها جوه ‎.NET. خدمة زيادة = network hop + deployment + نقطة فشل، ومن غير مقابل.

15

خدمة الـ Inference بـ FastAPI

Model loaded once, validated contract, model version in every response
Practical
حالة التحقق

أكواد القسم ده والقسم اللي بعده لم تُنفَّذ في بيئة تجهيز الموسوعة (FastAPI والـ ‎.NET SDK مش متاحين هناك). مكتوبة على الـ APIs الموثقة رسميًا؛ شغّلها عندك قبل الاعتماد عليها.

Pythonservice/main.py — FastAPI + Pydantic v2
from contextlib import asynccontextmanager
import joblib
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

MODEL_VERSION = "churn-classifier:14"
state = {}

@asynccontextmanager
async def lifespan(app: FastAPI):
    state["model"] = joblib.load("model.joblib")      # load ONCE at startup, never per request
    yield
    state.clear()

app = FastAPI(lifespan=lifespan)

class PredictRequest(BaseModel):
    tenure_months: int = Field(ge=0, le=600)
    monthly_charge: float = Field(gt=0, lt=100_000)
    support_tickets: int = Field(ge=0, le=1000)
    plan: str = Field(pattern="^(basic|plus|pro)$")

class PredictResponse(BaseModel):
    churn_probability: float
    model_version: str

@app.post("/v1/predict", response_model=PredictResponse)
def predict(req: PredictRequest) -> PredictResponse:   # sync def: FastAPI runs it in a threadpool,
    model = state.get("model")                         # so CPU-bound inference does not block the event loop
    if model is None:
        raise HTTPException(503, "model not loaded")
    import pandas as pd
    proba = float(model.predict_proba(pd.DataFrame([req.model_dump()]))[0, 1])
    return PredictResponse(churn_probability=proba, model_version=MODEL_VERSION)

@app.get("/health/ready")
def ready():
    if "model" not in state:
        raise HTTPException(503, "model not loaded")
    return {"status": "ready", "model_version": MODEL_VERSION}

الـ contract هو الـ Pydantic model: أي request برا الحدود بيترفض بـ 422 قبل ما يوصل للموديل. الموديل اللي بياخد قيمة برا نطاق التدريب بيرجّع رقم شكله طبيعي ومعناه غلط — الرفض أحسن.

model_version في كل رد: الـ backend بيسجلها مع كل توقع. لما حد يسأل «ليه العميل ده اتصنف كده يوم 3؟» تقدر تعرف أنهي نسخة ردّت.

الخدمة دي مش على الإنترنت: بتتكلم مع الـ backend بس (private network أو mTLS). مفيش فيها authentication مستخدمين ولا business rules.

16

الـ Backend: Typed Client بـ Resilience، و LLM بـ IChatClient

Timeouts, retries, circuit breaker and a fallback; structured output and streaming
Practical
C#Program.cs — registering the prediction client (Microsoft.Extensions.Http.Resilience)
builder.Services
    .AddHttpClient<PredictionClient>(c => c.BaseAddress = new Uri(builder.Configuration["Prediction:BaseUrl"]!))
    .AddStandardResilienceHandler(o =>
    {
        o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);        // one try
        o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(5);   // all tries together
        o.Retry.MaxRetryAttempts = 2;                              // exponential backoff + jitter by default
        o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30);
    });
C#PredictionClient.cs — the failure mode is part of the return type
public sealed record ChurnPrediction(double Probability, string ModelVersion);

public sealed class PredictionClient(HttpClient http, ILogger<PredictionClient> log)
{
    public async Task<ChurnPrediction?> PredictAsync(CustomerFeatures features, CancellationToken ct)
    {
        try
        {
            using var response = await http.PostAsJsonAsync("/v1/predict", features, ct);
            if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
            {
                log.LogWarning("Prediction rejected the payload: contract drift between services?");
                return null;                                       // retrying a 422 never helps
            }
            response.EnsureSuccessStatusCode();
            var dto = await response.Content.ReadFromJsonAsync<PredictResponseDto>(ct);
            return dto is null ? null : new ChurnPrediction(dto.ChurnProbability, dto.ModelVersion);
        }
        catch (Exception ex) when (ex is HttpRequestException or TimeoutRejectedException or BrokenCircuitException)
        {
            log.LogWarning(ex, "Prediction service unavailable");
            return null;                                           // caller decides the fallback
        }
    }

    private sealed record PredictResponseDto(
        [property: JsonPropertyName("churn_probability")] double ChurnProbability,
        [property: JsonPropertyName("model_version")] string ModelVersion);
}

null مش exception: وقوع خدمة الـ ML حدث متوقع، فالـ caller لازم يتعامل معاه صراحةً: يعرض الصفحة من غير الـ score، أو يستخدم قاعدة بسيطة، أو يأجّل. الـ API الأساسي ما يقعش عشان feature مساعدة وقعت.

الـ retry على عمليات آمنة بس: الـ predict قراءة بحتة فإعادتها آمنة. لو الخدمة بتعمل side effect لازم idempotency key.

الـ timeouts متداخلة: محاولة واحدة 2 ثانية، والكل 5. من غير حد إجمالي، 3 محاولات × timeout طويل = request معلّق والـ threads بتخلص.

نداء LLM من جوه الـ backend

C#Structured output + streaming with Microsoft.Extensions.AI
// Registration: the rest of the app depends on IChatClient, not on a provider SDK.
builder.Services
    .AddChatClient(sp => providerChatClient)        // e.g. an OpenAI / Azure OpenAI client adapted with .AsIChatClient()
    .UseOpenTelemetry()                             // traces + token usage metrics
    .UseFunctionInvocation();

public sealed record TicketTriage(string Category, int Priority, string Summary);

app.MapPost("/tickets/triage", async (TriageRequest req, IChatClient chat, CancellationToken ct) =>
{
    ChatResponse<TicketTriage> response = await chat.GetResponseAsync<TicketTriage>(
        [new(ChatRole.System, "Classify the support ticket. Category is one of: billing, bug, account. Priority is 1-3."),
         new(ChatRole.User, req.Text)],
        new ChatOptions { Temperature = 0 },
        cancellationToken: ct);

    if (!response.TryGetResult(out TicketTriage? triage) || triage.Priority is < 1 or > 3)
        return Results.Problem("The model returned an invalid triage result.", statusCode: 502);

    return Results.Ok(new { triage, usage = response.Usage });   // log usage per tenant for cost control
});

app.MapPost("/chat/stream", (ChatRequest req, IChatClient chat, CancellationToken ct) =>
{
    async IAsyncEnumerable<string> Stream()
    {
        await foreach (ChatResponseUpdate update in chat.GetStreamingResponseAsync(req.Message, cancellationToken: ct))
            yield return update.Text;               // ct is cancelled when the browser disconnects => generation stops
    }
    return Stream();
});

الـ schema مش validation كاملة: الـ structured output بيضمن الشكل (حقول وأنواع). القيود اللي الـ schema ما يعبّرش عنها — زي إن الـ priority بين 1 و3 أو إن الـ category موجودة فعلًا عندك — لازم تتأكد منها في الكود، زي أي input جاي من برا.

الـ CancellationToken هو التحكم في التكلفة: لو المستخدم قفل الصفحة والـ token ما اتمررش، الموديل هيكمّل يولّد وتدفع تمن رد محدش هيقرأه.

502 مش 500: العطل في upstream (الموديل) مش في كودك — وده بيفرق في الـ alerting.

خدمة الـ ML بتاخد 30 ثانية ترد أحيانًا. إيه أخطر نتيجة لو الـ HttpClient من غير timeout؟

17

اختبر فهمك

Knowledge Check
Practical
هل tool call من النموذج يعني أن المستخدم مخول بتنفيذه؟
لا. backend يجب أن يتحقق من identity والصلاحيات والـ arguments قبل التنفيذ.
لماذا لا نسجل كل prompt/response في production logs؟
قد تحتوي PII أو أسرارًا أو بيانات عميل؛ استخدم redaction و metadata و sampling وسياسات وصول.

اختبار الإتقان المهني

أين يجب أن يعيش provider-specific SDK في Clean Architecture؟
في Infrastructure خلف adapter/port، وليس في Domain أو business rules.
لماذا لا يعني HTTP timeout أن provider لم ينفذ الطلب؟
لأن التنفيذ قد يستمر بعد انقطاع العميل؛ يلزم reconciliation/request IDs وسياسة retry واعية بالتكلفة.
ما الذي يجب أن يفعله streaming endpoint عند client disconnect؟
يمرر cancellation إلى provider/tools ويوقف العمل ويحرر الموارد بدل الاستمرار دون مستهلك.
18

Streaming and Backpressure Across ASP.NET Core

A stream is a resource with a lifecycle
Deep dive

Streaming improves perceived latency but changes cancellation, error, و proxy behavior. في ASP.NET Core استخدم async enumeration/response streaming مع RequestAborted. لا تجمع كل tokens في memory قبل إرسالها إذا كان هدفك streaming. ضع heartbeat/flush strategy حسب protocol، وتعامل مع disconnects، partial outputs، و provider errors after headers have started.

Backpressure مهم: لو client بطيء، لا تسمح بتراكم unbounded channel. استخدم bounded channel وقراءة/كتابة async، وحدد max stream duration و max output tokens. لا تسجل full sensitive output تلقائيًا.

C#A stream is a resource with a lifecycle
// Pattern sketch for an async token stream
// await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, ct))
// {
//     ct.ThrowIfCancellationRequested();
//     await response.WriteAsync(Serialize(update), ct);
//     await response.Body.FlushAsync(ct);
// }
// Catch cancellation separately; never claim completion after a partial stream.
19

Observability, Tracing and Cost Attribution

Trace one user request across the AI pipeline
Deep dive

Trace يجب أن يربط HTTP request بـ retrieval، reranking، prompt assembly، model call، tool calls، و response validation. سجّل latency لكل stage، token usage، model/provider، prompt version، retrieval IDs/scores، retry count، و outcome. لا تسجل raw prompt/document content افتراضيًا؛ استخدم redaction و sampling وسياسة retention.

Cost attribution يحتاج tenant/use-case/model tags، مع cardinality controls في metrics. لا تضع user IDs أو document IDs كـ metric labels عالية cardinality؛ استخدم trace/log attributes محمية. اعمل dashboards لـ p50/p95، error rate، 429، tokens/request، cost/success، و fallback rate.

C#Trace one user request across the AI pipeline
public sealed record AiUsage(
    string Provider,
    string Model,
    int InputTokens,
    int OutputTokens,
    string PromptVersion,
    TimeSpan Duration);

// Emit structured telemetry; redact content and avoid high-cardinality metric labels.
20

معمل ‎.NET محلي: Chat و Streaming و Tools و Embeddings

Use Microsoft.Extensions.AI against a local Ollama endpoint
Practical

الأمثلة بتستخدم Microsoft.Extensions.AI كـ abstraction و OllamaSharp كـ adapter محلي. شغّل Ollama ونزّل model مناسب، وبعدها استبدل YOUR_LOCAL_MODEL. مفيش API key؛ الطلب محلي إلى localhost. دعم structured output و tool calling و embeddings يختلف حسب model والـ connector، فاختبر capability المطلوبة.

الرد typed يقلل parsing اليدوي، لكنه مش بديل عن domain validation أو authorization. حط نوع الـ record بعد top-level statements عشان يفضل المثال في شكل Program.cs مستقل.

C#Program.cs — typed chat response
using System;
using Microsoft.Extensions.AI;
using OllamaSharp;

IChatClient chat = new OllamaApiClient(new Uri("http://localhost:11434/"), "YOUR_LOCAL_MODEL");
var response = await chat.GetResponseAsync<TicketTriage>(
    "Classify ticket: The invoice was charged twice. Return category, priority 1-3, and summary.",
    new ChatOptions { Temperature = 0 });
if (!response.TryGetResult(out TicketTriage? result) || result.Priority is < 1 or > 3)
    throw new InvalidOperationException("The model response failed application validation.");
Console.WriteLine($"{result.Category} / {result.Priority}: {result.Summary}");

public sealed record TicketTriage(string Category, int Priority, string Summary);

الـ stream يرسل updates تدريجيًا. في web API مرّر HttpContext.RequestAborted؛ لو العميل فصل لازم يتوقف النداء. لا تبعت JSON chunks قبل تحديد framing واضح للواجهة.

C#Streaming with cancellation
using System;
using System.Threading;
using Microsoft.Extensions.AI;
using OllamaSharp;

IChatClient chat = new OllamaApiClient(new Uri("http://localhost:11434/"), "YOUR_LOCAL_MODEL");
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(45));
await foreach (ChatResponseUpdate update in chat.GetStreamingResponseAsync(
    "Explain why an API validates model output.", cancellationToken: timeout.Token))
    Console.Write(update.Text);

في tool calling، الموديل يطلب function والـ client ينفذها. خلّي الدالة ضيقة وقراءة فقط؛ الـ backend يستخرج user identity من السياق الموثوق ويتحقق من الصلاحيات. لا تعتبر tenant id الذي يقترحه الموديل إثباتًا.

C#Allowlisted read-only function tool
using System;
using System.ComponentModel;
using System.Threading;
using Microsoft.Extensions.AI;
using OllamaSharp;

[Description("Look up the status of a public demo order")]
static string FindOrder([Description("Order identifier")] string orderId) =>
    orderId == "DEMO-100" ? "Packed; expected Friday." : "Order not found.";

IChatClient client = new OllamaApiClient(new Uri("http://localhost:11434/"), "YOUR_TOOL_CAPABLE_LOCAL_MODEL");
client = ChatClientBuilderChatClientExtensions.AsBuilder(client).UseFunctionInvocation().Build();
var options = new ChatOptions { Tools = [AIFunctionFactory.Create(FindOrder)] };
var answer = await client.GetResponseAsync("Check order DEMO-100.", options, CancellationToken.None);
Console.WriteLine(answer);

والـ embeddings مسار منفصل غالبًا عن chat. ثبّت embedding model وإصداره وأبعاده مع الـ index؛ عند تغييره أعد embeddings وما تخلطش vectors من spaces مختلفة.

C#Generate a local embedding vector
using System;
using Microsoft.Extensions.AI;
using OllamaSharp;

IEmbeddingGenerator<string, Embedding<float>> generator = new OllamaApiClient(
    new Uri("http://localhost:11434/"), "YOUR_LOCAL_EMBEDDING_MODEL");
ReadOnlyMemory<float> vector = await generator.GenerateVectorAsync("Refund requests take five days.");
Console.WriteLine($"dimensions={vector.Length}");
حالة التحقق

الأمثلة فيها imports وبيانات محلية لكنها لم تُنفذ أو تُعمل لها compile في هذه الدفعة. أسماء models لازم تطابق ما حمّلته؛ راجع نسخة package ودعم الـ provider قبل الاستخدام.

Semantic Kernel إمتى يدخل؟

Microsoft.Extensions.AI مناسب لواجهة client موحدة و middleware مثل telemetry و caching. Semantic Kernel يضيف Kernel و plugins وتنظيم prompt/function calls. connector Ollama موصوف في docs كـ prerelease/experimental في بعض المسارات؛ راجع الحالة الحالية.

C#Semantic Kernel with local chat
using System;
using Microsoft.SemanticKernel;

#pragma warning disable SKEXP0070
var builder = Kernel.CreateBuilder();
builder.AddOllamaChatCompletion(
    modelId: "YOUR_LOCAL_MODEL",
    endpoint: new Uri("http://localhost:11434"),
    serviceId: "local");
var kernel = builder.Build();
#pragma warning restore SKEXP0070
var answer = await kernel.InvokePromptAsync(
    "In one sentence, why evaluate retrieval separately from generation?");
Console.WriteLine(answer);
الخيارمناسب لماحدوده
Microsoft.Extensions.AIIChatClient/IEmbeddingGenerator وواجهات ‎.NET موحدة مع middleware.مش orchestrator كامل؛ صلاحيات المنتج و business workflow مسؤولية تطبيقك.
Semantic Kernelتحتاج Kernel و plugins و prompt/function orchestration في ‎.NET.راجع connector والميزات التجريبية؛ plugin لا يمنح المستخدم صلاحية.
LangChainالفريق محتاج ecosystem واسع متعدد اللغات لـ chains/agents.ما تضفش طبقة تشغيل جديدة لمجرد الاسم؛ backend يظل مالك auth و domain rules.
LlamaIndexالمشكلة الأساسية document ingestion/indexing/retrieval.راجع ACL و tenant isolation؛ المكتبة لا تستبدل authorization.

Speech و Image Generation: نفس الحدود، بيانات مختلفة

Speech-to-text يحوّل صوتًا إلى transcript؛ text-to-speech يحوّل النص لصوت؛ real-time voice يجمع المسارين مع streaming. راقب اللهجات والضوضاء واللغة، وطبّق موافقة و retention لأن الصوت قد يكشف هوية أو بيانات حساسة. Image generation يعمل prompt-to-image أو تحرير صورة؛ الناتج ملف غير موثوق يحتاج فحص النوع والحجم قبل العرض.

في backend خلّي العمليات الطويلة asynchronous: ارجع job id، خزّن الناتج بصلاحيات ومدة صلاحية، وسجل model/prompt version و status. قِس latency والتكلفة في region والجهاز المستهدفين. واجهات بعض image/audio capabilities في ‎.NET معلّمة experimental؛ استخدم adapter واختبارات توافق.

تمارين وحلول ومشروع مصغر

أساسي: ارفض Priority خارج 1–3. الحل: افحص record بعد structured output؛ schema لا يطبق كل business rule.

متوسط: اربط tool بمستخدم حالي. الحل: مرّر principal لخدمة application واستخرج user id من claims، ولا تأخذه من prompt أو arguments.

متقدم: بدّل embedding model. الحل: ابنِ index جديدًا keyed بالـ model/version/dimension، قارن recall@k، ثم بدّل alias بعد النجاح.

مشروع: endpoint triage محلي مع typed response و stream و read-only tool و usage log. القبول: invalid result يرجع 502، disconnect يلغي ال stream، ولا توجد secrets في source.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 36 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapLLM APIs§01
RoadmapAPI Keys and Authentication§01
RoadmapRequests and Responses§01
RoadmapStructured Outputs§01
RoadmapTool Calling§01
RoadmapStreaming§01
RoadmapTimeouts and Retries§01
RoadmapRate Limits§01
RoadmapToken Cost§01
RoadmapPrompt Versioning§01
RoadmapOutput Validation§01
RoadmapError Handling§01
RoadmapLogging and Observability§01
RoadmapRetrieval-Augmented Generation (RAG)§05
RoadmapEmbeddings§05
RoadmapVector Search§05
RoadmapRetrieval and Ranking§06
RoadmapChunking§06
RoadmapEvaluation§06
RoadmapPrivacy§06
RoadmapPrompt Injection Defense§06
RoadmapHuman Review for High-Impact Actions§07
SuggestedMicrosoft.Extensions.AI (IChatClient, IEmbeddingGenerator)§02
SuggestedSemantic Kernel / Microsoft Agent Framework awareness§02
SuggestedProvider SDKs: Azure OpenAI, OpenAI, Anthropic, local Ollama§02
SuggestedVector stores: pgvector, Azure AI Search, Qdrant, Redis§02
SuggestedHybrid search (keyword + vector) and reranking§06
SuggestedQuery rewriting§06
SuggestedSemantic caching of answers§05
SuggestedFallback models and circuit breaker for AI calls§05
SuggestedToken counting and per-user budgets§05
SuggestedBackground AI processing through queues§04
SuggestedGolden dataset and regression evals§08
SuggestedPII redaction before calling an LLM§07
SuggestedStreaming to clients with SSE or SignalR§04
SuggestedTraces that include token usage§08

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس