Part 3, The Kiota Side Quest Harder than I thought

TL;DR – The official Mistral OpenAPI spec is 49,000 lines. Kiota’s –include-path flag filters it at generation time to the one endpoint I care about. The question was never “how do I shrink this file”. It was “how do I ask for less”. Along the way I got a Ferrari when I wanted a go-kart, plus a free sample of tool-calling scaffolding that pays off later in the series.

This is a small diversion from the main series, but it is the insight the whole project turned on. This post is the long-form version of the side quest; with the reasoning I skipped on stage. Buried in the model’s failed attempts, its reasoning kept naming Kiota, Microsoft’s OpenAPI client generator.

First attempt so many files

kiota generate --language CSharp
  --class-name MistralChatCompletionClient
  --namespace-name Mistral
  --openapi mistral-openapi.yaml

Second attempt 3% of the original count

kiota generate --language CSharp
  --class-name MistralChatCompletionClient
  --namespace-name Mistral
  --openapi mistral-openapi.yaml
  --output Generated
  --include-path "/v1/chat/completions*"

The interesting commandline flag is –include-path. The full 49,000-line spec, filtered at generation time to one endpoint. I did not edit the YAML. I did not trim anything by hand. I told the generator what I wanted and it brought back only that.

Bonus, the newer snapshot generated the response-side cache-hit field. One snapshot can send prompt_cache_key, the other cannot report the hit. Two downloads of “the same” file (days apart), and they disagree about what the API says back.

Full spec‘–include-path “/v1/chat/completions*”
.cs files2,39069
Lines of C#257,7416,463
Directories3035
Intersection-type wrappers3420
Generation time~35s~3s

Because the number of files was so big, I ran a cyclomatic complexity analyser over the two libraries.

Full spec (2,390 files)Chat only (69 files)
Total cyclomatic complexity~18,233~488
Total decision points~15,843~419
Average CC per file7.67.1
Files over CC 103788
Worst fileUsageQueryRowOUT.cs, CC ~189ChatCompletionRequest.cs, CC ~152

Complexity scales with breadth, not depth. Average complexity per file is nearly identical between the two (7.6 vs 7.1). The full client is not harder to read per file, there are just 37x more files. The worst offenders are serialization sinks. UsageQueryRowOUT (CC ~189), ExtendedOAuthServerMetadata (~188), CreateResponseResponse (~157), ChatCompletionRequest (~152).

The Kiota 1.39 generates for .NET 10, so an older standalone .NET 8 or 9 runtime will crash at startup with a MissingMethodException from the diagnostics stack. Point DOTNET_ROOT at a .NET 10 runtime and it runs clean.

I compared my fresh download against a generated client from a different snapshot of the same spec, taken weeks apart. One snapshot has RAG deployments, their metrics and the Vespa deployment models. The other has dataset-records bulk operations, workflow deployment archives, and a pile of new admin workspace-member models.

There were also a surprising number of warnings.

PS C:\Users\BrynLewis\Downloads\Kiota> kiota generate --language CSharp --class-name MistralChatCompletionClient --namespace-name Mistral --openapi openapi.yaml --output Generated --include-path "/v1/chat/completions*"
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema PipelineConfigDefinition is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema EmbeddingInput is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema OutputContentChunks is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema ChatClassificationRequestInputs is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema EvaluatorStatistics is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema /v1/workflows/{workflow_identifier}/execute is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema /v1/workflows/registrations/{workflow_registration_id}/execute is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/ - The schema /v1/conversations/{conversation_id} is a polymorphic type but does not define a discriminator. This will result in serialization errors.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ClientSecret/properties/value - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/AudioTranscriptionRequest/properties/file_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/AudioTranscriptionRequestStream/properties/file_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/AuthData/properties/client_secret/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ConnectorMCPPublicUpdate/properties/server/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/issuer - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/authorization_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/token_endpoint - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/registration_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/service_documentation/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/op_policy_uri/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/op_tos_uri/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/revocation_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/ExtendedOAuthServerMetadata/properties/introspection_endpoint/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/OAuth2ClientCredentialsInput/properties/client_secret/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/OAuth2ClientCredentialsInput/properties/client_private_key/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/Oauth2MetadataSecrets/properties/client_secret/anyOf/0 - The format password is not supported by Kiota for the type String and will be ignored.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateConnectorRequest/properties/oauth2_server_metadata_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateConnectorRequest/properties/server - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateHTTPConnectorRequest/properties/oauth2_server_metadata_url/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/CreateHTTPConnectorRequest/properties/server - The format uri is not supported by Kiota and the string type will be used.
warn: Kiota.Builder.KiotaBuilder[534942631]
      OpenAPI warning: #/components/schemas/UpdateHTTPConnectorRequest/properties/server/anyOf/0 - The format uri is not supported by Kiota and the string type will be used.
Generation skipped as no changes were detected

Hint: to force the generation to overwrite an existing client pass the --clean-output switch.
Example: kiota generate --clean-output

Hint: use the info command to get the list of dependencies you need to add to your project.
Example: kiota info -d "C:\Users\BrynLewis\Downloads\Kiota\openapi.yaml" -l CSharp
PS C:\Users\BrynLewis\Downloads\Kiota>

Next in the series: Part 4, the human as the clipboard, file tools, permissioning, and the CLI demo where the tool-calling scaffolding parked here finally earns its keep.

Part 2, Half-Arsed DTOs, and the 49,000-Line Spec

TL;DR – Hand-typing DTOs one 422 at a time slows you down. The official Mistral API OpenAPI spec is 49,000 lines and cannot fit in a 128K context window. The fix was a 296-line community extract and Kiota’s include-path trick. Same model, same request, only the approach changed.

This post is the long-form version of the middle third of the talk, everything between the two demos. It is the part I compressed hardest on stage because it is numbers and screenshots, which is a shame because it contains the actual lesson.

Sick of half-arsed DTOs

Once the basic loop from Part1 worked, the DTOs became the bottleneck. Hand-typed message and choice DTOs fixed one 422 at a time. Every fix revealed a property I had missed or a union variant I did not know existed. Every session started with fixingcasing and enums again, in prompts, over and over again.

// DTOs for the Mistral API
public record ChatCompletionRequest(
    [property: JsonPropertyName("model")] string Model,
    [property: JsonPropertyName("messages")] ChatMessage[] Messages,
    [property: JsonPropertyName("temperature")] float? Temperature = null,
    [property: JsonPropertyName("max_tokens")] int? MaxTokens = null,
    [property: JsonPropertyName("stream")] bool? Stream = null
);

public record ChatMessage(
    [property: JsonPropertyName("role")] string Role,
    [property: JsonPropertyName("content")] string Content
);

public record ChatCompletionResponse(
    [property: JsonPropertyName("id")] string Id,
    [property: JsonPropertyName("object")] string Object,
    [property: JsonPropertyName("created")] long Created,
    [property: JsonPropertyName("model")] string Model,
    [property: JsonPropertyName("choices")] Choice[] Choices,
    [property: JsonPropertyName("usage")] Usage Usage
);

public record Choice(
    [property: JsonPropertyName("index")] int Index,
    [property: JsonPropertyName("message")] ChatMessage Message,
    [property: JsonPropertyName("finish_reason")] string FinishReason
);

public record Usage(
    [property: JsonPropertyName("prompt_tokens")] int PromptTokens,
    [property: JsonPropertyName("completion_tokens")] int CompletionTokens,
    [property: JsonPropertyName("total_tokens")] int TotalTokens
);

There is a machine-readable source of truth. The OpenAPI spec. That is when the project stopped being “a chat client” and started being “a client generator’s customer”.

The full spec

