<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adem Özkayıt on Medium]]></title>
        <description><![CDATA[Stories by Adem Özkayıt on Medium]]></description>
        <link>https://medium.com/@adem.ozkyt?source=rss-4f3b871c9534------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uv6IcFgD7vcAjf3pUBXjHA.jpeg</url>
            <title>Stories by Adem Özkayıt on Medium</title>
            <link>https://medium.com/@adem.ozkyt?source=rss-4f3b871c9534------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:19:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adem.ozkyt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[N-Layer vs Clean Architecture vs Hexagonal Architecture: Hangisini Tercih Etmeliyiz?]]></title>
            <link>https://medium.com/@adem.ozkyt/n-layer-vs-clean-architecture-vs-hexagonal-architecture-hangisini-tercih-etmeliyiz-e589fa42d4a7?source=rss-4f3b871c9534------2</link>
            <guid isPermaLink="false">https://medium.com/p/e589fa42d4a7</guid>
            <dc:creator><![CDATA[Adem Özkayıt]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 18:32:53 GMT</pubDate>
            <atom:updated>2025-11-16T19:40:40.500Z</atom:updated>
            <content:encoded><![CDATA[<p>Selamlar,</p><p>Bu yazımda yazılımcıların projelerini başlatırken kafalarını karıştıran mimari seçimi için çok popüler 3 mimariyi karşılaştırıp bunlardan bahsetmeye çalışacağım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BPBajjurJkO8V9geCr0Ew.png" /></figure><p>Uygulamalar büyüdükçe ortaya çıkan karmaşıklığı kontrol edebilmek ve değişiklikleri daha öngörülebilir şekilde yönetebilmek için belirli bir mimari düzen şart hâline gelir. Bu düzeni sağlamanın temel yollarından biri, sistemi görevlerine ve sorumluluklarına göre bölümlere ayırmaktır. Kodun mantıklı katmanlara ayrılması, projede <strong>yeniden kullanılabilirliği artırır</strong>, <strong>gereksiz tekrarları azaltır. </strong>Bu nedenle mimariler, yazılım projelerinde kod organizasyonunu iyileştirmek ve modülerliği artırmak için sıkça tercih edilir. Uygulamanın yapısına göre bu mimariler çeşitli şekillerde modellenebilir.</p><h3>N-Layer Mimarisi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GfqRW8mwz7TjHjqXMQWrlw.png" /></figure><p><strong>N-Layer</strong>, yani N-katmanlı mimari uygulamayı belirli sorumluluklara ayrılmış katmanlar hâlinde organize eden en klasik mimaridir. Genellikle üç temel katman bulunur:</p><ul><li><strong>Presentation Layer</strong>: Controller, View, API Endpointleri</li><li><strong>Business Layer</strong>: İş kuralları, servisler</li><li><strong>Data Access Layer</strong>: Repository, EF Core, SQL sorguları</li></ul><p>Bu yaklaşımın amacı, her<strong> </strong>katmanın kendi görevine odaklanmasını <strong>sağlamak</strong> ve kodun daha düzenli görünmesini kolaylaştırmaktır. Öğrenmesi kolaydır ve küçük-orta ölçekli projelerde hızlıca sonuç verir. Ancak zaman içinde büyüyen projelerde iş kuralları ile altyapı (EF Core, DB kodları vs.) birbirine karışarak katmanlar arası bağımlılıkların artmasına neden olabilir. Bu nedenle projenin veritabanının değişmesi, kullanılan framework’ün değişmesi gibi nedenlere refactor edilmesi gerekirse ekstra bir çaba sarf ettirebilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*yYeZvPyAVH7wXk6LFDUp1Q.png" /><figcaption>Basit bir CQRS kullanımı ile N-Layer örneği</figcaption></figure><h3>Clean Mimarisi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nVIB5n8eDAqTWWfCXZ1gtA.png" /><figcaption>Clean mimarisinin bir alt türü olan görselde ki onion(soğan) mimarisinden anlatım gerçekleştireceğim.</figcaption></figure><p><strong>Clean Architecture</strong>, yani temiz mimari klasik N-Layer yapısının bir adım ötesine geçerek uygulamanın kalbinde domain’i konumlandırır. En önemli prensibi <strong>“bağımlılıklar içeri doğru akar”</strong> kuralıdır. Yani domain, hiçbir dış katmanı bilmez; tüm dış katmanlar domain’i bilir.</p><p>Temel katmanlar:</p><ul><li><strong>Domain</strong>: Entity, Interface, Services dosyalarında saf iş kuralları</li><li><strong>Application</strong>: DTO, CQRS, MediatR handler’ları, Mapping</li><li><strong>Infrastructure/Persistance </strong>: EF Core, dış servisler, cache, mail gibi teknik detaylar ve Veri tabanı işlemleri için Repositories</li><li><strong>Presentation</strong>: Controller, API, UI elementleri.</li></ul><p>Bu mimari, modülerliği artırır, test yazmayı kolaylaştırır ve uzun vadeli projelerde sürdürülebilirliği ciddi şekilde yükseltir. Potansiyel teknoloji değişikliklerine uygundur Orta ve büyük projelerde özellikle tercih edilir. Fazla dosya oluşturmayı gerektirir ve geliştirme yapılacağı zaman oldukça fazla dosya ile işlem yapılır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*lirUvO2AVwP7kUsbpzZHuw.png" /><figcaption>Soğan mimarisi adında popüler bir clean mimari yaklaşımı ile örnek dosya yapısı görselde ki gibidir.</figcaption></figure><h3>Altıgen Mimarisi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eQ9eZmDvLLpnIaTK940C5w.png" /></figure><p>Hexagonal Architecture, yani Altıgen Mimari, uygulamanın çekirdeğini (domain logic) dış dünyadan tamamen izole etmeyi amaçlayan bir yapıdır. Temel prensibi, <strong>“uygulama çekirdeği dış dünyayı bilmez; dış dünya çekirdeği bilir”</strong> kuralıdır. Bu izolasyon <strong>Port</strong> ve <strong>Adapter</strong> yapılarıyla sağlanır.</p><p>Uygulama çekirdeği sadece <strong>portlar</strong> ile konuşur; veritabanı, e-postalar, API çağrıları gibi tüm dış sistemler ise bu portları implement eden <strong>adapter’lar</strong> üzerinden çalışır.</p><p><strong>Temel katmanlar:</strong></p><ul><li><strong>Domain/Application Core:</strong><br> Entity, Value Object, Use Case, saf iş kuralları ve domain mantığı. Bu katman dış dünyaya tamamen kapalıdır.</li><li><strong>Ports:</strong><br> Core’un dış dünya ile konuştuğu soyut arabirimlerdir.</li></ul><p>-Primary Ports → Web/Mobil isteklerini içeri alır (Controller gibi).</p><p>-Secondary Ports → Core’un ihtiyaç duyduğu dış servisleri belirtir (Repository Interface, Email Interface gibi).</p><ul><li><strong>Adapters (Infrastructure):</strong><br> Portların gerçek implementasyonlarıdır.<br> EF Core repository’leri, MongoDB adapter’ları, e-mail servis adapter’ları, Redis caching, mesaj kuyruğu bağlantıları gibi teknik detaylar burada bulunur.</li></ul><p>Bu mimari, yüksek soyutlama seviyesi sayesinde değişime oldukça dayanıklıdır; altyapı teknolojileri (veritabanı, mesaj kuyruğu, dış API servisleri vb.) değişse bile domain etkilenmez.</p><p>Ancak başlangıçta fazla soyutlama gerektirdiği için küçük ve basit projelerde gereğinden fazla karmaşık gelebilir. Büyük ölçekli, dış entegrasyonların yoğun olduğu sistemlerde ise oldukça güçlü bir mimaridir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*CIrOUvQ8R6qWMrMlMk3Eeg.png" /><figcaption>Hexagonal mimari ile örnek dosya yapısı görselde ki gibidir.</figcaption></figure><h3>Sonuç</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHu1TsFnmDLZpra0BL3AaQ.png" /><figcaption>Genel karşılaştırma görselde ki gibi yapılabilir.</figcaption></figure><p>Yazılım geliştiricisi olarak proje seçimini doğru mimariyle yapmak uzun vadede:</p><ul><li>Teknik borcu azaltır</li><li>Refactoring ihtiyacını düşürür</li><li>Kodun test edilebilirliğini artırır</li><li>Ekibe yeni katılanların uyum süresini hızlandırır</li></ul><p>Her mimarinin bir doğru kullanım alanı vardır.<br>Önemli olan, <strong>ölçek + domain karmaşıklığı + ekip yapısı</strong> üçlüsüne göre karar vermektir.</p><p>Umarım yazım sizler için faydalı olmuştur, daha fazlası için takipte kalın!</p><p>İyi çalışmalar 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e589fa42d4a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Claude Sonnet with .NET: A Comprehensive Guide]]></title>
            <link>https://medium.com/@adem.ozkyt/use-claude-sonnet-with-net-a-comprehensive-guide-70e6f2b3fcc1?source=rss-4f3b871c9534------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e6f2b3fcc1</guid>
            <dc:creator><![CDATA[Adem Özkayıt]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 15:44:38 GMT</pubDate>
            <atom:updated>2025-01-14T15:44:38.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Use Claude Sonnet with .NET: A Comprehensive Guide</h3><p>Artificial intelligence tools like Claude Sonnet have the potential to transform how applications handle data analysis and interaction. In this guide, I will walk you through a practical implementation of Claude Sonnet in a .NET application, showcasing how to build an interactive system that leverages its advanced AI capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TVPSdP-YC-QYbU5aHACYQ.png" /></figure><h3>Content</h3><p><strong>1) What is Claude Sonnet?</strong></p><p><strong>2) Project Overview</strong></p><p><strong>3) AWS &amp; Claude Sonnet Configurations</strong></p><p><strong>4)</strong> .<strong>NET CORE WEB APPLICATION SETUP &amp; AI INTEGRATION</strong></p><p><strong>5) Service &amp; Controller Methods</strong></p><p><strong>6) Conclusion</strong></p><h3>1) What is Claude Sonnet?</h3><p>Claude Sonnet is a state-of-the-art AI model developed by Anthropic, designed to handle various natural language and content analysis tasks. Integrated into applications via the Amazon Bedrock platform, Claude Sonnet excels in:</p><ul><li><strong>Understanding complex queries</strong> and generating human-like responses.</li><li><strong>Analyzing structured and unstructured data</strong> such as text, images, and documents.</li><li><strong>Providing high accuracy and efficiency</strong> in real-world AI applications.</li></ul><p>This guide demonstrates how to integrate Claude Sonnet into a .NET application for functionalities such as retrieving detailed information, analyzing images, and processing PDFs. The project aims to highlight the ease of integration and the capabilities of Claude Sonnet in creating intelligent applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFLGzTKSkxZXO9jsmJp_Og.jpeg" /></figure><h3>2) Project Overview</h3><p>The primary goal of this project is to explore how Claude Sonnet can be integrated into a .NET application to deliver AI-driven features. The application supports:</p><ol><li><strong>Information Retrieval</strong>: Users can enter keywords and receive detailed information about specific animals.</li><li><strong>Image Analysis</strong>: Users can upload animal images for analysis and receive insights.</li><li><strong>PDF Analysis</strong>: Users can upload PDF documents containing content about animals and receive extracted insights.</li></ol><p>The full project code is available on <a href="https://github.com/AdmOzk/LearnAnimal">GitHub</a>, which you can reference for additional details and implementation specifics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXO82Ni-tyjEBjIfJE2dog.png" /></figure><h3>3) <strong>AWS &amp; Claude Sonnet Configurations</strong></h3><h4><strong>3.1) AWS Setup</strong></h4><p>1)Create an AWS Account (if you don’t have one) Go to <a href="https://aws.amazon.com/">https://aws.amazon.com</a> and create an account</p><p>2) Complete the signup process, including <strong>identity verification</strong> and <strong>payment details</strong>.</p><h4><strong>3.2) Enable Amazon Bedrock Service</strong></h4><p>Amazon Bedrock provides access to Claude Sonnet and other foundation models.</p><p>1)Go to <strong>AWS Management Console</strong>.</p><p>2)Search for <strong>Amazon Bedrock</strong> in the <strong>Search Bar</strong>.</p><p>3)Click <strong>Amazon Bedrock</strong> and <strong>Request Access</strong> if it’s not available by default.</p><p><strong>Note</strong>: Bedrock may require special access as it’s not available in all regions. AWS will review your request.</p><h4>3.3) Retrieve your API Credentials</h4><p>from the<a href="https://yourorganization.awsapps.com/start/#/?tab=accounts"> </a><a href="https://yourorganization.awsapps.com/start/#/?tab=accounts">Aws access portal</a> page (example link provided) By clicking the “access keys” button you should retrieve your</p><ul><li><strong>Access Key Id</strong></li><li><strong>Secret Access Key</strong></li><li><strong>Session Token</strong></li><li><strong>Region (US, EU, etc.)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*ahJm0ThDmC3Iqvw483sLag.png" /></figure><h3>4) .<strong>NET APPLICATION SETUP &amp; AI INTEGRATION</strong></h3><p><strong>4.1) Create a .NET CORE MVC or WEB API project</strong></p><p><strong>4.2) Install SDK Packages</strong> :<br>AWSSDK.Bedrock<br>AWSSDK.BedrockRuntime<br>AWSSDK.Core <br>(to use AWS with your application)</p><pre>dotnet add package AWSSDK.Bedrock<br>dotnet add package AWSSDK.BedrockRuntime<br>dotnet add package AWSSDK.Core</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bBDPRcBW1BPbKe5ga4N3w.png" /></figure><p><strong>4.3)</strong> <strong>Configure your appsettings.json </strong><br>retrieve your credentials as explained in part “3.3” <br>replace your credentials with the example credentials below</p><pre>{<br>  &quot;AWS&quot;: {<br>    &quot;AccessKeyId&quot;: &quot;YourAccessKeyId&quot;,<br>    &quot;SecretAccessKey&quot;: &quot;YourSecretAccessKey&quot;,<br>    &quot;SessionToken&quot;: &quot;YourSessionToken&quot;,<br>    &quot;Region&quot;: &quot;eu-central-1&quot; // Write the region used in your model , example for eu (Frankfurt). <br>  },<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;<br>}</pre><h3>5) <strong>Service &amp; Controller Methods</strong></h3><p><strong>5.1 )</strong> Create a Service File and Inject credentials from the appsettings.json file, you can implement the same code below.</p><pre>using Microsoft.Extensions.Configuration;<br>using System.IO;<br>using System.Text;<br>using System.Text.Json;<br>using System.Threading.Tasks;<br><br>namespace LearnAnimal.Services<br>{<br>    public class ClaudeService<br>    {<br>        private readonly AmazonBedrockRuntimeClient _bedrockClient;<br><br>        //aws configurations from appsettings.<br>        public ClaudeService(IConfiguration configuration)<br>        {<br>            var accessKeyId = configuration[&quot;AWS:AccessKeyId&quot;];<br><br>            var secretAccessKey = configuration[&quot;AWS:SecretAccessKey&quot;];<br><br>            var sessionToken = configuration[&quot;AWS:SessionToken&quot;];<br><br>            var region = configuration[&quot;AWS:Region&quot;];<br><br>            var credentials = new SessionAWSCredentials(accessKeyId, secretAccessKey, sessionToken);<br><br>            var config = new AmazonBedrockRuntimeConfig<br>            {<br>                RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName(region)<br>            };<br><br>            _bedrockClient = new AmazonBedrockRuntimeClient(credentials, config);<br>        }<br>}</pre><p>5.2) Implement the definition of the service in “Program.cs” with the code line below</p><pre>builder.Services.AddTransient&lt;ClaudeService&gt;();</pre><p>We are ready to use Claude Sonnet AI to launch our special project!</p><p>5.3.1) In-service file we will send requests to Claude AI API, let&#39;s start with <strong>TEXT REQUEST </strong>:</p><p>In this section, we will cover how to create a method that sends text requests to the Claude Sonnet AI model through the Amazon Bedrock platform. This method will process user input, convert it to a JSON-compatible format, and interact with the Claude Sonnet API to retrieve responses.</p><h4>Method: GetAnimalInfoAsync</h4><p>The GetAnimalInfoAsync method is designed to take an animal name as input and return a paragraph of detailed information about that animal by communicating with the Claude Sonnet API. Let&#39;s walk through each step of the method to understand its functionality in detail.</p><pre>//method for text input<br>public async Task&lt;string&gt; GetAnimalInfoAsync(string animalName)<br>{<br>    //Step 1 : System Prompt<br>    var systemPrompt = $&quot;Animal: {animalName}. Give a paragraph of detailed information about this animal.&quot;;<br><br>     // Step 2 : Messages Array<br>    //specify input type<br>    var input = new<br>    {<br>        system = systemPrompt,<br><br>        messages = new[]<br>        {<br>            new<br>            {<br>                role = &quot;user&quot;,<br><br>                content = $&quot;Give information about animal: {animalName}&quot;<br>            }<br>        },<br>         // Step 3 <br>        //model parameters<br>        max_tokens = 1000,<br><br>        temperature = 0.1,<br><br>        top_p = 0.9,<br><br>        top_k = 5,<br><br>        stop_sequences = new string[] { },<br><br>        anthropic_version = &quot;bedrock-2023-05-31&quot;<br>    };<br>     <br>     // Step 4<br>    //Convert input to json.<br>    var inputJson = JsonSerializer.Serialize(input);<br><br>    var request = new InvokeModelRequest<br>    {<br>        ModelId = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;,<br><br>        ContentType = &quot;application/json&quot;,<br><br>        Body = new MemoryStream(Encoding.UTF8.GetBytes(inputJson))<br>    };<br>      <br>      // Step 5<br>    //extract the response from ai model<br>    var response = await _bedrockClient.InvokeModelAsync(request);<br><br>    using (var reader = new StreamReader(response.Body))<br>    {<br>        var responseBody = await reader.ReadToEndAsync();<br><br>        var jsonDocument = JsonDocument.Parse(responseBody);<br><br>        var root = jsonDocument.RootElement;<br>      <br>        // Step 6 <br>        // Proccess Result<br>        if (root.TryGetProperty(&quot;content&quot;, out var contentArray) &amp;&amp; contentArray.ValueKind == JsonValueKind.Array)<br>        {<br>            foreach (var content in contentArray.EnumerateArray())<br>            {<br>                if (content.TryGetProperty(&quot;text&quot;, out var textElement) &amp;&amp; textElement.ValueKind == JsonValueKind.String)<br>                {<br>                    return textElement.GetString();<br>                }<br>            }<br>        }<br><br>        return &quot;No information found for this animal.&quot;;<br>    }<br>}</pre><h4>Detailed Explanation of Steps</h4><ol><li><strong>System Prompt</strong>: This is a predefined message that sets the context for the AI. In this example, the prompt instructs the AI to provide a paragraph of detailed information about the specified animal.</li><li><strong>Messages Array</strong>: The input includes a series of messages exchanged between the user and the AI. Each message has a role (either &quot;system&quot; or &quot;user&quot;) and content (the actual message text).</li><li><strong>Model Parameters</strong>: These are settings that control the behavior of the AI model:</li></ol><ul><li>max_tokens: Limits the length of the response.</li><li>temperature: Controls the randomness of the response. Lower values make the response more predictable.</li><li>top_p and top_k: Control the diversity of the response by limiting the sampling to the top tokens.</li><li>stop_sequences: Defines when the AI should stop generating text.</li></ul><p><strong>4. JSON Serialization</strong>: The input data must be serialized into a JSON format before being sent to the API. This is done using the JsonSerializer.Serialize() method.</p><p><strong>5. API Request</strong>: The InvokeModelRequest object is used to configure and send the request to the Claude Sonnet model. It includes the model ID, content type, and request body.</p><p><strong>6. Response Handling</strong>: The method reads the response from the API, parses the JSON structure, and extracts the relevant text content. If the response contains a content property with an array of text messages, it retrieves the text and returns it.</p><p>5.3.2 ) Use this method in the <strong>Controller<br>after a simple </strong>Dependency Injection in the Controller file <br>(such as the code below) The method from service is ready to call.</p><pre>  public class HomeController : Controller<br>  {<br>      // Dependency injection<br>      private readonly ClaudeService _claudeService;<br><br>      public HomeController(ClaudeService claudeService)<br>      {<br>          _claudeService = claudeService;<br>      }<br>}</pre><p>To call the method You can define an endpoint or controller method like the code below.</p><pre>   // example to use in MVC<br>  [HttpPost]<br>  public async Task&lt;IActionResult&gt; AnimalInfo(string animalName)<br>  {<br>      if (string.IsNullOrEmpty(animalName))<br>      {<br>          ViewBag.Error = &quot;Please enter an animal name.&quot;;<br>          return View();<br>      }<br><br>      // Method from service.<br>      var info = await _claudeService.GetAnimalInfoAsync(animalName);<br>      ViewBag.AnimalInfo = info;<br>      return View();<br>  }<br><br></pre><p>5.4.1) <br><strong>IMAGE REQUEST </strong>:</p><h4>Method: AnimalImage</h4><p>The AnimalImage method processes image-based input to recognize animals and retrieve related information. This method converts a PNG image to a Base64 string, sends it to the Claude Sonnet API, and extracts the AI-generated response. Let&#39;s break down the method step-by-step.</p><pre>       // Method for image input<br>// Claude Sonnet 3.0 version supports only PNG format.<br>public async Task&lt;string&gt; AnimalImage(string base64Image)<br>{<br>    // Step 1: Define the system prompt<br>    var systemPrompt = $&quot;Image: {base64Image}. What is this animal? Give short information. (English)&quot;;<br><br>    // Step 2: Specify the input type<br>    // The input includes the Base64 image string and <br>    // metadata indicating that the input type is an image.<br>    var input = new<br>    {<br>        system = systemPrompt,<br>        messages = new[]<br>        {<br>            new<br>            {<br>                role = &quot;user&quot;,<br>                content = new[]<br>                {<br>                    new<br>                    {<br>                        type = &quot;image&quot;,<br>                        source = new<br>                        {<br>                            type = &quot;base64&quot;,<br>                            media_type = &quot;image/png&quot;,<br>                            data = base64Image<br>                        }<br>                    }<br>                }<br>            }<br>        },<br>        max_tokens = 1000,<br>        temperature = 0.1,<br>        top_p = 0.9,<br>        top_k = 5,<br>        stop_sequences = new string[] { },<br>        anthropic_version = &quot;bedrock-2023-05-31&quot;<br>    };<br><br>    // Step 3: Convert input to JSON<br>    var inputJson = JsonSerializer.Serialize(input);<br><br>    // Step 4: Create and send the API request<br>    var request = new InvokeModelRequest<br>    {<br>        ModelId = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;,<br>        ContentType = &quot;application/json&quot;,<br>        Body = new MemoryStream(Encoding.UTF8.GetBytes(inputJson))<br>    };<br><br>    // Step 5: Extract the response from the AI model<br>    var response = await _bedrockClient.InvokeModelAsync(request);<br><br>    using (var reader = new StreamReader(response.Body))<br>    {<br>        var responseBody = await reader.ReadToEndAsync();<br>        var jsonDocument = JsonDocument.Parse(responseBody);<br>        var root = jsonDocument.RootElement;<br><br>        // Step 6: Parse the response to extract the text content<br>        if (root.TryGetProperty(&quot;content&quot;, out var contentArray) &amp;&amp; contentArray.ValueKind == JsonValueKind.Array)<br>        {<br>            foreach (var content in contentArray.EnumerateArray())<br>            {<br>                if (content.TryGetProperty(&quot;text&quot;, out var textElement) &amp;&amp; textElement.ValueKind == JsonValueKind.String)<br>                {<br>                    return textElement.GetString();<br>                }<br>            }<br>        }<br><br>        // If no information is found, return a default message<br>        return &quot;No information found for this animal.&quot;;<br>    }<br>}</pre><h4>Difference from the previous method</h4><p><strong>Image Input</strong>: The AnimalImage method specifies the input as an image by including additional metadata, such as type, media_type, and data fields in the content array.</p><p>5.4.2 ) To use this method in the controller implement the same dependency injection discussed in 5.3.2</p><p>To call the method You can define an endpoint or controller method like the code below. Note that <em>the Image should be in base64 format, If you attempt to send a raw image file directly to the API without Base64 encoding, the request will fail because the Claude Sonnet API won’t be able to parse the binary data within the JSON request structure.</em></p><pre>  [HttpPost]<br>  public async Task&lt;IActionResult&gt; AnalyzeImage(IFormFile image)<br>  {<br>      if (image == null || image.Length == 0)<br>      {<br>          ViewBag.Error = &quot;Please upload a valid PNG image.&quot;;<br>          return View();<br>      }<br><br>      try<br>      {<br>          // Convert the image to Base64 format<br>          string base64Image;<br>          using (var memoryStream = new MemoryStream())<br>          {<br>              await image.CopyToAsync(memoryStream);<br>              var imageBytes = memoryStream.ToArray();<br>              base64Image = Convert.ToBase64String(imageBytes);<br>          }<br><br>          // Call Method from Service <br>          var result = await _claudeService.AnimalImage(base64Image);<br>          ViewBag.AnalysisResult = result;<br>      }<br>      catch (Exception ex)<br>      {<br>          ViewBag.Error = $&quot;An error occurred: {ex.Message}&quot;;<br>      }<br><br>      return View();<br>  }</pre><p>5.5.1) <br><strong>PDF REQUEST </strong>:</p><h4>Method: AnalyzePdfAsync</h4><p>The AnalyzePdfAsync method demonstrates how to handle PDF input by converting the file into Base64 format and sending it to the Claude Sonnet API. However, it&#39;s important to note that <strong>Claude Sonnet 3.0 does not support PDF input</strong>. This method shows how to structure the request if future versions of Claude Sonnet provide PDF support.</p><pre>     //method for pdf input<br>     // !!! NOT SUPPORTED FOR CLAUDE SONNET 3.0 VERSION <br>     public async Task&lt;string&gt; AnalyzePdfAsync(string base64Pdf)<br>     {<br>         var systemPrompt = $&quot;PDF: {base64Pdf}. Give information about the animals in this PDF. (English)&quot;;<br><br>         //specify input type.<br>         var input = new<br>         {<br>             system = systemPrompt,<br><br>             messages = new[]<br>             {<br>         new<br>         {<br>             role = &quot;user&quot;,<br>             content = new[]<br>             {<br>                 new<br>                 {<br>                     type = &quot;document&quot;,<br>                     source = new<br>                     {<br>                         type = &quot;base64&quot;,<br>                         media_type = &quot;application/pdf&quot;,<br>                         data = base64Pdf<br>                     }<br>                 },<br>               <br>             }<br>         }<br>     },<br>     //model parameters<br>             max_tokens = 1500,<br>             temperature = 0.1,<br>             top_p = 0.9,<br>             top_k = 5,<br>             stop_sequences = new string[] { },<br>             anthropic_version = &quot;bedrock-2023-05-31&quot;<br>         };<br><br>         //convert input to json.<br>         var inputJson = JsonSerializer.Serialize(input);<br><br>         var request = new InvokeModelRequest<br>         {<br>             ModelId = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;,<br>             ContentType = &quot;application/json&quot;,<br>             Body = new MemoryStream(Encoding.UTF8.GetBytes(inputJson))<br>         };<br><br>         //extract the response from ai model<br>         var response = await _bedrockClient.InvokeModelAsync(request);<br><br>         using (var reader = new StreamReader(response.Body))<br>         {<br>             var responseBody = await reader.ReadToEndAsync();<br><br>             var jsonDocument = JsonDocument.Parse(responseBody);<br>             var root = jsonDocument.RootElement;<br><br>             //get specific text.<br>             if (root.TryGetProperty(&quot;content&quot;, out var contentArray) &amp;&amp; contentArray.ValueKind == JsonValueKind.Array)<br>             {<br>                 foreach (var content in contentArray.EnumerateArray())<br>                 {<br>                     if (content.TryGetProperty(&quot;text&quot;, out var textElement) &amp;&amp; textElement.ValueKind == JsonValueKind.String)<br>                     {<br>                         return textElement.GetString();<br>                     }<br>                 }<br>             }<br><br>             return &quot;No information found for this PDF.&quot;;<br>         }<br>     }</pre><p><strong>PDF Input: The </strong>AnalyzePdfAsync<strong> method defines the PDF input by including metadata fields such as type, media_type, and data in the content array.</strong></p><p>5.5.2) To use this method in the controller implement the same dependency injection discussed in 5.3.2</p><p>To call the method You can define an endpoint or controller method like the code below. Note that <em>the PDF should be in base64 format, If you attempt to send a raw image file directly to the API without Base64 encoding, the request will fail because the Claude Sonnet API won’t be able to parse the binary data within the JSON request structure and remember that unfortunately, this implementation does not support Claude sonnet 3.0 version.</em></p><pre>        [HttpPost]<br>        public async Task&lt;IActionResult&gt; AnalyzePdf(IFormFile pdfFile)<br>        {<br>            if (pdfFile == null || pdfFile.Length == 0)<br>            {<br>                ViewBag.Error = &quot;Please upload a valid PDF file.&quot;;<br>                return View();<br>            }<br><br>            try<br>            {<br>                // Convert the PDF file to Base64 format<br>                string base64Pdf;<br>                using (var memoryStream = new MemoryStream())<br>                {<br>                    await pdfFile.CopyToAsync(memoryStream);<br>                    var pdfBytes = memoryStream.ToArray();<br>                    base64Pdf = Convert.ToBase64String(pdfBytes);<br>                }<br><br>                // Call Method from Service<br>                var result = await _claudeService.AnalyzePdfAsync(base64Pdf);<br>                ViewBag.PdfAnalysisResult = result;<br>            }<br>            catch (Exception ex)<br>            {<br>                ViewBag.Error = $&quot;An error occurred during PDF analysis: {ex.Message}&quot;;<br>            }<br><br>            return View();<br>        }</pre><h3>6) Conclusion</h3><p>This guide demonstrated a comprehensive approach to using Claude Sonnet with .NET, from setup to implementation. Whether you’re building an educational app, automating document analysis, or enhancing user interactions, integrating AI into your applications will provide significant value.</p><p>For the complete source code and additional resources, you can visit the project repository on <a href="https://github.com/AdmOzk/LearnAnimal">GitHub</a>. Feel free to share your feedback, ask questions, or contribute to the project to make it even better.</p><p>By leveraging Claude Sonnet’s capabilities, you can unlock new possibilities in AI-driven applications, paving the way for more intelligent and user-friendly solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e6f2b3fcc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>