# TBIT: एपीआई संदर्भों को आपस में सुलझाने के लिए: टुकड़े - टुकड़े करने के साथ - साथ काम करते रहना

<!--category-- AI, LLM, LLMApi, ASP.NET Core, API, Nuget, mockllmapi, AI-Article-->
<datetime class="hidden">2025-11-05T13:52</datetime>

> ध्यान दीजिए: टी. वी.

# यह बहुत दिलचस्प है तो मैं इसे यहाँ डाल दिया है लेकिन अगर यह आप के लिए एक समस्या है आप इसे नज़रअंदाज़ करें.

परिचय

**जब हम निर्माण और परीक्षण कार्यक्रमों का निर्माण करते हैं, तब पारंपरिक हँसी - ठट्ठा करनेवालों में से एक सबसे बड़ी चुनौतियाँ होती हैं ।**प्रत्येक निवेदन का पूर्ण रूप से बेतरतीब डाटा लौटाता है पिछले कॉल के साथ कोई सम्बन्ध नहीं.

[![यदि आप एक उपयोक्ता को ID3 के साथ लाते हैं, तो उनके आदेश लाते हैं, वहाँ कोई गारंटी नहीं है कि एक ही उपयोगकर्ता आईडी का संदर्भ करेगा.](https://img.shields.io/nuget/v/mostlylucid.mockllmapi.svg)](https://www.nuget.org/packages/mostlylucid.mockllmapi)
[![एपीआई संदर्भ](https://img.shields.io/nuget/dt/mostlylucid.mockllmapi.svg)](https://www.nuget.org/packages/mostlylucid.mockllmapi)

## इस समस्या को हल करने के द्वारा आप अपने ठट्ठों में उड़ाकर याद रख सकते हैं ।[लागू नहीं](https://github.com/scottgal/LLMApi)लागू नहीं

[TOC]

## आप पा सकते हैं

GiHh यहाँ

```mermaid
sequenceDiagram
    participant Client
    participant MockAPI
    participant LLM

    Client->>MockAPI: GET /users/1
    MockAPI->>LLM: Generate user data
    LLM-->>MockAPI: {"id": 42, "name": "Alice"}
    MockAPI-->>Client: User data

    Client->>MockAPI: GET /orders?userId=42
    MockAPI->>LLM: Generate order data
    LLM-->>MockAPI: {"userId": 99, ...}
    MockAPI-->>Client: Order data (userId mismatch!)
```

परियोजना के लिए, सभी सार्वजनिक डोमेन...

## समस्या: राज्यहीन शैम्पस

पारंपरिक नकली एपीआई्स प्रत्येक निवेदन के लिए स्वतंत्र डाटा बनाता है:

```mermaid
sequenceDiagram
    participant Client
    participant MockAPI
    participant Context as Context Manager
    participant LLM

    Client->>MockAPI: GET /users/1?context=session-1
    MockAPI->>Context: Get history for "session-1"
    Context-->>MockAPI: (empty - first call)
    MockAPI->>LLM: Generate user (no context)
    LLM-->>MockAPI: {"id": 42, "name": "Alice"}
    MockAPI->>Context: Store: GET /users/1 → {"id": 42, ...}
    MockAPI-->>Client: User data

    Client->>MockAPI: GET /orders?context=session-1
    MockAPI->>Context: Get history for "session-1"
    Context-->>MockAPI: Previous call: user with id=42, name=Alice
    MockAPI->>LLM: Generate order (with context history)
    LLM-->>MockAPI: {"userId": 42, "customerName": "Alice", ...}
    MockAPI->>Context: Store: GET /orders → {"userId": 42, ...}
    MockAPI-->>Client: Order data (consistent!)
```

समस्या को ध्यान में रखते हुए?

## उपयोक्ता का ID 42 था, लेकिन आदेश उपयोक्ता IId 99 के साथ वापस आया.

### संबंधित कॉल के बीच कोई सुसंगतता नहीं है.

समाधान: कॉन्टेक्स्ट मेमोरी

```mermaid
graph TD
    A[HTTP Request] --> B[ContextExtractor]
    B --> C{Context Name?}
    C -->|Yes| D[OpenApiContextManager]
    C -->|No| E[Generate without context]
    D --> F[Retrieve Context History]
    F --> G[PromptBuilder]
    E --> G
    G --> H[LLM]
    H --> I[Response]
    I --> J{Context Name?}
    J -->|Yes| K[Store in Context]
    J -->|No| L[Return Response]
    K --> L
```

**एपीआई संदर्भों के साथ, सक्रिय एपीआई से संबंधित निवेदनों के दौरान एक साझा संदर्भ बनाए रखता है:**अबLM पिछले उपयोक्ता कॉल को देखता है और आदेश बनाता है कि एक ही उपयोक्ता आईडी और नाम का संदर्भ देता है.
**डाटा एक सह कहानी बनाता है.**यह कैसे कार्य करता है
**अ- धातु**संदर्भ तंत्र में तीन मुख्य अवयव हैं:

### 1 ..

कॉन्टेक्स्ट निकालेंटर`ConcurrentDictionary`:

```csharp
public class OpenApiContextManager
{
    private readonly ConcurrentDictionary<string, ApiContext> _contexts;
    private const int MaxRecentCalls = 15;
    private const int SummarizeThreshold = 20;

    public void AddToContext(
        string contextName,
        string method,
        string path,
        string? requestBody,
        string responseBody)
    {
        var context = _contexts.GetOrAdd(contextName, _ => new ApiContext
        {
            Name = contextName,
            CreatedAt = DateTimeOffset.UtcNow,
            RecentCalls = new List<RequestSummary>(),
            SharedData = new Dictionary<string, string>(),
            TotalCalls = 0
        });

        context.RecentCalls.Add(new RequestSummary
        {
            Timestamp = DateTimeOffset.UtcNow,
            Method = method,
            Path = path,
            RequestBody = requestBody,
            ResponseBody = responseBody
        });

        ExtractSharedData(context, responseBody);

        if (context.RecentCalls.Count > MaxRecentCalls)
        {
            SummarizeOldCalls(context);
        }
    }
}
```

### - निवेदन से संदर्भ नाम निकालें

2

```mermaid
graph LR
    A[20+ Calls] --> B[Keep 15 Most Recent]
    A --> C[Summarize Older Calls]
    B --> D[Full Request/Response]
    C --> E[Summary: 'GET /users - called 5 times']
    D --> F[Included in LLM Prompt]
    E --> F
```

```csharp
private void SummarizeOldCalls(ApiContext context)
{
    var toSummarize = context.RecentCalls
        .Take(context.RecentCalls.Count - MaxRecentCalls)
        .ToList();

    var summary = new StringBuilder();
    summary.AppendLine($"Earlier calls ({toSummarize.Count}):");

    var groupedByPath = toSummarize
        .GroupBy(c => $"{c.Method} {c.Path.Split('?')[0]}");

    foreach (var group in groupedByPath)
    {
        summary.AppendLine($"  {group.Key} - called {group.Count()} time(s)");
    }

    context.ContextSummary = summary.ToString();
    context.RecentCalls.RemoveRange(0, toSummarize.Count);
}
```

### प्रमाणपत्र प्रबंधक प्रारंभ करें

- संदर्भ भंडारण तथा वापसी का प्रबंधन करता है

```csharp
private void ExtractSharedData(ApiContext context, string responseBody)
{
    using var doc = JsonDocument.Parse(responseBody);
    var root = doc.RootElement;

    if (root.ValueKind == JsonValueKind.Array && root.GetArrayLength() > 0)
    {
        var firstItem = root[0];
        ExtractValueIfExists(context, firstItem, "id", "lastId");
        ExtractValueIfExists(context, firstItem, "userId", "lastUserId");
        ExtractValueIfExists(context, firstItem, "name", "lastName");
        ExtractValueIfExists(context, firstItem, "email", "lastEmail");
    }
    else if (root.ValueKind == JsonValueKind.Object)
    {
        ExtractValueIfExists(context, root, "id", "lastId");
        ExtractValueIfExists(context, root, "userId", "lastUserId");
        ExtractValueIfExists(context, root, "name", "lastName");
        // ... more common patterns
    }
}
```

3

## संकेत

### - कोठरी में संदर्भ इतिहास शामिल करें

कॉन्टेक्स्ट भंडारण

**थ्रेड सुरक्षित के प्रयोग से संदर्भों में भंडारित हैं**एक्सपोजराइजेशन

```http
GET /api/mock/users?context=my-session
GET /api/mock/users?api-context=my-session
```

**संदर्भ को हमेशा - हमेशा के लिए बढ़ने से रोकने के लिए, तंत्र स्वचालित रूप से पुराने कॉलों का सार देता है जब 15:**

```http
GET /api/mock/users
X-Api-Context: my-session
```

**साझा डाटा निकाला**

```http
POST /api/mock/orders
Content-Type: application/json

{
  "context": "my-session",
  "shape": {"orderId": 0, "userId": 0}
}
```

### संदर्भ प्रबंधक स्वचालित रूप से उपभोक्ताओं को आसानी से आसानी से पहुँच योग्य बनाने के लिए कनेक्ट करता है:

यह तंत्र को सर्वाधिक हाल ही के उपयोक्ता आईडी, अनुक्रम आईडी, आदि को ट्रैक करने देता है, उन्हें संदर्भ इतिहास में उपलब्ध कराने देता है.**संदर्भों का उपयोग किया जा रहा है**संदर्भ निर्दिष्ट करने के लिए तीन तरीके

#### आप संदर्भ नाम को तीन भिन्‍न तरीक़ों से पार कर सकते हैं, इस प्राथमिकताात्मक क्रम के साथ:

```http
GET /api/mock/users/123?context=session-1
```

#### 1 ..

```http
GET /api/mock/stream/stock-prices?context=trading-session
Accept: text/event-stream
```

#### क्वैरी पैरामीटर

```http
POST /graphql?context=my-app
Content-Type: application/json

{
  "query": "{ users { id name } }"
}
```

#### (सबसे उच्च प्राथमिकता)

```json
{
  "mostlylucid.mockllmapi": {
    "HubContexts": [
      {
        "Name": "stock-ticker",
        "Description": "Real-time stock prices",
        "ApiContextName": "stocks-session",
        "Shape": "{\"symbol\":\"string\",\"price\":0}"
      }
    ]
  }
}
```

## 2

### एचटीटीपी शीर्षिका

3

```http
### 1. Create user
POST /api/mock/users?context=checkout-flow
{
  "shape": {
    "userId": 0,
    "name": "string",
    "email": "string",
    "address": {"street": "string", "city": "string"}
  }
}

### Response: {"userId": 42, "name": "Alice", ...}

### 2. Create cart (will reference same user)
POST /api/mock/cart?context=checkout-flow
{
  "shape": {
    "cartId": 0,
    "userId": 0,
    "items": [{"productId": 0, "quantity": 0}]
  }
}

### Response: {"cartId": 123, "userId": 42, ...}

### 3. Create order (consistent user and cart)
POST /api/mock/orders?context=checkout-flow
{
  "shape": {
    "orderId": 0,
    "userId": 0,
    "cartId": 0,
    "total": 0
  }
}

### Response: {"orderId": 789, "userId": 42, "cartId": 123, ...}
```

### निवेदन शरीर

समर्थित अंतपाइंट क़िस्म

```http
### First call - establishes baseline
GET /api/mock/stocks?context=market-data
    &shape={"symbol":"string","price":0,"volume":0}

### Response: {"symbol": "ACME", "price": 145.50, "volume": 10000}

### Second call - price changes realistically
GET /api/mock/stocks?context=market-data
    &shape={"symbol":"string","price":0,"volume":0}

### Response: {"symbol": "ACME", "price": 146.20, "volume": 12000}
### Notice: Same symbol, price increased by $0.70 (realistic)

### Third call - continues the trend
GET /api/mock/stocks?context=market-data
    &shape={"symbol":"string","price":0,"volume":0}

### Response: {"symbol": "ACME", "price": 145.80, "volume": 11500}
### Notice: Price fluctuates but stays in realistic range
```

आस - पास की आयतें

### सभी

अंत- बिन्दु क़िस्म:

```http
### Start game
POST /api/mock/game/start?context=game-session-123
{
  "shape": {
    "playerId": 0,
    "level": 0,
    "health": 0,
    "score": 0,
    "inventory": []
  }
}

### Response: {"playerId": 42, "level": 1, "health": 100, "score": 0}

### Complete quest
POST /api/mock/game/quest?context=game-session-123
{
  "shape": {
    "playerId": 0,
    "level": 0,
    "score": 0,
    "reward": {"item": "string", "value": 0}
  }
}

### Response: {"playerId": 42, "level": 2, "score": 500,
###           "reward": {"item": "Sword", "value": 100}}
### Notice: Same player, level increased, score increased

### Get stats
GET /api/mock/game/player?context=game-session-123
    &shape={"playerId":0,"level":0,"health":0,"score":0}

### Response: {"playerId": 42, "level": 2, "health": 100, "score": 500}
### Notice: Consistent with quest completion
```

## रेस्ट एपीआई्स

### स्ट्रीमिंग एपीआई्स

```http
GET /api/openapi/contexts

### Response:
{
  "contexts": [
    {
      "name": "session-1",
      "totalCalls": 5,
      "recentCallCount": 5,
      "sharedDataCount": 3,
      "createdAt": "2025-01-15T10:00:00Z",
      "lastUsedAt": "2025-01-15T10:05:00Z",
      "hasSummary": false
    }
  ],
  "count": 1
}
```

### ग्राफ

```http
GET /api/openapi/contexts/session-1

### Response shows full context including:
### - All recent calls with timestamps
### - Extracted shared data (IDs, names, emails)
### - Summary of older calls (if any)
```

### सिग्नलआर (क्रिया विन्यास)

```http
DELETE /api/openapi/contexts/session-1
```

### वास्तविक विश्‍व प्रयोग केस

```http
DELETE /api/openapi/contexts
```

## केस 1: ई- मेल प्रवाह इस्तेमाल करें

### लगातार उपयोक्ता व आदेश डाटा के साथ पूरा खरीदारी का एक पूरा अनुभव सिमुलेट करें:

केस 2: स्टॉकस का सिमुलेशन इस्तेमाल करें

```csharp
public async Task<string> HandleRequestAsync(
    string method,
    string fullPathWithQuery,
    string? body,
    HttpRequest request,
    HttpContext context,
    CancellationToken cancellationToken = default)
{
    // 1. Extract context name from request
    var contextName = _contextExtractor.ExtractContextName(request, body);

    // 2. Get context history if context specified
    var contextHistory = !string.IsNullOrWhiteSpace(contextName)
        ? _contextManager.GetContextForPrompt(contextName)
        : null;

    // 3. Build prompt with context history
    var prompt = _promptBuilder.BuildPrompt(
        method, fullPathWithQuery, body, shapeInfo,
        streaming: false, contextHistory: contextHistory);

    // 4. Get response from LLM
    var response = await _llmClient.GetCompletionAsync(prompt, cancellationToken);

    // 5. Store in context if context name provided
    if (!string.IsNullOrWhiteSpace(contextName))
    {
        _contextManager.AddToContext(
            contextName, method, fullPathWithQuery, body, response);
    }

    return response;
}
```

### बेतरतीब मान के बजाए उचित प्रकार के स्टॉक मूल्य आंदोलन उत्पन्न करें:

बिना किसी संदर्भ के, प्रत्येक कॉल एक पूरी तरह से बेतरतीब प्रतीक और मूल्य वापस आएगा ।

```
TASK: Generate a varied mock API response.
RULES: Output ONLY valid JSON. No markdown, no comments.

API Context: session-1
Total calls in session: 3

Shared data to maintain consistency:
  lastId: 42
  lastName: Alice
  lastEmail: alice@example.com

Recent API calls:
  [10:00:05] GET /users/42
    Response: {"id": 42, "name": "Alice", "email": "alice@example.com"}
  [10:00:12] GET /orders?userId=42
    Response: {"orderId": 123, "userId": 42, "items": [...]}

Generate a response that maintains consistency with the above context.

Method: POST
Path: /shipping/123
Body: {"orderId": 123}
```

आस - पास की आयतों से पता चलता है कि सी.

## केस ३: खेल स्थिति प्रगति इस्तेमाल करें

### खेल सत्रों के माध्यम से खिलाड़ी प्रगति ट्रैक करें:

```http
 Bad:  ?context=test1
 Good: ?context=user-checkout-flow-jan15
```

### कॉन्टेक्स्ट प्रबंधन एपीआई

सभी संदर्भों की सूची दें

```http
### After completing your test scenario
DELETE /api/openapi/contexts/user-checkout-flow-jan15
```

### कॉन्टेक्स्ट विवरण प्राप्त करें

विशिष्ट संदर्भ साफ करें

```http
GET /api/mock/users?context=demo-session
GET /api/mock/orders?context=demo-session
GET /api/mock/shipping?context=demo-session
```

### सभी संदर्भों को साफ करें

कार्यान्वयन विवरण

```http
GET /api/openapi/contexts/demo-session
```

हैंडलर निवेदन में संयोजन

### प्रत्येक निवेदन हैंडलर (प्रयोग, स्ट्रीम, ग्राफ, सिग्नलR) उसी पैटर्न पर चलते हैं:

QLM संकेतों में संदर्भ

```http
### Load spec with context
POST /api/openapi/specs
{
  "name": "petstore",
  "source": "https://petstore3.swagger.io/api/v3/openapi.json",
  "basePath": "/petstore",
  "contextName": "petstore-session"
}

### All petstore endpoints will share the same context
```

## जब संदर्भ मौजूद होता है, उसका इतिहास अलीएल प्राम्प्ट में शामिल होता है:

### LLM सभी पिछले कॉलों को देखता है और प्रतिक्रिया बनाता है जो एक ही आईडी, नाम, और अन्य डेटा का उल्लेख करते हैं, सुसंगतता बनाए रखने के लिए।

बढ़िया अभ्यास

- 1 ..
- डिस्क्रिप्ट्ड संदर्भ नाम इस्तेमाल करें
- 2

**जब समाप्त हो जाए तो कॉन्टेक्स्ट साफ करें**संदर्भों को मेमोरी में स्थिर रखता है जब तक कि साफ- सफाई या सर्वर फिर आरंभ नहीं कर देता है:

### 3

`OpenApiContextManager`संबंधित अंत बिन्दुओं के बीच संदर्भ साझा करें`ConcurrentDictionary`सभी संबंधित कॉल के लिए उसी संदर्भ नाम का उपयोग करें:

### 4.

कॉन्टेक्स्ट आकार मॉनीटर करें

## संदर्भ विवरण जाँचें कि कितनी बार कॉल भंडारित हैं:

1. **अगर आपके पास बहुत सारे कॉल हैं (> 100), तो ध्यान दीजिए कि आप लंबाई से जुड़ी समस्याओं से बचने के लिए ताजा कदम उठा रहे हैं ।**5.
2. **ओपनपीआई स्पाइट्स के साथ मिला**अधिकतम वास्तविकवाद के लिए, ओपनपीआई स्पेस के साथ संदर्भों का प्रयोग करें:
3. **परफ़ॉर्मेंस पर ध्यान दें**मेमोरी उपयोग
4. **हर संदर्भ स्टोरः**15 से ऊपर (पूरा निवेदन/ चिल्ला)

## पुराने कॉल का सारांश (अनुप्रयोग)

साझा डाटा (कम शब्दकोश) निकालें (n)

विशिष्ट मेमोरी प्रति संदर्भ

जवाब आकार पर आधारित ~50-200 केबी