Download from docs.mistral.ai/openapi.yaml. 49,000 lines. 1.5 MB. About 300K tokens. Chat completions, Files API, OCR, insertions, all of the things. My context window is approximately128K. It cannot/wouldnot fit so I did the obvious thing anyway. Loaded the whole spec and my client went pop. Prompts hundreds of thousands of tokens deep. Responses slowing and “token maxing”. With the useful answer hidden at the bottom of the payload.

Two lessons came out of the wreck. First, this is why “just give the model the docs” fails in real projects: ground truth has to fit in the window, and the interesting APIs do not. Second, the failure forced the question that saves the whole project: 49,000 lines is what is in it.

The thinking told me

Buried in the model’s failed attempts at code, its reasoning kept naming two things. Kiota, Microsoft’s OpenAPI client generator. Also, a chat-completions-only YAML by API Evangelists. It could not build either. But it knew they existed. It also offered Python libraries and NodeJS utilities, and I even considered generating a console application to chop up the file before choosing to explore instead.

The Telerik Fiddler raw POSTs with 422 typos. First chat client with Memento amnesia and JsonDocument, which made the large model parsing go pop. Second chat client with hand-typed DTOs and a system message, which brought context. Then a chat client plus the big YAML, where the context exploded and .NET regressed. Third chat client with an IMistralService abstraction, plus the small YAML, which works and became YAMLClientLibrary and YAMLClientApplication.

// Client
public class MistralClient
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;
    private readonly string _model;

    public MistralClient(HttpClient httpClient, IConfiguration config)
    {
        _httpClient = httpClient;
        _apiKey = config["FOEHN_API_KEY"] ?? throw new InvalidOperationException("FOEHN_API_KEY not set");
        _model = config["MFOEHN_MODEL"] ?? "mistral-medium-latest";
        _httpClient.DefaultRequestHeaders.Authorization = new("Bearer", _apiKey);
    }

    public async Task<ChatResponse> ChatAsync(ChatRequest request)
    {
        var response = await _httpClient.PostAsJsonAsync(
            "https://api.mistral.ai/v1/chat/completions",
            request);

        return await response.EnsureSuccessStatusCode().Content.ReadFromJsonAsync<ChatResponse>()
            ?? throw new InvalidOperationException("Empty response");
    }
}

In Retrospect

Since my session (3 days AGO) Mistral.ai doc YAML link has been removed from the API docs page,but is still accessible. Using my “leet” search skills I found the URL of the YAML used by the Mistral Python & Typescript generators use. But I couldn’t access the SpeakeasyAPI endpoint. Some of the changes have been really odd

There are some libraries tghamm(NuGet), tryAGI(NuGet) libraries are based on an older/smaller (roughly 30%) version of the OpenAPI specification, but these weren’t in the spirit of the project.

Calls from New Zealand terminate in Cloudflare, then on to the EU or US. Typical response is 1 to 2 seconds. Occasional tails of 10 to 15 seconds. Bigger models slower, as expected. Fiddler showed the connection path before any application code existed.

There is no Australia East option for Mistral. You pick EU residency or US speed this any distributed API lesson, but the AI hype cycle makes you forget it. Reasoning models spend tokens thinking before they answer. My responses kept truncating mid-code. I escalated the prompt through four rewrites. The winner was “Just code. No thinking.” I dropped the punctuation too. It worked.

Sometimes the fix is asking for less, not explaining more. Negative-space instructions.

The max_tokens dial

Responses cut off mid-line usually are not the model failing. They hit the max_tokens cap. Raise the cap, same request, whole answer. Too small and you waste a full bill on a truncated answer, then retry and pay again. Too big is fine, it is only headroom, except with runaway generation, which bills forever. Tune the cap to your worst realistic response, not your average.

The model matrix

Small. Fast, cheap, occasionally shallow.
Medium. The workhorse. Best cost to quality for this workload.
Large. Made response parsing go pop, literally. Its answers came back so long and so ornately structured that my hand-rolled parsing choked. Beautiful prose, unusable payloads. Small and Medium answer the question. Large writes you an essay about the question.
Codestral. For development text insertions, not this.

Measure with your own workloads. The leaderboards do not know your payload.

.NET drift and prose prompts

I asked for .NET 10 and C# 14. I got .NET 8 idioms. Not malice. The model defaults to the median of its training data. Pleading in the prompt helped a little. Grounding helped completely. This shows up again in a moment as the recurring theme.

Meanwhile the prompts had become a hand-written mini-spec, badly, in prose. “Generate a C# v14 .NET 10 client library for this YAML.” Then a refined version with streaming, synchronous, shared, discriminators. Then “Don’t use NSwag”.

Negative instructions are weak. The model still has to guess what you do want.

System.md, the proto-skill

One attempt generated code that contained a system.md. Static instructions move to a file that rides along on every turn. The prompt shrinks to the request and the conventions persist.

The cache keys from Part 1: the live API reports cache hits, billed at 10%, and neither spec knew. The official one caught half the story. The request side has the plumbing, prompt_cache_key. The response side does not, prompt_tokens_details is missing from the generated interface. The snapshot froze mid-feature.

The exponential increase in speed

More code for me to copy n paste, well lots of code.

4,385 tokens for the client library.

7,756 more for a sample client. So far 11,924

14,332 for basic tool support. So far 26,256

19,999 for smarter searching. So far 46,255.

26,333 for searching with filters. So far 72,588.

31,353 for a slash-command UX. So far 103,941

36,924 for skills. All up 140,865 to get a functional application.

The Human as the Clipboard

The workflow so far: model writes code, I copy it out of the console, paste into a file, build, copy errors back in
Every round-trip has a human where a file operation should be

I am the tool’s tool

Part 1, One HTTP POST, Fiddler, SSE and the 422 That Lied

TL;DR – The whole Mistral Chat Completions API contract starts as one HTTP POST. A system message, a user message, an assistant message reply, and an optional tool message result. Four different payloads, not a list of strings. Streaming is done with Server Sent Events(SSE), JSON inside JSON. The first real “bug” was an HTTP Error 422 Unprocessable Content and the error message lied by omission.

This post is the long-form version of the first demo in the talk. The first and last time Telerik Fiddler (I’m over the licensing message) appears in the session.

The starting point

The Mistral API surface is huge (and the docs changed between the start and end of the series) Chat completions, Files, Models, Embeddings etc. The samples are TypeScript, Python and curl, which tells you who the expected audience is. I am a C# developer and only cared about chat completions.

On the top left of the docs page there is(was) a Yet Another Markup Language (YAML) download for the OpenAPI specification (the clickable link disappeared overnight). The download link is still a live, and the file is 30% bigger today.

The messages array is not a list of strings. It is four different payloads SystemMessage | UserMessage | AssistantMessage | ToolMessage.

A System Message is usually a plain string. Standing instructions, no response expected, rides along on every turn. It can be an array of typed chunks a TextChunk or ThinkChunk

A UserMessage contains the prompt. The content field is not just a string either. It can be an array of typed chunks. TextChunk. ImageURLChunk. DocumentURLChunk, ReferenceChunk, FileChunk, ThinkChunk, AudioChunk, ResourceChunk or ResourceLinkChunk

An Assistant Message is what comes back. In addition to the original UserMessage and response payload it can also carry ToolCalls. A ToolMessage closes the loop. It is a structured message with which a model asks the runtime to execute a specific tool/function on its behalf, rather than producing a plain text answer.

On the wire you send one HTTP POST with model name, SystemMessage,UserMessage, temperature, stream, and max_tokens (important for message truncation discussion). That is the entire contract. Later on both the request side and the response side, is this shape better dressed. Two different JSON payloads and this is where the DTO pain in Part 2 starts.

The demo

Non-streaming first. Fire the HTTP POST with stream off. One JSON, document comes back, choices[0].message.content. Easy to code. Dead to watch. A wall of silence, then everything at once.

{
   "model": "mistral-large-latest",
   "messages": [
      {
         "role": "user",
         "content": "Explain the software acronym ACID."
      }
   ]
}
{
   "id": "5272af17c792494bb8ea6871f68e1f08",
   "created": 1794546851,
   "model": "mistral-large-latest",
   "usage": {
      "prompt_tokens": 24,
      "total_tokens": 798,
      "completion_tokens": 774,
      "prompt_tokens_details": {
         "cached_tokens": 0
      },
      "completion_tokens_details": {
         "reasoning_tokens": 265
      },
      "service_tier": "standard"
   },
   "object": "chat.completion",
   "choices": [
      {
         "index": 0,
         "finish_reason": "stop",
         "message": {
            "role": "assistant",
            "tool_calls": null,
            "content": [
               {
                  "type": "thinking",
                  "thinking": [
                     {
                        "type": "text",
                        "text": "The user is asking for an explanation of the software acronym ACID. This is a fundamental concept in database systems and transaction processing. I should explain:\n\n1. What ACID stands for (Atomicity, Consistency, Isolation, Durability)\n2. What each property means in practical terms\n3. Why it matters (transactions, data integrity)\n4. Maybe a brief example to make it concrete\n5. Context (primarily used in relational databases)\n\nLet me structure this clearly:\n\n**ACID** stands for:\n- **Atomicity**: All-or-nothing. A transaction is treated as a single unit. Either all operations succeed or none do.\n- **Consistency**: The database moves from one valid state to another, maintaining all defined rules/constraints (integrity constraints, cascades, triggers).\n- **Isolation**: Concurrent transactions don't interfere with each other. Each sees the database as if it were the only one running.\n- **Durability**: Once committed, changes persist even in case of system failure (power loss, crash).\n\nI should mention this is crucial for financial systems, banking, etc. where data integrity is paramount.\n\nMaybe contrast briefly with BASE (NoSQL) to give context, but keep focus on ACID.\n\nLet me write this in a clear, educational tone."
                     }
                  ],
                  "closed": true
               },
               {
                  "type": "text",
                  "text": "**ACID** is an acronym describing the four key properties that guarantee reliable processing of database transactions. It ensures that data remains accurate and consistent even when errors, power failures, or other mishaps occur.\n\nHere is what each letter stands for:\n\n### **A — Atomicity**\nA transaction is an **\"all-or-nothing\"** proposition. Either *all* the operations in the transaction complete successfully, or *none* of them do. If any part fails, the entire transaction is rolled back to its original state.\n- **Example:** Transferring $100 from Account A to Account B requires two steps: debit A and credit B. If the credit fails, the debit is undone. You never end up with money disappearing into thin air.\n\n### **C — Consistency**\nA transaction must take the database from one **valid state to another valid state**, preserving all defined rules and constraints (data integrity, foreign keys, unique constraints, triggers, etc.).\n- **Example:** If a database rule says an account balance cannot be negative, a transaction that would make it negative will be rejected entirely, keeping the database consistent.\n\n### **I — Isolation**\nConcurrent transactions (multiple users/processes running at the same time) must not interfere with each other. Each transaction sees the database as if it were the only one executing, preventing \"dirty reads,\" non-repeatable reads, and phantom reads.\n- **Example:** If two people book the last seat on a flight simultaneously, isolation ensures only one succeeds and the other gets an error, rather than both getting the seat.\n\n### **D — Durability**\nOnce a transaction has been **committed**, it remains so permanently—even in the event of a system crash, power loss, or hardware failure. The changes are written to non-volatile storage (like disk) before the commit is acknowledged.\n- **Example:** After you see a \"payment successful\" confirmation, the record of that payment will still exist even if the server immediately loses power.\n\n---\n\n### Why it matters\nACID properties are critical in systems where correctness is non-negotiable—**banking, financial trading, inventory management, healthcare records, and e-commerce checkout systems**. They ensure that data integrity is maintained despite concurrent access, hardware failures, and software errors.\n\n*(Note: In contrast, some distributed NoSQL databases use **BASE**—Basically Available, Soft state, Eventual consistency—trading strict ACID guarantees for higher availability and scalability.)*"
               }
            ]
         }
      }
   ]
}

Flip stream to true. Same request. Now the response arrives as SSE. A stream of data: {…} events, ending in data: [DONE]. It looks faster and it genuinely is for the user. First tokens arrive while the model is still generating. But total time is the same. You have moved the wait into the stream.

The client has to stitch the deltas back together. Fragments and tool-call arguments arrive in pieces across chunks. Second, each one of these events is a string with JSON inside it. JSON inside JSON, parsed chunk after chunk. Get a boundary slightly wrong (like I did multiple times) and nothing fails cleanly. That is why my streaming client has a whole assembly class.

The 422 Trap

My favourite bug of the session. I accidentally changed one character in the request. The c in context to a C. The API answered 422, “missing required property”.

{
   "model": "mistral-large-latest",
   "messages": [
      {
         "role": "user",
         "Content": "Explain the software acronym ACID."
      }
   ]
}

The property was not missing. The casing was wrong. The API expects snake_case and I sent .NET’s default PascalCase(I wasn’t using DataAnnotations or JsonSerializerOptions yet)

Diff the request the docs show against the request you sent. Character by character, property by property. Casing, underscores, everything. Comment out the payload and add fields back one at a time until it breaks again. Inspect the payloads in a JSON viewer in the debugger.

Not glamorous. Not clever. Just effective. That one habit saved me more time across this project than every clever thing I did combined.

My First Chat Client

A console application. Read input, send it, print the response. The reflex of every developer since 1974 (I started coding in early then got my own compute an Amstrad CPC6128). The first surprise is structural. Every run starts from zero. No memory of the previous conversation. A Memento brain wipe.

The amnesia was never the model. The model has no state at all. It is entirely the plumbing. And there is a subtle failure mode hiding here: the model had nothing to “misremember” from, so it answers confidently either way. No wrong memory is bad. No memory answering confidently is worse, because it looks the same from the outside.

It’s Stateless(WTF)?

The API is stateless by design this is a deliberate choice, not a shortcoming. If the API held your conversation server-side, every turn would have to land on the machine holding the session. i.e. a sticky session, or every machine would have to have a shared session store.

Stickiness plus unpredictable turn times, this call runs 200ms, that one runs 30 seconds, means machines sitting reserved for slow conversations while new ones starve. Stateless means any request can run anywhere, on any GPU, and that is what makes the economics of inference work.

The vendor farms the storage problem back to you. You have the conversation on disk anyway, so it is cheap for you too. In Memento terms: the cloud has no new memories, only the polaroids you mail it.

There is a quiet upside I did not spot until much later. The client re-sends the same prefix every turn, so the API has a trick for exactly this pattern: prompt cache keys. You give the request a prompt_cache_key and the recurrent prefix gets served from cache at 10% of the token price. The stateless design quietly lends you a hand. Numbers from my logs in Part 3.

What this cost

Continuity is not free. As soon as the client re-sends the story every turn, the token count on each request climbs. Convenience and cost are the same dial. The API gives you amnesia and charges you for the cure. You build the memory, then pay per turn to keep it.

Next: Part 2. The hand-typed DTOs got fed up with me, so I went looking for the spec. The spec is 49,000 lines. It did not go well.

I Built My Own Agentic Client (So You Don’t Have To)

TL;DR – I built a series of Mistral API clients in C#, starting with one raw HTTP POST in Telerik Fiddler and ending with a command line interface(CLI) that has file tools, permissioning and context management. No SDK, no libraries. This post starts the series. Everything I mention is committed at KiwiBryn/CodeCampCHC2026, numbered in talk order.

Part 0- Series Introduction

On 21 November 2026 I gave a session at Christchurch Code Camp called “I Built My Own Agentic Client (So You Don’t Have To)”. This is the long-form version, split into a series of posts.

  • Part 1 – the first demo, one HTTP POST in Telerik Fiddler, and what the messages array on the wire actually looks like.
  • Part 2 – what happened between the two demos. Hand-typed DTOs, the OpenAPI spec that would not fit.
  • Part 3 – the second demo, the Mistral CLI. File tools, permissioning, context management and the Files API.

The honest subtitle was “Fiddler to a self-building, self-improving CLI”. The plan grew backwards from there. Everything in the repo got built twice. Once by me understanding it, once by the model generating it.

The rules

Every client in the series, I built. No SDK, no libraries. Visual Studio 2026, C#/.NET, Mistral Chat Completions API, System.Text.Json.

That was the constraint for the talk and it is the constraint for these posts. Constraints make a better story than plans.

One housekeeping note. Mistral hosts data in the EU by default. There is a US endpoint which is faster from New Zealand, but it is the US of A. The European Union (EU) General Data Protection Regulation (GDPR) was a factor for the clients I build professionally. Here it is mostly an excuse to say I checked.

Why bother

Three reasons, none of them “because it is there” or “just because”

First, understanding. If every client I use, I build, then when the payload is wrong I know which layer is lying. An HTTP Error 422 Unprocessable Content does not become a GitHub issue on someone else’s SDK repo. I have the wire trace and I have the Data Transfer Obect(DTO)s.

Second, judgement. An agentic client is a small amount of code around a large amount of policy. What the model may read, what it may write, what it may delete, what gets compressed. My view is that policy should be visible in code you can read over coffee, for the same reason you do not hand your car keys to a stranger.

Third, receipts. Everything in this series is committed and numbered in the order I built it. Clone KiwiBryn/CodeCampCHC2026 and follow along.

What I am not doing

I am not arguing nobody should use an SDK. Kiota shows up in Part 2 as a deliberate sidequest and it taught me two things I use. The reason to build one yourself, once, is that after you have done it, the SDK stops being magic and starts being a trade-off you can price.

Posts in this series

  • Part 1 – One HTTP POST, Fiddler, Server Sent Events(SSE), and the 422 that lied to me.
  • Part 2 – From half-arsed DTOs to 296 lines of YAML. The spec journey, the token ladder.
  • Part 3 – The CLI. Tools, permissioning, a model that went feral, and what it cost.

Next up: Part 1, the atom everything else is built from – one HTTP POST.

The Things Network MQTT & Azure IoT Part3A

Cloud to Device with frm_payload no confirmation

An Azure IoT Hub supports three kinds for Cloud to Device(C2D) messaging and my gateway will initially support only Direct Methods and Cloud-to-device messages.

The first step was to add the The Things Network(TTN) V3 Tennant ID to the context information as it is required for the downlink Message Queue Telemetry Transport (MQTT) publish topic.

namespace devMobile.TheThingsNetwork.Models
{
   public class AzureIoTHubReceiveMessageHandlerContext
   {
      public string TenantId { get; set; }
      public string DeviceId { get; set; }
      public string ApplicationId { get; set; }
   }
}

The object is passed as the context parameter of the SetReceiveMessageHandlerAsync method.

try
{
	DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(
		options.AzureIoTHubconnectionString,
		endDevice.Ids.Device_id,
		TransportType.Amqp_Tcp_Only);

	await deviceClient.OpenAsync();

	AzureIoTHubReceiveMessageHandlerContext context = new AzureIoTHubReceiveMessageHandlerContext()
	{
		TenantId = options.Tenant,
		DeviceId = endDevice.Ids.Device_id,
		ApplicationId = options.ApiApplicationID,
	};

	await deviceClient.SetReceiveMessageHandlerAsync(AzureIoTHubClientReceiveMessageHandler, context);
	
	DeviceClients.Add(endDevice.Ids.Device_id, deviceClient, cacheItemPolicy);
}
catch( Exception ex)
{
	Console.WriteLine($"Azure IoT Hub OpenAsync failed {ex.Message}");
}

To send a message to a LoRaWAN device in addition to the payload, TTN needs the port number and optionally a confirmation required flag, message priority, queueing type and correlation ids.

With my implementation the confirmation required flag, message priority, and queueing type are Azure IoT Hub message properties and the messageid is used as a correlation id.

private async static Task AzureIoTHubClientReceiveMessageHandler(Message message, object userContext)
{
	bool confirmed;
	byte port;
	DownlinkPriority priority;
	string downlinktopic;

	try
	{
		AzureIoTHubReceiveMessageHandlerContext receiveMessageHandlerConext = (AzureIoTHubReceiveMessageHandlerContext)userContext;

		DeviceClient deviceClient = (DeviceClient)DeviceClients.Get(receiveMessageHandlerConext.DeviceId);
		if (deviceClient == null)
		{
			Console.WriteLine($" UplinkMessageReceived unknown DeviceID: {receiveMessageHandlerConext.DeviceId}");
			await deviceClient.RejectAsync(message);
			return;
		}

		using (message)
		{
			Console.WriteLine();
			Console.WriteLine();
			Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} Azure IoT Hub downlink message");
			Console.WriteLine($" ApplicationID: {receiveMessageHandlerConext.ApplicationId}");
			Console.WriteLine($" DeviceID: {receiveMessageHandlerConext.DeviceId}");
#if DIAGNOSTICS_AZURE_IOT_HUB
			Console.WriteLine($" Cached: {DeviceClients.Contains(receiveMessageHandlerConext.DeviceId)}");
			Console.WriteLine($" MessageID: {message.MessageId}");
			Console.WriteLine($" DeliveryCount: {message.DeliveryCount}");
			Console.WriteLine($" EnqueuedTimeUtc: {message.EnqueuedTimeUtc}");
			Console.WriteLine($" SequenceNumber: {message.SequenceNumber}");
			Console.WriteLine($" To: {message.To}");
#endif
			string messageBody = Encoding.UTF8.GetString(message.GetBytes());
			Console.WriteLine($" Body: {messageBody}");
#if DOWNLINK_MESSAGE_PROPERTIES_DISPLAY
			foreach (var property in message.Properties)
			{
				Console.WriteLine($"   Key:{property.Key} Value:{property.Value}");
			}
#endif
			if (!message.Properties.ContainsKey("Confirmed"))
			{
				Console.WriteLine(" UplinkMessageReceived missing confirmed property");
				await deviceClient.RejectAsync(message);
				return;
			}

			if (!bool.TryParse(message.Properties["Confirmed"], out confirmed))
			{
				Console.WriteLine(" UplinkMessageReceived confirmed property invalid");
				await deviceClient.RejectAsync(message);
				return;
			}

			if (!message.Properties.ContainsKey("Priority"))
			{
				Console.WriteLine(" UplinkMessageReceived missing priority property");
				await deviceClient.RejectAsync(message);
				return;
			}

			if (!Enum.TryParse(message.Properties["Priority"], true, out priority))
			{
				Console.WriteLine(" UplinkMessageReceived priority property invalid");
				await deviceClient.RejectAsync(message);
				return;
			}

			if (priority == DownlinkPriority.Undefined)
			{
				Console.WriteLine(" UplinkMessageReceived priority property undefined value invalid");
				await deviceClient.RejectAsync(message);
				return;
			}

			if (!message.Properties.ContainsKey("Port"))
			{
				Console.WriteLine(" UplinkMessageReceived missing port number property");
				await deviceClient.RejectAsync(message);
				return;
			}

			if (!byte.TryParse( message.Properties["Port"], out port))
			{
				Console.WriteLine(" UplinkMessageReceived port number property invalid");
				await deviceClient.RejectAsync(message);
				return;
			}

			if ((port < Constants.PortNumberMinimum) || port > (Constants.PortNumberMaximum))
			{
				Console.WriteLine($" UplinkMessageReceived port number property invalid value must be between {Constants.PortNumberMinimum} and {Constants.PortNumberMaximum}");
				await deviceClient.RejectAsync(message);
				return;
			}

			if (!message.Properties.ContainsKey("Queue"))
			{
				Console.WriteLine(" UplinkMessageReceived missing queue property");
				await deviceClient.RejectAsync(message);
				return;
			}

			switch(message.Properties["Queue"].ToLower())
			{
				case "push":
					downlinktopic = $"v3/{receiveMessageHandlerConext.ApplicationId}@{receiveMessageHandlerConext.TenantId}/devices/{receiveMessageHandlerConext.DeviceId}/down/push";
					break;
				case "replace":
					downlinktopic = $"v3/{receiveMessageHandlerConext.ApplicationId}@{receiveMessageHandlerConext.TenantId}/devices/{receiveMessageHandlerConext.DeviceId}/down/replace";
					break;
				default:
					Console.WriteLine(" UplinkMessageReceived missing queue property invalid value");
					await deviceClient.RejectAsync(message);
					return;
               }

			DownlinkPayload Payload = new DownlinkPayload()
			{
				Downlinks = new List<Downlink>()
				{ 
					new Downlink()
					{
						Confirmed = confirmed,
						PayloadRaw = messageBody,
						Priority = priority,
						Port = port,
						CorrelationIds = new List<string>()
						{
							message.MessageId
						}
					}
				}
			};

			var mqttMessage = new MqttApplicationMessageBuilder()
					.WithTopic(downlinktopic)
					.WithPayload(JsonConvert.SerializeObject(Payload))
					.WithAtLeastOnceQoS()
					.Build();

			await mqttClient.PublishAsync(mqttMessage);

			// Need to look at confirmation requirement ack, nack maybe failed & sent
			await deviceClient.CompleteAsync(message);

			Console.WriteLine();
		}
	}
	catch (Exception ex)
	{
		Debug.WriteLine("UplinkMessageReceived failed: {0}", ex.Message);
	}
}

To “smoke test”” my implementation I used Azure IoT Explorer to send a C2D telemetry message

Azure IoT Hub Explorer send message form with payload and message properties

The PoC console application then forwarded the message to TTN using MQTT to be sent(which fails)

PoC application sending message then displaying result

The TTN live data display shows the message couldn’t be delivered because my test LoRaWAN device has not been activiated.

TTN Live Data display with message delivery failure

Now that my PoC application can receive and transmit message to devices I need to reconfigure my RAK Wisgate Developer D+ gateway and Seeeduino LoRaWAN and RAK Wisnode 7200 Track Lite devices on The Things Industries Network so I can test my approach with more realistic setup.

The Things Network MQTT & Azure IoT Part2

Uplink with decoded_payload & frm_payload

The next functionality added to my Proof of Concept(PoC) Azure IoT Hub, The Things Network(TTN) V3 Hypertext Transfer Protocol(HTTP) client API Integration, and Message Queue Telemetry Transport (MQTT) Data API Integration is sending of raw and decoded uplink messages to an Azure IoT Hub.

// At this point all the AzureIoT Hub deviceClients setup and ready to go so can enable MQTT receive
mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClientApplicationMessageReceived(e)));

// This may shift to individual device subscriptions
string uplinkTopic = $"v3/{options.MqttApplicationID}/devices/+/up";
await mqttClient.SubscribeAsync(uplinkTopic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);

//string queuedTopic = $"v3/{options.MqttApplicationID}/devices/+/queued";
//await mqttClient.SubscribeAsync(queuedTopic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);

The additional commented out subscriptions are for the processing of downlink messages

The MQTTNet received message handler uses the last segment of the topic to route messages to a method for processing

private static async void MqttClientApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
	if (e.ApplicationMessage.Topic.EndsWith("/up", StringComparison.InvariantCultureIgnoreCase))
	{
		await UplinkMessageReceived(e);
	}

	/*
	if (e.ApplicationMessage.Topic.EndsWith("/queued", StringComparison.InvariantCultureIgnoreCase))
	{
		await DownlinkMessageQueued(e);
	}
	...			
	*/
}

The UplinkMessageReceived method deserialises the message payload, retrieves device context information from the local ObjectCache, adds relevant uplink messages fields (including the raw payload), then if the message has been unpacked by a TTN Decoder, the message fields are added as well.

static async Task UplinkMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
	try
	{
		PayloadUplinkV3 payload = JsonConvert.DeserializeObject<PayloadUplinkV3>(e.ApplicationMessage.ConvertPayloadToString());
		string applicationId = payload.EndDeviceIds.ApplicationIds.ApplicationId;
		string deviceId = payload.EndDeviceIds.DeviceId;
		int port = payload.UplinkMessage.Port;
...
		DeviceClient deviceClient = (DeviceClient)DeviceClients.Get(deviceId);
		if (deviceClient == null)
		{
			Console.WriteLine($" UplinkMessageReceived unknown DeviceID: {deviceId}");
			return;
		}

		JObject telemetryEvent = new JObject();
		telemetryEvent.Add("DeviceID", deviceId);
		telemetryEvent.Add("ApplicationID", applicationId);
		telemetryEvent.Add("Port", port);
		telemetryEvent.Add("PayloadRaw", payload.UplinkMessage.PayloadRaw);

		// If the payload has been unpacked in TTN backend add fields to telemetry event payload
		if (payload.UplinkMessage.PayloadDecoded != null)
		{
			EnumerateChildren(telemetryEvent, payload.UplinkMessage.PayloadDecoded);
		}

		// Send the message to Azure IoT Hub/Azure IoT Central
		using (Message ioTHubmessage = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(telemetryEvent))))
		{
			// Ensure the displayed time is the acquired time rather than the uploaded time. 
			//ioTHubmessage.Properties.Add("iothub-creation-time-utc", payloadObject.Metadata.ReceivedAtUtc.ToString("s", CultureInfo.InvariantCulture));
			ioTHubmessage.Properties.Add("ApplicationId", applicationId);
			ioTHubmessage.Properties.Add("DeviceId", deviceId);
			ioTHubmessage.Properties.Add("port", port.ToString());

			await deviceClient.SendEventAsync(ioTHubmessage);
		}
	}
	catch( Exception ex)
	{
		Debug.WriteLine("UplinkMessageReceived failed: {0}", ex.Message);
	}
}

private static void EnumerateChildren(JObject jobject, JToken token)
{
	if (token is JProperty property)
	{
		if (token.First is JValue)
		{
			// Temporary dirty hack for Azure IoT Central compatibility
			if (token.Parent is JObject possibleGpsProperty)
			{
				if (possibleGpsProperty.Path.StartsWith("GPS_", StringComparison.OrdinalIgnoreCase))
				{
					if (string.Compare(property.Name, "Latitude", true) == 0)
					{
						jobject.Add("lat", property.Value);
					}
					if (string.Compare(property.Name, "Longitude", true) == 0)
					{
						jobject.Add("lon", property.Value);
					}
					if (string.Compare(property.Name, "Altitude", true) == 0)
					{
						jobject.Add("alt", property.Value);
					}
				}
			}
			jobject.Add(property.Name, property.Value);
		}
		else
		{
			JObject parentObject = new JObject();
			foreach (JToken token2 in token.Children())
			{
				EnumerateChildren(parentObject, token2);
				jobject.Add(property.Name, parentObject);
			}
		}
	}
	else
	{
		foreach (JToken token2 in token.Children())
		{
			EnumerateChildren(jobject, token2);
		}
	}
}

There is also some basic reformatting of the messages for Azure IoT Central

TTN Simulate uplink message with GPS location payload.
Nasty console application processing uplink message
Message from LoRaWAN device displayed in Azure IoT Explorer

Currently the code has a lots of diagnostic Console.Writeline statements, doesn’t support Uplink messages, has no Advanced Message Queuing Protocol(AMQP) client connection pooling, can’t run as an Azure Webjob, and a number of other features which I plan on adding in future blog posts.

The Things Network MQTT & Azure IoT Part1

Side by Side

In my last few posts I have built Proof of Concept(PoC) The Things Network(TTN) V3 Hypertext Transfer Protocol(HTTP) API Integration and Message Queue Telemetry Transport (MQTT) Data API Integrations.

While building these PoCs I have learnt a lot about the way that the TTN V3 RESTful and MQTT APIs work and this is the first in a series of posts about linking them together. My plan is to start with yet another .NetCore Console application which hosts both the MQTT and Azure IoT Hub DeviceClient (using the Advanced Message Queueing Protocol(AMQP)) client implementations. I’m using MQTTnet to build my data API client and used NSwag by Richo Suter to generate my RESTful client from the TTN provided swagger file.

In this PoC I’m using the commandlineParser NuGet package to the reduce the amount of code required to process command line parameters and make it more robust. This PoC has a lot of command line parameters which would have been painful to manually parse and validate.

public class CommandLineOptions
{
	[Option('u', "APIbaseURL", Required = false, HelpText = "TTN Restful API URL.")]
	public string ApiBaseUrl { get; set; }

	[Option('K', "APIKey", Required = true, HelpText = "TTN Restful API APIkey")]
	public string ApiKey { get; set; }

	[Option('P', "APIApplicationID", Required = true, HelpText = "TTN Restful API ApplicationID")]
	public string ApiApplicationID { get; set; }

	[Option('D', "DeviceListPageSize", Required = true, HelpText = "The size of the pages used to retrieve EndDevice configuration")]
	public int DevicePageSize { get; set; }

	[Option('S', "MQTTServerName", Required = true, HelpText = "TTN MQTT API server name")]
	public string MqttServerName { get; set; }

	[Option('A', "MQTTAccessKey", Required = true, HelpText = "TTN MQTT API access key")]
	public string MqttAccessKey { get; set; }

	[Option('Q', "MQTTApplicationID", Required = true, HelpText = "TTN MQTT API ApplicationID")]
	public string MqttApplicationID { get; set; }

	[Option('C', "MQTTClientName", Required = true, HelpText = "TTN MQTT API Client ID")]
	public string MqttClientID { get; set; }

	[Option('Z', "AzureIoTHubConnectionString", Required = true, HelpText = "Azure IoT Hub Connection string")]
	public string AzureIoTHubconnectionString { get; set; }
}

To keep things simple in this PoC I’m using an Azure IoT Hub specific (rather than a device specific connection string)

Azure IoT Hub Device shared access policy selection

After some trial and error I found the order of execution was important

  • Open MQTTnet connection to TTN host (but don’t configure any subscriptions)
  • Configure connection to TTN RESTful API
  • Retrieve list of V3EndDevices (paginated), then for each V3EndDevice
    • Open connection to Azure IoT Hub using command line connection string + TTN Device ID
    • Call DeviceClient.SetReceiveMessageHandlerAsync to specify ReceiveMessageCallback and additional context information for processing Azure IoT Hub downlink messages.
    • Store DeviceClient instance in ObjectCache using DeviceID as key
  • Configure the MQTTnet recived message handler
  • Subscribe to uplink messages from all the V3EndDevices in the specified application.
private static async Task ApplicationCore(CommandLineOptions options)
{
	MqttFactory factory = new MqttFactory();
	mqttClient = factory.CreateMqttClient();

#if DIAGNOSTICS
	Console.WriteLine($"baseURL: {options.ApiBaseUrl}");
	Console.WriteLine($"APIKey: {options.ApiKey}");
	Console.WriteLine($"ApplicationID: {options.ApiApplicationID}");
	Console.WriteLine($"AazureIoTHubconnectionString: {options.AzureIoTHubconnectionString}");
	Console.WriteLine();
#endif

	try
	{
		// First configure MQTT, open connection and wire up disconnection handler. 
		// Can't wire up MQTT received handler as at this stage AzureIoTHub devices not connected.
		mqttOptions = new MqttClientOptionsBuilder()
			.WithTcpServer(options.MqttServerName)
			.WithCredentials(options.MqttApplicationID, options.MqttAccessKey)
			.WithClientId(options.MqttClientID)
			.WithTls()
			.Build();

		mqttClient.UseDisconnectedHandler(new MqttClientDisconnectedHandlerDelegate(e => MqttClientDisconnected(e)));

		await mqttClient.ConnectAsync(mqttOptions);

		// Prepare the HTTP client to be used in the TTN device enumeration
		using (HttpClient httpClient = new HttpClient())
		{
			EndDeviceRegistryClient endDeviceRegistryClient = new EndDeviceRegistryClient(options.ApiBaseUrl, httpClient)
			{
				ApiKey = options.ApiKey
			};

			// Retrieve list of devices page by page
			V3EndDevices endDevices = await endDeviceRegistryClient.ListAsync(
				options.ApiApplicationID, 
				field_mask_paths: DevicefieldMaskPaths, 
				limit: options.DevicePageSize);
			if ((endDevices != null) && (endDevices.End_devices != null)) // If no devices returns null rather than empty list
			{
				foreach (V3EndDevice endDevice in endDevices.End_devices)
				{
					// Display the device info+attributes then connect device to Azure IoT Hub
#if DEVICE_FIELDS_MINIMUM
					Console.WriteLine($"EndDevice ID: {endDevice.Ids.Device_id}");
#else
					Console.WriteLine($"Device ID: {endDevice.Ids.Device_id} Name: {endDevice.Name} Description: {endDevice.Description}");
					Console.WriteLine($"  CreatedAt: {endDevice.Created_at:dd-MM-yy HH:mm:ss} UpdatedAt: {endDevice.Updated_at:dd-MM-yy HH:mm:ss}");
#endif

#if DEVICE_ATTRIBUTES_DISPLAY
					if (endDevice.Attributes != null)
					{
						Console.WriteLine("  EndDevice attributes");

						foreach (KeyValuePair<string, string> attribute in endDevice.Attributes)
						{
							Console.WriteLine($"    Key: {attribute.Key} Value: {attribute.Value}");
						}
					}
#endif
					try
					{
						DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(
							options.AzureIoTHubconnectionString, 
							endDevice.Ids.Device_id, 
							TransportType.Amqp_Tcp_Only);

						await deviceClient.OpenAsync();

						await deviceClient.SetReceiveMessageHandlerAsync(
							AzureIoTHubClientReceiveMessageHandler,
							new AzureIoTHubReceiveMessageHandlerContext()
							{
								DeviceId = endDevice.Ids.Device_id,
								ApplicationId = endDevice.Ids.Application_ids.Application_id,
							});

						DeviceClients.Add(endDevice.Ids.Device_id, deviceClient, cacheItemPolicy);
					}
					catch( Exception ex)
					{
						Console.WriteLine($"Azure IoT Hub OpenAsync failed {ex.Message}");
					}
				}
			}
		}

		// At this point all the AzureIoT Hub deviceClients setup and ready to go so can enable MQTT receive
		mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClientApplicationMessageReceived(e)));

		// This may shift to individual device subscriptions
		string uplinktopic = $"v3/{options.MqttApplicationID}/devices/+/up";

		await mqttClient.SubscribeAsync(uplinktopic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);
	}
	catch(Exception ex)
	{
		Console.WriteLine($"Main {ex.Message}");
		Console.WriteLine("Press any key to exit");
		Console.ReadLine();
		return;
	}

	while (!Console.KeyAvailable)
	{
		Console.Write(".");
		await Task.Delay(1000);
	}

	// Consider ways to mop up connections

	Console.WriteLine("Press any key to exit");
	Console.ReadLine();
}

When I was initially looking at Azure Deviceclient I would of had to have created a thread (which would have been blocked most of the time) for each device. This implementation issued was removed by the introduction of the DeviceClient SetReceiveMessageHandlerAsync method in release 1.33.0.

Currently the application just displays the Cloud to Device(C2D) message payload plus diagnostic information, and the CompleteAsync method is called so the message is dequeued.

private async static Task AzureIoTHubClientReceiveMessageHandler(Message message, object userContext)
{
	AzureIoTHubReceiveMessageHandlerContext receiveMessageHandlerConext = (AzureIoTHubReceiveMessageHandlerContext)userContext;

	DeviceClient deviceClient = (DeviceClient)DeviceClients.Get(receiveMessageHandlerConext.DeviceId);

	using (message)
	{
		Console.WriteLine();
		Console.WriteLine();
		Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} Azure IoT Hub downlink message");
		Console.WriteLine($" ApplicationID: {receiveMessageHandlerConext.ApplicationId}");
		Console.WriteLine($" DeviceID: {receiveMessageHandlerConext.DeviceId}");
#if DIAGNOSTICS_AZURE_IOT_HUB
		Console.WriteLine($" Cached: {DeviceClients.Contains(receiveMessageHandlerConext.DeviceId)}");
		Console.WriteLine($" MessageID: {message.MessageId}");
		Console.WriteLine($" DeliveryCount: {message.DeliveryCount}");
		Console.WriteLine($" EnqueuedTimeUtc: {message.EnqueuedTimeUtc}");
		Console.WriteLine($" SequenceNumber: {message.SequenceNumber}");
		Console.WriteLine($" To: {message.To}");
#endif
		string messageBody = Encoding.UTF8.GetString(message.GetBytes());
		Console.WriteLine($" Body: {messageBody}");
#if DOWNLINK_MESSAGE_PROPERTIES_DISPLAY
		foreach (var property in message.Properties)
		{
			Console.WriteLine($"   Key:{property.Key} Value:{property.Value}");
		}
#endif

		await deviceClient.CompleteAsync(message);

		Console.WriteLine();
	}
}

Currently the application just displays the Cloud to Device(D2C) message payload plus diagnostic information, displaying the payload fields if the message format has been configured and successfully processed.

private static void MqttClientApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
	if (e.ApplicationMessage.Topic.EndsWith("/up"))
	{
		PayloadUplinkV3 payload = JsonConvert.DeserializeObject<PayloadUplinkV3>(e.ApplicationMessage.ConvertPayloadToString());

		Console.WriteLine();
		Console.WriteLine();
		Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} TTN Uplink message");
#if DIAGNOSTICS_MQTT
		Console.WriteLine($" ClientId:{e.ClientId} Topic:{e.ApplicationMessage.Topic}");
		Console.WriteLine($" Cached: {DeviceClients.Contains(payload.EndDeviceIds.DeviceId)}");
#endif
		Console.WriteLine($" ApplicationID: {payload.EndDeviceIds.ApplicationIds.ApplicationId}");
		Console.WriteLine($" DeviceID: {payload.EndDeviceIds.DeviceId}");
		Console.WriteLine($" Port: {payload.UplinkMessage.Port} ");
		Console.WriteLine($" Payload raw: {payload.UplinkMessage.PayloadRaw}");

		if (payload.UplinkMessage.PayloadDecoded != null)
		{
			Console.WriteLine($" Payload decoded: {payload.UplinkMessage.PayloadRaw}");
			EnumerateChildren(1, payload.UplinkMessage.PayloadDecoded);
		}

		Console.WriteLine();
	}
	else
	{
		Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} ClientId: {e.ClientId} Topic: {e.ApplicationMessage.Topic}");
	}
}
dotNet Core Console application displaying simulated uplink and downlink messages.
Simulating C2D messages with AzureIoTExplorer
Simulating D2C messages with TTN Device console

In the MQTT received message handler.

Console.WriteLine($" Cached: {DeviceClients.Contains(receiveMessageHandlerConext.DeviceId)}");

and Azure DeviceClient received message handler.

Console.WriteLine($" Cached: {DeviceClients.Contains(receiveMessageHandlerConext.DeviceId)}");

check that the specified TTN device ID is in the DeviceClients ObjectCache

TTN V3 EndDevice API Basic Client

The next step was to enumerate all the EndDevices of a The Things Network(TTN) Application and display their attributes. I have to establish an Azure DeviceClient connection to an Azure IoT Hub for each TTN EndDevice to get downlink messages. To do this I will have to enumerate the TTN Applications in the instance then enumerate the LoRaWAN EndDevices.

using (HttpClient httpClient = new HttpClient())
{
	EndDeviceRegistryClient endDeviceRegistryClient = new EndDeviceRegistryClient(baseUrl, httpClient)
	{
		ApiKey = apiKey
	};

	try
	{
#if FIELDS_MINIMUM
		string[] fieldMaskPathsDevice = { "attributes" }; // think this is the bare minimum required for integration
#else
		string[] fieldMaskPathsDevice = { "name", "description", "attributes" };
#endif
		V3EndDevices endDevices = await endDeviceRegistryClient.ListAsync(applicationID, field_mask_paths:fieldMaskPathsDevice);
		if ((endDevices != null) && (endDevices.End_devices != null)) // If there are no devices returns null rather than empty list
		{
			foreach (V3EndDevice endDevice in endDevices.End_devices)
			{
#if FIELDS_MINIMUM
				Console.WriteLine($"EndDevice ID:{endDevice.Ids.Device_id}");
#else
				Console.WriteLine($"Device ID:{endDevice.Ids.Device_id} Name:{endDevice.Name} Description:{endDevice.Description}");
				Console.WriteLine($"  CreatedAt: {endDevice.Created_at:dd-MM-yy HH:mm:ss} UpdatedAt: {endDevice.Updated_at:dd-MM-yy HH:mm:ss}");
#endif
				if (endDevice.Attributes != null)
				{
					Console.WriteLine("  EndDevice attributes");

					foreach (KeyValuePair<string, string> attribute in endDevice.Attributes)
					{
						Console.WriteLine($"    Key: {attribute.Key} Value: {attribute.Value}");
					}
				}
				Console.WriteLine();
			}
		}
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}

	Console.WriteLine("Press <enter> to exit");
	Console.ReadLine();
}

Like the applicationRegistryClient.ListAsync call the endDeviceRegistryClient.ListAsync also returns null rather than an empty list.

I also wanted to explore whether I could use EndDevice attributes to populate the ClientOptions ModelId of my CreateFromConnectionString call. The modelId would contain the Digital Twins Definition Language(DTDL) ID of the LoRaWAN device so it could be automatically provisioned.

TTN V3 Application API Basic Paging and Filtering Client

The next step was to enumerate The Things Network(TTN) Applications so I could connect only to the required Azure IoT hub(s). There would also be a single configuration setting for the client (establish a connection for every TTN application, or don’t establish a connection for any) and this could be overridden with a TTN application attribute

long pageSize = long.Parse(args[3]);
Console.WriteLine($"Page size: {pageSize}");

Console.WriteLine();

using (HttpClient httpClient = new HttpClient())
{
	ApplicationRegistryClient applicationRegistryClient = new ApplicationRegistryClient(baseUrl, httpClient)
	{
		ApiKey = apiKey
	};

	try
	{
		int page = 1;

		string[] fieldMaskPathsApplication = { "attributes" }; // think this is the bare minimum required for integration

		V3Applications applications = await applicationRegistryClient.ListAsync(collaborator, field_mask_paths: fieldMaskPathsApplication, limit: pageSize, page: page);
		while ((applications != null) && (applications.Applications != null)) 
		{
			Console.WriteLine($"Applications:{applications.Applications.Count} Page:{page} Page size:{pageSize}");
			foreach (V3Application application in applications.Applications)
			{
				bool applicationIntegration = ApplicationAzureintegrationDefault;

				Console.WriteLine($"Application ID:{application.Ids.Application_id}");
				if (application.Attributes != null)
				{
					string ApplicationAzureIntegrationValue = string.Empty;
					if (application.Attributes.TryGetValue(ApplicationAzureIntegrationField, out ApplicationAzureIntegrationValue))
					{
						bool.TryParse(ApplicationAzureIntegrationValue, out applicationIntegration);
					}

					if (applicationIntegration)
					{
						Console.WriteLine("  Application attributes");

						foreach (KeyValuePair<string, string> attribute in application.Attributes)
						{
							Console.WriteLine($"   Key: {attribute.Key} Value: {attribute.Value}");
						}
					}
				}
				Console.WriteLine();
			}
			page += 1;
			applications = await applicationRegistryClient.ListAsync(collaborator, field_mask_paths: fieldMaskPathsApplication, limit: pageSize, page: page);
		};
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}

	Console.WriteLine("Press <enter> to exit");
	Console.ReadLine();
}

I Used the field_mask_paths parameter (don’t need created_at, updated_at, name etc.) to minimise the data returned to my client.

public async System.Threading.Tasks.Task<V3Applications> ListAsync(string collaborator_organization_ids_organization_id = null, string collaborator_user_ids_user_id = null, string collaborator_user_ids_email = null, System.Collections.Generic.IEnumerable<string> field_mask_paths = null, string order = null, long? limit = null, long? page = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
   var urlBuilder_ = new System.Text.StringBuilder();
   urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/applications?");
   if (collaborator_organization_ids_organization_id != null) 
   {
         urlBuilder_.Append(System.Uri.EscapeDataString("collaborator.organization_ids.organization_id") + "=").Append(System.Uri.EscapeDataString(ConvertToString(collaborator_organization_ids_organization_id, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
   }
   if (collaborator_user_ids_user_id != null) 
   {
         urlBuilder_.Append(System.Uri.EscapeDataString("collaborator.user_ids.user_id") + "=").Append(System.Uri.EscapeDataString(ConvertToString(collaborator_user_ids_user_id, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
   }
   if (collaborator_user_ids_email != null) 
   {
         urlBuilder_.Append(System.Uri.EscapeDataString("collaborator.user_ids.email") + "=").Append(System.Uri.EscapeDataString(ConvertToString(collaborator_user_ids_email, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
   }
   if (field_mask_paths != null) 
   {
         foreach (var item_ in field_mask_paths) { urlBuilder_.Append(System.Uri.EscapeDataString("field_mask.paths") + "=").Append(System.Uri.EscapeDataString(ConvertToString(item_, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); }
   }
   if (order != null) 
   {
         urlBuilder_.Append(System.Uri.EscapeDataString("order") + "=").Append(System.Uri.EscapeDataString(ConvertToString(order, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
   }
   if (limit != null) 
   {
         urlBuilder_.Append(System.Uri.EscapeDataString("limit") + "=").Append(System.Uri.EscapeDataString(ConvertToString(limit, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
   }
   if (page != null) 
   {
         urlBuilder_.Append(System.Uri.EscapeDataString("page") + "=").Append(System.Uri.EscapeDataString(ConvertToString(page, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
   }
}

I was hoping that there would be a away to further “shape” the returned data, but in the NSwag generated code the construction of the URL with field_mask_paths, order, limit, and page parameters meant this appears not to be possible.

TTN V3 Application API Basic Paging Client

The next step was to enumerate The Things Network(TTN) Applications and their attributes. I’m planning on using attributes to manage which applications (and in future EndDevices) are enabled in my Advanced Message Queuing Protocol(AMQP) client.

In the code I have left the different paging implementations which I trialled but abandoned.

using (HttpClient httpClient = new HttpClient())
{
	ApplicationRegistryClient applicationRegistryClient = new ApplicationRegistryClient(baseUrl, httpClient)
	{
		ApiKey = apiKey
	};

	try
	{
		int page = 1;
		string[] fieldMaskPathsApplication = { "attributes" };

		V3Applications applications = await applicationRegistryClient.ListAsync(collaborator, field_mask_paths: fieldMaskPathsApplication, limit:pageSize, page: page);
		while ((applications != null) && (applications.Applications != null))
		{ 
			Console.WriteLine($"Applications:{applications.Applications.Count} Page:{page} Page size:{pageSize}");
			foreach (V3Application application in applications.Applications)
			{
				Console.WriteLine($"Application ID:{application.Ids.Application_id}"); 
				if (application.Attributes != null)
				{
					Console.WriteLine("  Application attributes");

					foreach (KeyValuePair<string, string> attribute in application.Attributes)
					{
						Console.WriteLine($"   Key: {attribute.Key} Value: {attribute.Value}");
					}
				}
				Console.WriteLine();
			}
			page += 1;
			applications = await applicationRegistryClient.ListAsync(collaborator, field_mask_paths: fieldMaskPathsApplication, limit: pageSize, page: page);
		}
	}   
}

For each LoraWAN client I have to have an open connection to the Azure IoT hub to get Cloud to Device (C2D) messages so I’m looking at using connection pooling to reduce the overall number of connections.

I think the Azure ClientDevice library supports up to 995 devices per connection and has quiet a lot of additional functionality.

/// <summary>
/// contains Amqp Connection Pool settings for DeviceClient
/// </summary>
public sealed class AmqpConnectionPoolSettings
{
   private static readonly TimeSpan s_defaultConnectionIdleTimeout = TimeSpan.FromMinutes(2);
    private uint _maxPoolSize;
    internal const uint MaxDevicesPerConnection = 995; // IotHub allows upto 999 tokens per connection. Setting the threshold just below that.

    /// <summary>
    /// The default size of the pool
    /// </summary>
    /// <remarks>
    /// Allows up to 100,000 devices
    /// </remarks>
    private const uint DefaultPoolSize = 100;

    /// <summary>
    /// The maximum value that can be used for the MaxPoolSize property
    /// </summary>
     public const uint AbsoluteMaxPoolSize = ushort.MaxValue;

    /// <summary>
    /// Creates an instance of AmqpConnecitonPoolSettings with default properties
    /// </summary>
    public AmqpConnectionPoolSettings()
    {
       _maxPoolSize = DefaultPoolSize;
       Pooling = false;
    }

Whereas I think AMQPNetLite may support more, but will require me to implement more of the Azure IoT client interface

/// <summary>
/// The default maximum frame size used by the library.
/// </summary>
public const uint DefaultMaxFrameSize = 64 * 1024;
internal const ushort DefaultMaxConcurrentChannels = 8 * 1024;
internal const uint DefaultMaxLinkHandles = 256 * 1024;
internal const uint DefaultHeartBeatInterval = 90000;
internal const uint MinimumHeartBeatIntervalMs = 5 * 1000;

I have got todo some more research to see which library is easier/requires more code/complex/scales better.