<?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 Ezgi Gökdemir on Medium]]></title>
        <description><![CDATA[Stories by Ezgi Gökdemir on Medium]]></description>
        <link>https://medium.com/@ezgigokdemir?source=rss-b23914a50c76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yi3yIVB9citWRhOrGM4BdQ.png</url>
            <title>Stories by Ezgi Gökdemir on Medium</title>
            <link>https://medium.com/@ezgigokdemir?source=rss-b23914a50c76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:40:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ezgigokdemir/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[MCP (Model Context Protocol) — Python & .NET Implementation from Scratch and Benchmarks]]></title>
            <link>https://medium.com/sabancidx/mcp-model-context-protocol-python-net-implementation-from-scratch-and-benchmarks-bc305c096d3c?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc305c096d3c</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Sat, 09 May 2026 16:18:46 GMT</pubDate>
            <atom:updated>2026-05-09T19:19:15.027Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWkyANpdBLij-GFpaMtiBw.png" /><figcaption>Generated by Gemini 3</figcaption></figure><p><strong><em>What is MCP?</em></strong></p><p>This blog post will discuss MCP. Actually, I covered MCP in detail in my previous <a href="https://medium.com/sabancidx/mcp-model-context-protocol-7d0a24a748f8">blog post</a>. But to summarize briefly, thanks to MCP, you can access your system’s external resources. For example, you have a book automation application, and you say you want to add the book “The Fisherman and His Son by Zülfü Livaneli” to the LLM. The LLM cannot directly access your system and use the book adding API. Thanks to MCP, it understands which endpoint you want to make this request to and redirects the request to that tool. Therefore, the model receives the necessary response from your external resources without needing to know your system and can return a response to the user, such as “Your book has been successfully added.”</p><p><strong><em>What Are We Building?</em></strong></p><p>In our previous article, we built a RAG application that uses vector embeddings to retrieve relevant context and respond to user queries. Now we want to extend this pattern with tools — so the model can reach out to external resources and access real-time data when needed.</p><p>To demonstrate this, we’ll build MCP tools for a project management scenario. When a user asks “What is the active sprint?”, the model will call the get_sprint_status tool and return up-to-date information directly from the server.</p><blockquote><strong><em>Python vs. .NET Implementation</em></strong></blockquote><p><strong><em>Tool Definition</em></strong></p><p>Both Python and .NET use a similar approach — a decorator or attribute to mark a function as a tool, and a description to tell the LLM what it does. In Python, <a href="http://twitter.com/mcp">@mcp</a>.tool() and a docstring are enough; FastMCP automatically generates the JSON schema. In .NET, [McpServerTool] and [Description] attributes do the same job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ed10679a5258245d4b3c8fa39700444/href">https://medium.com/media/0ed10679a5258245d4b3c8fa39700444/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c027d03e6f7a0404b8d954e188c4b398/href">https://medium.com/media/c027d03e6f7a0404b8d954e188c4b398/href</a></iframe><p><strong><em>Server Setup</em></strong></p><p>The more notable difference is in how tools are discovered. In Python, you need to manually import each tool file in main.py — import tools.project_tools. Every time you add a new tool file, you have to remember to add the import. In .NET, WithToolsFromAssembly() scans the assembly and automatically picks up everything marked with [McpServerTool] — no manual imports needed. It’s not a major disadvantage on the Python side, but it’s worth noting: as the number of tools grows, the manual import step becomes an easy thing to forget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c200b7ed3e9812c5022003f98b968c5/href">https://medium.com/media/4c200b7ed3e9812c5022003f98b968c5/href</a></iframe><p>In .NET, WithToolsFromAssembly() scans the assembly and automatically picks up everything marked with [McpServerTool] — no manual imports needed. It’s not a major disadvantage on the Python side, but it’s worth noting: as the number of tools grows, the manual import step becomes an easy thing to forget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b711c3783d98a12aeb64cc7a08ac2994/href">https://medium.com/media/b711c3783d98a12aeb64cc7a08ac2994/href</a></iframe><p>Both Python and .NET implement the MCP protocol — tool discovery, routing, and execution are handled by the framework in both cases. The key differences emerge in how tools are structured and how dependencies are managed.</p><blockquote><strong><em>Benchmark Results — </em>A different kind of benchmark: lines of code</strong></blockquote><p>Performance isn’t the only metric worth comparing. I also looked at code volume — how much you actually have to write to build the same thing in each platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiBDelF_iasIAdBL3vNOcQ.png" /></figure><p><strong>Cold Start — Python 0.071s vs .NET 3.021s:</strong> Python starts almost instantly. .NET takes ~3 seconds, but this includes the build step from dotnet run. With a published binary, startup drops below 200ms.</p><p><strong>Total Lines — Python 219 vs .NET 298:</strong> .NET requires 36% more code — but almost all of it comes from the Models layer, explained below.</p><p><strong>Entry Point — Python 6 vs .NET 18 lines:</strong> Python’s server.py + main.py is minimal. .NET&#39;s Program.cs includes DI registration, logging configuration, and MCP server setup.</p><p><strong>Tool Definition — Python 59 vs .NET 64 lines:</strong> Nearly equal. The decorator vs attribute difference doesn’t meaningfully affect line count.</p><p><strong>Business Logic — Python 154 vs .NET 170 lines:</strong> Similar structure, similar size. No real difference here.</p><p><strong>Models — Python 0 vs .NET 46 lines:</strong> This is where the gap comes from. Python works with raw dicts — no model definitions needed. .NET requires explicit type declarations for SprintTask, Sprint, TeamMember, etc. This brings compile-time safety, but at the cost of 46 extra lines.</p><p><strong>Takeaway:</strong> .NET requires more code, but it’s almost entirely the type system. Business logic is nearly identical across both platforms.</p><blockquote><strong>Conclusion</strong></blockquote><p>If you want to get things up and running quickly, work primarily in data science, or make heavy use of libraries like PyTorch and TensorFlow, Python is the natural choice. With a small team, a limited number of tools, and the need for a fast UI like Streamlit, Python offers significantly less friction.</p><p>If your team already works in .NET, the system is expected to grow, and long-term maintenance matters, .NET provides a much more solid foundation. Complex dependencies are managed automatically through the DI container. Errors are caught at compile time rather than at runtime — which becomes increasingly important as the codebase scales. And if you want to add AI capabilities to an existing .NET infrastructure, Semantic Kernel and Agent Framework make that possible without ever touching Python.</p><p>In short: Python offers speed and flexibility, .NET offers safety and scalability. The right question isn’t “which one is better?” — it’s “which one fits my situation?</p><p>Thanks for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc305c096d3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/mcp-model-context-protocol-python-net-implementation-from-scratch-and-benchmarks-bc305c096d3c">MCP (Model Context Protocol) — Python &amp; .NET Implementation from Scratch and Benchmarks</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG (Retrieval Augmented Generation) — Python & .NET Implementation from Scratch and Benchmarks]]></title>
            <link>https://medium.com/sabancidx/rag-retrieval-augmented-generation-python-net-implementation-from-scratch-and-benchmarks-84d8959631f7?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/84d8959631f7</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Sat, 09 May 2026 16:17:01 GMT</pubDate>
            <atom:updated>2026-05-09T19:18:12.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNnEq_nB37_5aFNJuRx1rw.png" /><figcaption>Generated by Gemini 3</figcaption></figure><p>I participated in this year’s Devnot Dotnet Conference and gave a presentation on whether it’s possible to develop AI applications without Python. In this article, I wanted to share the details of that presentation in writing.</p><p>Python is the first choice when developing AI applications. It is too normal because this language is really popular for studying machine learning and deep learning. There are a lot of libraries to manipulate data or perform complex mathematical calculations.</p><p>But now, developing an AI application is on a different level. We know different concepts such as RAG, MCP, agentic AI, etc. With these concepts, we can develop chatbots, agents that can solve a lot of problems. For example, someone who is working on customer solutions can get repeated demands from customers every day. By using RAG, you can embed related documents in a database and give answers to customers according to these embeddings. Or you can send paraphrased emails to the customers by using an agent. We could give many more examples like these. Now, not only Python but also other environments like .NET are releasing AI-focused libraries.</p><p>So, I wanted to write a blog series about this comparison. This isn’t actually a definitive comparison; my aim is to share my own experiences and demonstrate how we can develop AI applications using different platforms.</p><p>In this blog series, we will benchmark Python vs. .NET in developing AI-based applications. There will be two blogs, as I mentioned below.</p><ul><li>RAG (Retrieval Augmented Generation) — Python &amp; .NET Implementation from Scratch and Benchmarks</li><li>MCP (Model Context Protocol) — Python &amp; .NET Implementation from Scratch and Benchmarks</li></ul><p>Let’s start with the first one.</p><p><strong><em>What is Retrieval Augmented Generation?</em></strong></p><p>I’ve actually already discussed RAG in detail in <a href="https://medium.com/sabancidx/rag-vs-fine-tuning-2001040d1275">this blog</a>, comparing it to fine-tuning. To briefly define it, RAG is essentially a method where you split a specific document into chunks, embed them in a vector database, convert the user’s question into a vector value, and compare this value with the vector data in the database to arrive at the LLM.</p><p>In this project, I used a vector-based database by adding PostgreSQL’s pgvector extension. Here, each vector represents one dimension of a 1536-dimensional vector. This is because the model I’m using (text-embedding-3-small) represents each piece of text as a list of 1536 numbers. Each dimension captures an aspect of meaning; we don’t manually define what each dimension means; the model learns this during training. Think of it like coordinates in a very high-dimensional space where similar meanings are close to each other.</p><p>We used the following query to calculate the similarities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5Z8LIA3oG3ySuYbFWH9CQ.png" /></figure><p>Let’s examine the SQL code line by line:</p><p>“embedding &lt;=&gt; CAST(:query AS vector)” — this is the cosine distance between the stored vector and our query vector.</p><p>“1 — (distance)” — we reverse this to get similarity instead of distance, so a higher value = more similarity.</p><p>Think of it this way — we look at the angle between two vectors:</p><ul><li><em>Angle = 0° → they point in the same direction → exactly the same meaning</em></li><li><em>Angle = 90° → right angle → irrelevant</em></li><li><em>Angle = 180° → opposite directions → opposite meaning</em></li></ul><p>Cosine distance is a function of this angle:</p><ul><li><em>Small angle → distance close to 0</em></li><li><em>Angle large → distance close to 1</em></li></ul><p>So distance actually tells us how different they are. We want to know how similar they are — so we set it to 1 — and reverse the scale:</p><ul><li><em>distance 0 → similarity 1.0 (same)</em></li><li><em>distance 0.5 → similarity 0.5 (partially similar)</em></li><li><em>distance 1 → similarity 0.0 (irrelevant)</em></li></ul><p>“ORDER BY … LIMIT 3” — we only want the top 3 most relevant parts.</p><p>Now let’s look at how I wrote the application separately for Python and .NET.</p><p><strong><em>Python vs. .NET Implementation</em></strong></p><p>Before we begin, let’s place our document in a vector database. I used the same database and data in both applications.</p><p>I used data in the following structure. It contains a question, an answer, and a brief context description for each entry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e411c16d3a1d59eb8ee4c2fb9f265089/href">https://medium.com/media/e411c16d3a1d59eb8ee4c2fb9f265089/href</a></iframe><p>I divided the data into chunks using the following pattern when uploading the document.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/106bf5e82576aff762e7b68870f24268/href">https://medium.com/media/106bf5e82576aff762e7b68870f24268/href</a></iframe><p>The output will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eaa62b642f9b0544ba671cf55925382/href">https://medium.com/media/9eaa62b642f9b0544ba671cf55925382/href</a></iframe><p>Ultimately, the database will contain a vector of size 1536 for each chunk, as follows:</p><p>[0.015925936,0.0466492,0.011871302,0.009504356,…]</p><p>I completed these embedding steps once and created the vector database; I didn’t apply a separate step in .NET for this.</p><p><strong><em>Step 1: Embedding the Query</em></strong></p><p>Now that our vector database is ready, let’s look at what happens when a user asks a question.</p><p>In this demo project, to get embedding, you directly call the Azure OpenAI client — meaning your code is tightly coupled to Azure. If you want to change providers, you need to manually modify the get_embedding function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e98329da89bfda425ddff2aa51e4ca62/href">https://medium.com/media/e98329da89bfda425ddff2aa51e4ca62/href</a></iframe><p>In .NET, the Semantic Kernel’s ITextEmbeddingGenerationService interface intervenes. You only register Azure OpenAI once in Program.cs; the rest of the code doesn’t know about it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cf87e94467c6af7a535d6327f0bb284/href">https://medium.com/media/3cf87e94467c6af7a535d6327f0bb284/href</a></iframe><p>And this is how it’s called in DbService — regardless of which provider is registered, this code never changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f336b4c9da42815848799c3d560f0f5c/href">https://medium.com/media/f336b4c9da42815848799c3d560f0f5c/href</a></iframe><p>You may want to use two providers at the same time — for A/B testing, fallback (switching to Ollama if Azure goes down), or cost optimization. In .NET, you simply change the registry line in Program.cs; you don&#39;t need to touch RagService or DbService at all:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e952e67df27bf7bc517550fc8b4f7755/href">https://medium.com/media/e952e67df27bf7bc517550fc8b4f7755/href</a></iframe><p>For multiple providers simultaneously, Keyed Services handle it with two registrations — no factory class needed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7451fde2105a8955d97209ca2711d794/href">https://medium.com/media/7451fde2105a8955d97209ca2711d794/href</a></iframe><p>In Python, you need to go into db_service.py and directly replace the client call — the framework doesn&#39;t provide an abstraction layer for this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5460b2a6df989ba817bdf73ef6859b33/href">https://medium.com/media/5460b2a6df989ba817bdf73ef6859b33/href</a></iframe><p>If you want to support multiple providers simultaneously, you need to build this infrastructure yourself using abstractions like the Factory Pattern. In other words, you end up writing what .NET’s ITextEmbeddingGenerationService already provides out of the box.</p><p>In Python, what you write from scratch — abstract classes, factories, selection logic — is handled here by a DI container and an attribute.</p><p><strong><em>Step 2: Retrieval (Searching Similar Chunks)</em></strong></p><p>In this section, I’m using the same database and the same query I shared above for both implementations — this is the same pgvector database used in the demo project.</p><p>Here, it takes the vector of the user’s query, finds the top_k most similar chunks in pgvector, and returns them along with the similarity score.</p><p>Since SQLAlchemy’s core doesn’t include a native Vector type, we convert the embedding to a string and pass it to SQL using CAST(:query_embedding AS vector) — PostgreSQL handles the conversion on its side. We also tested the pgvector-python extension to skip the cast entirely, but the results were similar — .NET was still faster. This suggests the performance gap comes from connection management rather than the cast operation itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8469deb674aa95b01ca97a8a9d797d3/href">https://medium.com/media/a8469deb674aa95b01ca97a8a9d797d3/href</a></iframe><p>Unlike Python, we first configure the connection with NpgsqlDataSourceBuilder — this is the .NET equivalent of SQLAlchemy&#39;s engine. The critical step here is dataSourceBuilder.UseVector() — you cannot use the Vector type without explicitly registering pgvector support. After that, we pass the embedding directly as a new Vector(embedding) parameter — no string conversion, no SQL casting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/867e3dc93faf88ce1b2199faeebaf51f/href">https://medium.com/media/867e3dc93faf88ce1b2199faeebaf51f/href</a></iframe><p><strong><em>Step 3: Calling the LLM</em></strong></p><p>In the beginning, the prompt structure is exactly the same in both implementations — we provide the 3 most similar chunks from RAG as context, then add the user’s question. Regardless of the language, the message sent to the LLM is the same.</p><p>Below you can see example uses for Python and .NET, respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1f3ab52a7b59f1aede6853a2dcfa98/href">https://medium.com/media/9e1f3ab52a7b59f1aede6853a2dcfa98/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48eb6f8df18438deda831d52a66325bd/href">https://medium.com/media/48eb6f8df18438deda831d52a66325bd/href</a></iframe><p>As you can see, implementing RAG in .NET isn’t as difficult as it seems. The basic logic is the same — the same SQL query, the same model, the same prompt structure. The differences are mostly at the ecosystem level. One practical advantage worth mentioning: in .NET, type safety is built into the language itself. The compiler catches type errors before the application even runs. In Python, similar checks are possible with tools like Pylance or mypy, but they are optional — the language doesn’t enforce them by default. For larger codebases, this difference becomes more significant.</p><p><strong><em>Benchmark Results</em></strong></p><p>To measure the performance difference, I ran 20 queries against a 100-chunk project management dataset covering topics like Scrum, Kanban, CI/CD, and technical debt — using the same PostgreSQL + pgvector instance for both implementations. LLM latency was excluded from the comparison as it depends on Azure OpenAI network conditions rather than the language or framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3Kem5jjQeTBbwD7937hKA.png" /><figcaption>Benchmarks</figcaption></figure><p><strong><em>Embedding — Why is .NET faster?</em></strong></p><p>In our benchmark, .NET was 2.6× faster in the embedding step. To validate this, we switched the Python side from string casting to native Vector support using pgvector-python — the embedding gap remained unchanged. This confirms that the difference comes from connection management, not the cast operation. openai-python uses httpx under the hood with connection pooling, while Semantic Kernel leverages .NET’s HttpClientFactory infrastructure — a more aggressively optimized connection management layer. AddAzureOpenAITextEmbeddingGeneration() brings both API abstraction and this connection optimization out of the box. That said, this is a small benchmark — 20 questions, single machine, single network. Python’s embedding times varied between 278ms and 3700ms within the same session, which clearly reflects network variability. These results are directional, not definitive.</p><p><strong><em>Retrieval — Why is .NET faster?</em></strong></p><p>Two technical reasons. First, async-first architecture: .NET’s built-in libraries — Npgsql, HttpClient, ASP.NET Core — treat async as the default. ExecuteReaderAsync(), SendAsync(), ReadAsStringAsync() are the standard choices; writing synchronous code actually requires extra effort. In Python, it’s the opposite — psycopg2, requests, and SQLAlchemy’s core are synchronous by default. Async support came later or requires separate packages like asyncpg or aiohttp. Both languages share the same async/await keywords, but the ecosystems are built around different defaults. <br>Second, we confirmed that binary transfer is not the deciding factor — after switching to pgvector-python and removing the cast, retrieval times barely changed (15ms vs 7ms gap remained). The async architecture is what drives the difference.</p><p>One final note: these tests were run locally. If this application were deployed to Azure Container Apps or a similar cloud environment, network conditions, resource allocation, and runtime behavior could produce different results. The numbers here reflect a local development setup.</p><p>In the <a href="https://medium.com/sabancidx/mcp-model-context-protocol-python-net-implementation-from-scratch-and-benchmarks-bc305c096d3c">next article</a>, we will cover MCP (Model Context Protocol). We will implement it for both platforms, discuss the architectural differences. Happy reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84d8959631f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/rag-retrieval-augmented-generation-python-net-implementation-from-scratch-and-benchmarks-84d8959631f7">RAG (Retrieval Augmented Generation) — Python &amp; .NET Implementation from Scratch and Benchmarks</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP (Model Context Protocol)]]></title>
            <link>https://medium.com/sabancidx/mcp-model-context-protocol-7d0a24a748f8?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d0a24a748f8</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[fastmcp]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 20:01:09 GMT</pubDate>
            <atom:updated>2025-12-31T10:31:36.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKaH57TK8_3hSOWlij37OA.png" /><figcaption>By Claude</figcaption></figure><p>In this article, we will discuss MCP, what it is, and its roles when applying AI to our projects.</p><p><em>What is function calling?</em></p><p>Before we start, let’s make a little definition. We can ask different types of questions to an LLM that will cause it to make various API requests, and for each of these, it will need to make a function call. These questions may be about weather, up-to-date news, or art, etc. For example, you ask, “What is the temperature in Istanbul now?”. The model doesn’t know this information currently; it needs to make a web scraping, and this scraping operation is a function call. Or you ask, “Send a reminder message to my friend for our meeting,” and the model will use the <em>send_email()</em> function by making another function call.</p><p>So, function calling is the ability of LLM to produce formatted output that can trigger other parts of the system with method or API calls, according to the context of the prompt. So, it translates prompts into actionable instructions.</p><p>Each LLM has its own function calling definition. For example, the structure is as follows for GPT;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d0f5bee9a3eae1924df1672de6c2785/href">https://medium.com/media/7d0f5bee9a3eae1924df1672de6c2785/href</a></iframe><p>And for Claude;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbb41bd5f9faf1a5f78254f9b817bbd7/href">https://medium.com/media/bbb41bd5f9faf1a5f78254f9b817bbd7/href</a></iframe><p>When we look at just two language models, we see that these structures are different from each other. You may want to add different LLMs to your application (Gemma, Claude, ChatGPT etc). So, you have N different functions for M different AI models, which will create an MxN problem. Each function type needs its custom code, and you may use different LLMs. This will become much more complex as your project grows.</p><p>This is precisely where standardization is needed. A solution called the Model Context Protocol (MCP) addresses this need. MCP, a protocol developed by Anthropic, provides a standard for LLMs to handle these diverse requests. Moreover, this allows these tools to be run client-side. You can run these tools on your local machine, customize them, and use them from anywhere.</p><p>For example, the tool written for a function call runs on the model provider’s server, meaning the tools are run remotely. Let’s say we have a scenario like “Analyze my last 100 emails and summarize the important ones.” A typical function call would flow as follows:</p><ul><li>100 emails are retrieved using the Gmail API.</li><li>All emails (header + content) are sent to the OpenAI server.</li><li>The model reads and analyzes the emails in the cloud.</li><li>The summary is returned to you.</li></ul><p>Problem: All your emails are processed on OpenAI’s servers.</p><p>The entire process takes place in the cloud, and analysis is performed on remote servers. At this point, the mails are completely transferred to the cloud. This could pose a privacy issue.</p><p>But with MCP, you can send more summary information to the model by writing a tool like the one below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c64aecfc820629821d991f3ab1b5a953/href">https://medium.com/media/c64aecfc820629821d991f3ab1b5a953/href</a></iframe><p>With MCP, emails themselves are not sent to the model. Instead, emails are processed by a client-side tool, and only the necessary summary information or results are sent to the model.</p><p>You can use a simpler standardized tool template for MCP as follows, and adapt this structure for all tools.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee3e07d7039837647e58755d60797aa6/href">https://medium.com/media/ee3e07d7039837647e58755d60797aa6/href</a></iframe><p>MCP works by using the following flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLUXp10Bjzw_XaVH5wC0FA.png" /><figcaption>By Claude</figcaption></figure><p>The host is the layer that allows us to communicate with the model and manage clients. Any web or desktop application, such as Claude, Cline, Streamlit, or applications you write yourself, such as React, Vue, etc., can serve as a host.</p><p>Clients are the components that enable us to implement the MCP protocol. By speaking the MCP protocol, they enable connecting to servers, performing tool discovery, and routing tool calls. It converts the input sent from the host via LLM into JSON-RPC format and sends it to the relevant server. It then converts the response from the server into a meaningful format and forwards it to LLM. Each programming language or platform may have different client implementations (Python — mcp package, TypeScript/JavaScript — <a href="http://twitter.com/modelcontextprotocol/sdk">@modelcontextprotocol/sdk</a> etc.).</p><p>Servers are where tools run, such as a weather API, a database connector, or an email sender. Each server is a standalone program/service. The host connects to them based on its needs.</p><p>The logic here works exactly like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0u00YAtErjGria-WzWK1w.png" /><figcaption>By Claude</figcaption></figure><p>For example, you asked LLM what the weather was like today.</p><ul><li>User Prompt: “What’s the weather like today?”</li><li>Host (Claude Desktop): Sends the prompt to the model</li><li>LLM Analyzes: “weather” → get_weather tool required</li><li>Host → MCP Client: Request a tool call</li><li>MCP Client → MCP Server: JSON-RPC call</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f03bddb6cf188f5f637c9e02ac79b4/href">https://medium.com/media/c8f03bddb6cf188f5f637c9e02ac79b4/href</a></iframe><ul><li>MCP Server: Executes the tool locally<br>- Makes an API call<br>- Reads a local file<br>- Runs a database query</li><li>MCP Server → MCP Client: Returns the result</li><li>MCP Client → Host: Sends the tool result</li><li>Host → LLM: Sends the tool result + context</li><li>LLM: Creates the final response</li><li>Host → User: “Today in Istanbul it’s 22°C and sunny”</li></ul><p>Now, let’s write a simple MCP application that we will run on Claude Desktop. Here we’ll use the FastMCP package. There are SDKs for many programming languages ​​to use MCP, you can review them <a href="https://modelcontextprotocol.io/docs/sdk">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fecd5b78fc4b9e5f548b364fc5268421/href">https://medium.com/media/fecd5b78fc4b9e5f548b364fc5268421/href</a></iframe><p>Here, we wrote an MCP server containing our tools that saves our notes to a file whose path we specified and reads them from that file. We then hosted this application on the Claude desktop. For more information on using Claude desktop, please see <a href="https://modelcontextprotocol.io/quickstart/user">here</a>.</p><p>You can find usage examples below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAIck-QfzOWprzYpvb-fZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDseNhl5ymUefIBMQIwNlQ.png" /></figure><p>We wrote an MCP server and used the necessary tools with the help of a set of natural language prompts. As the scope of our application expands, this usage style will become a crucial need for us. Therefore, this type of standardization is truly important.</p><p>In this article, I’ve tried to explain the MCP concept in as much detail as possible. Enjoy reading.</p><p>References</p><ul><li><a href="https://platform.openai.com/docs/guides/function-calling#function-tool-example"><em>https://platform.openai.com/docs/guides/function-calling#function-tool-example</em></a></li><li><a href="https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/overview"><em>https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/overview</em></a></li><li><a href="https://modelcontextprotocol.io/docs/getting-started/intro"><em>https://modelcontextprotocol.io/docs/getting-started/intro</em></a></li><li><a href="https://x.com/MindupLife/status/1892686401386512755"><em>https://x.com/MindupLife/status/1892686401386512755</em></a></li><li><a href="https://medium.com/@patc888/function-calling-vs-mcp-model-context-protocol-fc01e9c41eb4"><em>https://medium.com/@patc888/function-calling-vs-mcp-model-context-protocol-fc01e9c41eb4</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d0a24a748f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/mcp-model-context-protocol-7d0a24a748f8">MCP (Model Context Protocol)</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG vs. Fine-tuning]]></title>
            <link>https://medium.com/sabancidx/rag-vs-fine-tuning-2001040d1275?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/2001040d1275</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[llm-finetuning]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 14:14:12 GMT</pubDate>
            <atom:updated>2025-03-19T15:25:24.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*II9B4wrH6-kdxRvjqUai_g.jpeg" /><figcaption>Generated by ChatGPT</figcaption></figure><p>This paper will discuss the differences between RAG (Retrieval Augmented Generation) and fine-tuning techniques. I will explain these differences mathematically.</p><p><strong><em>Artificial Intelligence</em></strong></p><p>First of all, let&#39;s explain what is artificial intelligence. Artificial intelligence represents a computer system developed by mimicking the human brain. An AI model is trained by recognizing patterns in a given dataset, just like a human learns from experience. For example, when you first give the model a photo of a cat, it may not be able to output that it is a cat. However, after training with thousands of cat photos, the model will recognize certain cat characteristics, such as the number of legs, eye structure, and ear type, in other words, patterns, and will be more likely to make a cat prediction. Like a baby :)</p><p>Today, there are many artificial intelligence models used for various purposes, such as analyzing texts, diagnosing diseases, and even playing chess.</p><p><strong><em>Generative AI</em></strong></p><p>Although traditional AI models successfully performed tasks such as text analysis, detection of diseased cells, or various recommendation systems, they had limited capacity for human creativity. With new generative AI models, producing new and completely original content has become possible. Moreover, these outputs no longer come to us as just probabilistic outputs. It has become possible to see outputs in various forms such as images, songs, texts, and videos. A generative AI model can learn a composer’s style and compose a new song accordingly, imitate a painter’s brush strokes to produce a new painting, and speed up the process of writing code for software developers. These models, which have many more capabilities, have transformed the field of artificial intelligence from a field specific to data science into a system that everyone can use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*Ex__PEy3SAKL9ACV" /></figure><p>Generative AI models are categorized as Large Language Models (LLM) and a method such as Natural Language Processing (NLP) is used in the training of these models. NLP is a sub-branch of artificial intelligence. This technology, which refers to a process in which natural human language is attempted to be understood and processed, makes it possible to analyze texts using natural language, make some inferences from texts, and asks text-based questions.</p><p>However, how large language models use the information they learn and update it with new information is an important topic. This is where two main methods come into play: Retrieval-Augmented Generation (RAG) and Fine-Tuning. These two approaches offer different strategies for how AI models are presented and how answers can be obtained.</p><p><strong><em>Retrieval-Augmented Generation (RAG)</em></strong></p><p>The basic logic of RAG is a method that allows it to receive data from an external information source (vector database, API, etc.) and produce a response. The model produces a response by accessing current and new information rather than trained data.</p><p>In this method, a certain data set is taken and divided into certain pieces (chunks). Then, each piece is converted into a vector, i.e. embedding, and saved in a vector database. Then, a prompt is received from the user and this prompt is also converted into a vector. According to the value of this vector, the most similar pieces in the database are found.</p><p>If we are going to use a metric such as cosine similarity while finding these similar parts, the calculation is done as follows;</p><p><em>cosine similarity = (A x B) / (||A|| x ||B||)</em></p><p>Here A represents the prompt vector and B represents an information vector in the database. These pieces obtained are presented as context to an LLM model, and the model produces a response in natural language using this information.</p><p>Each vector here, or embedding, is a numerical representation in mathematical space. For example, the embedding equivalent of the word “apple” could be a vector like [5, 5] (2 dimensions).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*tHRYdJviyvCMooty" /></figure><p>Let’s assume that we have two vectors in the vector database [7, 7] → “fruit” and [3, 4] → “vegetable”. Here first the cosine similarity between [5, 5] and [7, 7] is calculated, and let’s say the result is 1.0 then the cosine similarity between [5, 5] and [3, 4] is calculated and the result is approximately 0.99. As a result, [7, 7] has the highest similarity score. So when you ask, “What is an <strong>apple</strong>?” you are more likely to get the answer, “An <strong>apple</strong> is a <strong>fruit</strong>.”</p><p>The number of dimensions in embeddings depends on how much we want to divide this space semantically. The larger the dimension of this space, the more semantic distinctions the model can make.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWWKW-eEqnuXkfkGHieC9g.png" /></figure><p>For example, if you are going to make a distinction between animals, the first dimension could be age, and the second one could be size. If you want to increase the number of dimensions semantically, you can add new dimensions, such as the number of legs, eye structure, etc.</p><p><strong><em>Fine-tuning</em></strong></p><p>In fine-tuning, a given LLM model is retrained with a new dataset or by updating the existing model parameters. In this process, the model weights are updated with the new information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyHX9ij_tHyxOIUDdKzTJA.png" /></figure><p>First, the text is divided into tokens and converted into numerical values. For example, the sentence “Hello, world!” can be divided into tokens as follows:<br>[“Hello”, “,”, “ world!”] → [2456, 987, 32]</p><p>These numerical tokens are converted into fixed-size vectors in the embedding layer. Then, by applying transformer layers, the model learns the contexts between the tokens. Finally, the weights of the model are updated with backpropagation and the new dataset is adopted.</p><p>To give a simple mathematical example;</p><p><strong>Tokenization</strong>: “Hello” → 2456, “,” → 987, “world!” → 32</p><p><strong>Embedding</strong>: Convert each token to fixed-size vectors.<br>2456 → [0.1, 0.2]<br>987 → [0.3, 0.4]<br>32 → [0.5, 0.6]</p><p><strong>Fine-tuning:</strong> Updates the model’s weights with new data.</p><p>For example, if weight <em>w </em>= 0.5 and error = 0.2, the new <em>w</em> value for 2456 will be [0.5 − 0.1 ⋅ 0.2, 0.5 − 0.2 ⋅ 0.2] = [0.48, 0.46].</p><p>The error value here is calculated by subtracting the model’s prediction from the actual result.</p><p>As a result, after all these new weight calculations, the model will become more compatible with the new data.</p><p><strong><em>RAG vs. Fine-tuning</em></strong></p><ul><li>In RAG, the user prompt is converted into a vector and matched with stored vectors, while fine-tuning updates the model’s embeddings and weights.</li><li>RAG retrieves responses from external data, whereas fine-tuning relies on learned knowledge.</li><li>RAG allows adding new information without modifying the model while fine-tuning makes the model more task-specific.</li><li>Embedding is fast, easy, and cost-effective, whereas fine-tuning is resource-intensive and costly.</li><li>Embedding provides static, reliable retrieval, while fine-tuning is dynamic but may produce hallucinations.</li></ul><p>In this article, I tried to explain the basic differences between RAG and fine-tuning. Enjoy reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2001040d1275" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/rag-vs-fine-tuning-2001040d1275">RAG vs. Fine-tuning</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Tokenization?]]></title>
            <link>https://medium.com/sabancidx/what-is-tokenization-a60c77ea6424?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/a60c77ea6424</guid>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[token]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 13:32:03 GMT</pubDate>
            <atom:updated>2023-12-28T17:04:01.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*kb1f7z_6fvG9WpINv4rcLg.png" /></figure><p>What are token and tokenization, and how can some examples be applied to this concepts? We will touch upon these topics in this article.</p><p>Before we start, I touched on some basic concepts in <a href="https://medium.com/sabancidx/what-is-prompt-engineering-79b101cd4d9f">this article</a>, you can read it :)</p><p>In every NLP application, we need to apply a process to the text. In this way, we transform our data into a more predictable and analysable form that the computer can understand. We can call one of these processes tokenization, and we will focus on it in this article.</p><p>Tokenization is the process of dividing a piece of text into smaller units called tokens. These tokens can be words, subwords or characters.</p><p>Tokens serve as the fundamental units in Natural Language Processing (NLP). The preprocessing and analysis of textual data often occur at the token level. This token-level processing is a critical step in various NLP tasks such as sentiment analysis.</p><p>Now let’s do some examples. In the examples here I used the NLTK tool.</p><ul><li>Sentence tokenization</li></ul><p>Here we simply divided the text into sentences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1a9c24c0041ffd0e97141732f76a914/href">https://medium.com/media/a1a9c24c0041ffd0e97141732f76a914/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*x2011MEYN6ttQtMnV_gYKA.png" /><figcaption>Sentence Tokenization</figcaption></figure><ul><li>Word tokenization</li></ul><p>Word tokenization is one of the most widely used tokenization algorithms. It breaks a piece of text into individual words.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f02f8c92e49c3ce26df6297a415e24dc/href">https://medium.com/media/f02f8c92e49c3ce26df6297a415e24dc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*2XIvj9gyOswBPhSZia0pLg.png" /><figcaption>Word Tokenization</figcaption></figure><p>We can also use the split function to tokenize a sentence into words, but it’s important to note that the split function may not handle all cases perfectly, especially when dealing with punctuation marks.</p><p>As you can see from the result, the “dot sign (.)” came with the word “day”. And it’s the same with the word “better”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48ea541bbf54e6105f76a74eaf56fd4a/href">https://medium.com/media/48ea541bbf54e6105f76a74eaf56fd4a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*opJwNRV2JXcuaXoPQY2xvQ.png" /><figcaption>Word Tokenization With Split Function</figcaption></figure><p>Natural languages often contain ambiguous words or expressions. For example, “I can’t” can be tokenized as “I” and “can’t” or as “I” and “ca” and “n’t.” Resolving such ambiguities might require additional context or language-specific rules.</p><p>In this example, we were able to make this distinction thanks to the NLTK tool.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f7d784d512e1314d6ef5f75deea63de/href">https://medium.com/media/7f7d784d512e1314d6ef5f75deea63de/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*IDtXzrMvBYyHydQmrEBJDQ.png" /><figcaption>Word Tokenization</figcaption></figure><ul><li>Character tokenization</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440877b36cdbb8d5a2915c03d98c8d9f/href">https://medium.com/media/440877b36cdbb8d5a2915c03d98c8d9f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*09AC4dj4S_IlrHRnbxNXEg.png" /><figcaption>Character Tokenization</figcaption></figure><p>This approach essentially treats each character as if it were a separate “word,” by using the nltk.word_tokenize function. Character tokens may lack semantic meaning, making it more challenging to understand the overall meaning of a text. While beneficial for certain tasks, character tokenization may not be ideal for tasks relying on word-level semantics.</p><p>In this article, I tried to cover the concept of tokenization in a more superficial way. I hope it will be useful content. Have fun reading in advance :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a60c77ea6424" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/what-is-tokenization-a60c77ea6424">What is Tokenization?</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Prompt Engineering?]]></title>
            <link>https://medium.com/sabancidx/what-is-prompt-engineering-79b101cd4d9f?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/79b101cd4d9f</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 16:55:43 GMT</pubDate>
            <atom:updated>2023-09-24T21:52:37.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa2XDyAVN0b2Nvm5Wije4Q.jpeg" /></figure><p>Hey everyone. Today I’m going to talk about a little bit different topic. What is prompt engineering?</p><p>But before I dig deeper, I would like to explain some fundamental terms.</p><p>What is Generative AI?</p><p>As you know, a standard AI aims to make some tasks autonomous, analyze data and solve some complex problems, but when it comes to mimic human creativity, it falls short. This is exactly where we encountered Generative AI. Generative AI is a kind of AI sub-branch, and it is a solution to this lack of creativity.</p><p>Generative AI refers to AI systems capable of generating text, images, music, and various types of data. These systems can create new contents by using learning model based on a pre-defined pattern or sample.</p><p><em>ChatGPT</em></p><p>As you all know, a chatbot application such as ChatGPT has recently entered our lives. It’s a really different tool that we’ve used so far. When we ask a question, it can answer like a human. It can create completely unique contents such as cover letter, code samples etc.</p><p>Actually, ChatGPT is a kind of generative AI model. That’s why it has these abilities. Such models are artificial intelligence systems that can generate text-based data and often have natural language processing (NLP) capabilities.</p><p><em>NLP (Natural Language Processing)</em></p><p>NLP is a sub-branch of artificial intelligence. In this approach, natural human language is tried to be understood and processed. This technology is used in many areas such as analyzing texts, making inferences from texts, and asking text-based questions.</p><p><em>LLM (Large Language Model)</em></p><p>LLM is a term used to represent large-scale and complex NLP models. LLMs represent current technological advances in this field, while NLP focuses on processing and understanding natural language. These models are artificial intelligence systems that understand natural language by training and processing large amounts of data. They can be very successful in text-based tasks.</p><p><em>Prompt</em></p><p>A prompt is any input we can give to such models. An initial input that specifies how the model will run or respond. Especially in generative AI, a model tries to produce content according to a given prompt. For example, “Can you write me a cover letter to apply to X university and X department?”, a prompt like this will trigger the model to write an cover letter about the university and department you are providing.</p><p>When you write an accurate and engaging prompt, you help the model generate the answers you want. That’s why it’s really important to write prompts in AI-based applications. In this context, we came across a new profession called Prompt Engineering.</p><p><em>What is prompt engineering?</em></p><p>Prompt engineering is the process of preparing and designing prompts for an NLP model to elicit desired responses or behaviours from the model. It involves formulating prompts that will help the model generate more accurate, meaningful and specific outputs. This arrangement is done by tuning wording and content of a prompt.</p><p>How can we be more carefull when doing prompt engineering, or at least using ChatGPT? Let’s examine it in a few steps.</p><p><strong>Clarity and Specificity: </strong>Preparing prompts with clear and specific information can help ensure that the model correctly understands the client’s wishes. In this way, the model can generate more relevant answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Nb6dwIuvwoUOb9Vh.png" /><figcaption>Clarity and Specificity Sample</figcaption></figure><p>This is a really simple example, I know, but it makes sense in our case here. The tool we’re trying to ask is not a human, just an AI model. Don’t forget it :)</p><p>This model tries to convert our prompts into some numerical values in the background and then respond by making a predictions based on these values. So writing something randomly and not giving details prevents us from getting better answers. It’s actually about tokenization. We will talk about this term later in the article.</p><p><strong>Contextual Information:</strong> Adding contextual information or related data to a prompt is really important. Thus, the model can generate more relational contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*cavBD5rdKHA57nF2.png" /><figcaption>Contextual Information Sample</figcaption></figure><p>Here I asked for a line graph where I specified the coordinates, then gave a small dataset to support my prompt.</p><p><strong>Multi-Turn Conversations:</strong> Doing multi-turn conversations means that the conversation between the human and the AI model involves many turns. In these types of interactions, the client typically starts the conversation with an initial message or a question, then the AI model responds and it goes on like this. Thus, the model can provide interrelated answers based on previous questions or answers.</p><p>For example, you asked something and received an answer. From now on, you can ask “Can you add my new value here?” or “Can you change last sentence you gave me because I don’t understand it?”. In this way, you can ensure that the model outputs more accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*q_1cDWedcjyD0fHY.png" /><figcaption>Multi-Turn Conversations Sample</figcaption></figure><p>In this example, I gave a part of code and asked the model to convert this code for StringBuilder format. After that, I asked the model to compare these two code samples. Here, I asked a new question in the same context. According to my previous prompt, the model knew what to compare, and the model made a performance comparison between the code I first wrote and the code with StringBuilder.</p><p><strong>Chain of Thought (CoT): </strong>In such an approach, we try to guide the model by giving some instructions and telling the model how to think so that it can create a logical response chain. The main purpose here is to shape the model’s outputs according to the instructions we will give. That’s why, each instruction should be design according to the previous instruction so that the model can generate logical outputs. Thus, the model can create a flow of thought and generate coherent responses for a task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*KQ98UKkkpD_hEhqg.png" /><figcaption>CoT Sample 1</figcaption></figure><p>Here I asked the model a question and asked it to think about it step by step. So I gave the model an instruction so that it could think step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*gump26Wc8zGwcZig.png" /><figcaption>CoT Sample 2</figcaption></figure><p>And here I opened a new chat and asked the model to use the steps I took in the previous chat. So in a new prompt, I used the information I got from the model and told the model to use these steps.</p><p><strong>Prompt Chunking: </strong>It is an approach to separate complicated prompts into more manageable chunks. We can make the model provide more consistent and context-sensitive responses. This approach helps improve the outputs and enables the model understand the question comprehensively. In fact, you can give the entire text to the model at the same time but token size is the critical here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Wtvqa3X1CGzZOFM5.png" /><figcaption>Token Size</figcaption></figure><p><em>Token &amp; Tokenization</em></p><p>Let’s explain what a token is.</p><p>A <strong>token </strong>is the smallest part of a text that can be meaningful. The token can be a word, number, punctuation mark or several characters. <strong>Tokenization </strong>is the process of splitting a text into tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*M29G0r0n0MzD8ne4.png" /><figcaption><a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a></figcaption></figure><p>When dividing the text into tokens, some distinctions are made according to factors such as spacing, punctuation marks, and grammar rules. Each token is assigned a weight during the tokenization process. This weight value is determined based on how often that token appears in the text. In such models, the aim is to predict the next tokens according to your prompt. While making this estimation, a calculation is made based on the weight values given to these tokens.</p><p>The more tokens in the prompt you give are seen in the model, the greater the weight value is given to it. Therefore, the more likely the model will use this token or related tokens when responding.</p><p>Closely related words and other contextually relevant tokens can also be considered by the model and used in responses. For example, if the word “beautiful” has a high weight and appears frequently in the model’s training data, the model is more likely to use the word “beautiful” when responding to “the weather is very nice today.” However, the model may also use other words or tokens, taking into account the context. For example, it can also generate similar meaningful expressions such as “the weather is wonderful” or “the weather is perfect.”</p><p>In summary, tokens with higher weights will have more influence in determining the response of the model. If we consider again to the prompt chunking as I mentioned above, the longer our prompt is, the more tokens there will be and the weight value of each token will be smaller when determining the response of the model. Therefore, the model will give us a less accurate or less logical prediction. It means that long prompts may be less effective in responding.</p><p>In this article, I tried to touch upon the subject of Prompt Engineering. I hope it will be a useful content. Enjoy reading :)</p><p>Additionally, while researching for this article, dear Daron Yondem’s <a href="https://www.youtube.com/watch?v=J09R0Z5cjA8">Azure OpenAI from Scratch</a> training video was very useful for me. I highly recommend anyone interested in the subject to watch it.</p><p><em>References</em></p><ul><li><a href="https://www.youtube.com/watch?v=J09R0Z5cjA8"><em>https://www.youtube.com/watch?v=J09R0Z5cjA8</em></a></li><li><a href="https://docs.cohere.com/docs/model-prompting"><em>https://docs.cohere.com/docs/model-prompting</em></a></li><li><a href="https://www.promptingguide.ai/techniques/cot"><em>https://www.promptingguide.ai/techniques/cot</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79b101cd4d9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/what-is-prompt-engineering-79b101cd4d9f">What is Prompt Engineering?</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering nedir?]]></title>
            <link>https://medium.com/sabancidx/prompt-engineering-nedir-5fdcb15b0439?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fdcb15b0439</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 14:01:15 GMT</pubDate>
            <atom:updated>2023-12-28T17:04:15.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa2XDyAVN0b2Nvm5Wije4Q.jpeg" /></figure><p>Herkese merhabalar. Bugün her zamankinden biraz farklı bir içerikle karşınızdayım. Prompt engineering nedir, bundan bahsediyor olacağım.</p><p>Konuya giriş yapmadan önce bazı kavramlardan biraz bahsetmek istiyorum.</p><p><em>Generative AI nedir?</em></p><p>Bildiğiniz gibi standart bir yapay zeka belirli görevleri otomatize etmek, verileri analiz etmek veya karmaşık sorunları çözmek gibi birçok amaç için kullanılıyor, ancak insan yaratacılığını taklit etme noktasında yetersiz kalıyordu. Tam da bu noktada karşımıza Generative AI kavramı çıkmış oldu.</p><p>Generative AI veya üretken yapay zeka olarak çevirebileceğimiz bu kavram, bir tür yapay zeka alt dalı olup, tam da yaratıcılık noktasındaki bu eksikliğe getirilen bir çözümdür.</p><p>Generative AI , metin, görüntü, müzik ve çeşitli veri türlerini üretebilme yeteneğine sahip yapay zeka sistemlerini ifade eder. Bu sistemler, önceden belirlenmiş bir pattern’e veya örneğe dayalı olarak bir öğrenme modellemesi kullanarak yeni içerikler oluşturabilirler.</p><p><em>ChatGPT</em></p><p>Hepinizin bildiği gibi son dönemde hayatımıza ChatGPT gibi bir chatbot uygulaması girdi. Bu zamana kadar kullandığımız chatbot’lardan oldukça farklı olan bu uygulamaya bir soru yönelttiğimizde karşımızda bir insan varmışçasına yanıtlar alabiliyoruz. Sıfırdan verdiğimiz bir girdiye göre bize bir içerik üretebiliyor. Cover letter yazdırabiliyoruz, kod düzenlemeleri yaptırabiliyoruz, bir yazının özetini alabiliyoruz ve çok daha fazlası..</p><p>ChatGPT, bir tür generative AI modeli olduğu için bu yeteneklere sahip aslında. Bu tür modeller, metin tabanlı verileri üretebilen yapay zeka sistemleridir ve genellikle doğal dil işleme (NLP) yeteneklerine sahiptirler.</p><p><em>Peki NLP nedir?</em></p><p>NLP (Natural Language Processing) veya Türkçe’siyle doğal dil işleme, yapay zekanın bir alt dalıdır. Doğal insan dilinin bilgisayarlar tarafından anlaşılması ve işlenmesi anlamına gelir. Bu teknoloji, metin verileri üzerinde çalışarak, metinlerin analiz edilmesi, çeviri yapılması, metinlerden anlam çıkarılması ve metin tabanlı soruların yanıtlanması gibi birçok uygulama alanında kullanılır.</p><p><em>LLM (Large Language Model)</em></p><p>LLM, büyük boyutlu ve karmaşık yapılı doğal dil işleme (NLP) modellerini ifade etmek için kullanılan bir terimdir. NLP, doğal dilin işlenmesi ve anlaşılması alanına odaklanırken, LLM’ler de bu alanın güncel teknolojik gelişmelerini temsil ederler aslında. Bu modeller, büyük miktarda metin verisini train eden ve işleyen doğal dil anlama ve üretme yeteneklerine sahip yapay zeka sistemleridir. Metin tabanlı görevlerde (örneğin, metin üretme, çeviri, özetleme, duygu analizi gibi) çok başarılı olabilirler.</p><p><em>Prompt kavramı</em></p><p>Bizim bu tür modellere girdi olarak vereceğimiz herşey prompt olarak isimlendirilir. Prompt, bir modelin nasıl çalışacağını veya nasıl yanıt vereceğini belirleyen bir başlatıcı input’tur aslında. Özellikle generative AI gibi modeller, verilen bir prompt’a göre bir içerik üretmeye çalışır. Örneğin, “Bana X okulunda X bölümüne başvuru yapmam için bir cover letter yazar mısın?” gibi bir prompt, modelin ilgili bölüm ve okul hakkında hakkında bir yazı oluşturmasını tetikleyecektir.</p><p>Doğru ve etkili bir prompt yazdığınızda, modelin istediğiniz sonuçları üretmesine daha fazla yardımcı olursunuz. Bu nedenle prompt’ların tasarımı ve kullanımı, AI tabanlı uygulamalarda önemli bir konu haline geldi ve karşımıza <em>Prompt Engineering</em> dediğimiz yeni bir meslek kolu çıkmış oldu.</p><p><em>Prompt engineering nedir?</em></p><p>Prompt engineering yani Türkçe’siyle istem mühendisliği, modelden istenen yanıtları veya davranışları ortaya çıkarmak için bir doğal dil işleme (NLP) modelinin girdi talimatlarını veya istemlerini yani prompt’larını dikkatli bir şekilde hazırlama ve tasarlama sürecidir. Modelin doğru, anlamlı veya daha spesifik çıktılar üretmesine yardımcı olacak şekilde prompt’ların formüle edilmesini içerir.</p><p>Amaç, modele açık veya bir takım düzenlenmiş direktifler sağlayarak modelin çıktısını etkilemektir. Bu düzenleme, giriş prompt’unun ifade ediliş şeklini, içeriğini veya biçimini ayarlayarak yapılabilir.</p><p>Şimdi bir kaç maddeyle prompt engineering yaparken ya da en azından ChatGPT gibi bir tool’u kullanırken ne gibi kurallara dikkat edebiliriz, bunları inceleyelim.</p><p><strong>Clarity and Specificity: </strong>Açık, spesifik ve net bilgi içeren prompt’lar oluşturmak, modelin kullanıcının amacını doğru bir şekilde anlamasını sağlamaya yardımcı olabilir. Daha net ve detaylı talimatlar, modele daha alakalı yanıtlar vermesi için yol gösterebilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*ZdV0f_jrz7WnZA-4mwOAkQ.png" /><figcaption>Clarity and Specificity Sample</figcaption></figure><p>Yukaridaki konuşma çok basit bir örnek oldu farkındayım, ancak açık ve net sorular sormak anlamında iyi bir örnek olabilir. Karşımızda bir insan varmış gibi yanıtlar alıyoruz evet ama, karşımızdaki bir insan değil, bunu unutmamamız lazım. En nihayetinde bu model bizim verdiğimiz inputları arka tarafta bir takım sayısal değerlerle tutup, yine bu sayısal değerlere göre bir tahminleme yapıp bize bir yanıt dönüyor. Dolayısıyla random bir şeyler yazmak, detay vermemek daha iyi sonuçlar almamızın önünde bir engel oluşturuyor. Bu noktada t<strong>okenization </strong>kavramı giriyor aslında devreye, yazının sonuna doğru bu kavramdan bahsediyor olacağım.</p><p><strong>Contextual Information:</strong> Prompt içerisine bağlamsal bilgiler eklemek, bir ön bilgi, veri seti ya da küçük bir veri parçası ile sorumuzu desteklemek oldukça önemli olabilir. Bu bilgiler, modelin bağlamsal olarak daha ilgili çıktılar oluşturmasına yardımcı olabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*LtXHUNFGBCCKPtr2hFiIFg.png" /><figcaption>Contextual Information Sample</figcaption></figure><p>Burada bir line grafiği istediğimi, koordinatlarımın ne olacağını söyledim ve prompt’umu küçük bir veri setiyle destekledim. Sonrasında aldığım kod çıktısını bir Jupyter notebook’da çalıştırdığımda grafiğim görselde gördüğünüz gibi oldu.</p><p><strong>Multi-Turn Conversations:</strong> Çok yönlü konuşmalar yapmak kullanıcı ve yapay zeka modeli arasında bir sohbetin birden fazla dönüşü(turn) içerdiği bir etkileşim biçimidir. Bu tür etkileşimlerde, kullanıcı tipik olarak konuşmayı bir ilk mesaj veya soruyla başlatır ve ardından yapay zeka modeli bir yanıt verir. Sonrasında kullanıcı bir soru daha sorar ve yeni bir yanıt alır ve bu şekilde devam eder. Dolayısıyla modelle konuşurken daha kümülatif çıktılar alma şansınız olur. Örneğin bir soru sordunuz ve bir yanıt aldınız. Sonra bu eklemeyi de yapabilir misin, ya da son cümlede söylediğin x kavramını anlamadım gibi bir takım geri dönüşlerle alacağınız yanıtı iyileştirebilir ya da bağlamsal yeni sorular sorabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcbcLzSX6lSDdJTnOZ-M0w.png" /><figcaption>Multi-Turn Conversations Sample</figcaption></figure><p>Yukarıdaki örnekte önce bir kod inputu verdim ve bunu StringBuilder kullanacak şekilde düzenlemesini istedim. Ardından bu iki syntax örneği için bir performans karşılaştırması yapmasını istedim. Burada ben aynı session özelinde yeni bir soru sordum ve model karşılaştırması gereken şeylerin ne olduğunu bir önceki prompt’uma göre biliyor hale geldi ve benim için ilk yazdığım kod ile StringBuilder’lı kod arasında bir performans karşılaştırması yaptı.</p><p><strong>Chain of Thought (CoT): </strong>Bu yaklaşımda modele bir takım direktifler verilerek ve nasıl düşünmesi gerektiği söylenerek, mantıklı bir yanıt zinciri oluşturması gerektiği konusunda rehberlik edilmeye çalışılır.</p><p>CoT’nin temel mantığı, bir takım talimatlar veya direktifler kullanarak modelin düşünme sürecini şekillendirmektir. Dolayısıyla her bir talimat, modelin bir önceki direktife dayalı olarak mantıklı bir yanıt üretmesi için tasarlanmalıdır. Bu şekilde, model, bir düşünce akışı oluşturur ve bir konu veya görev hakkında tutarlı ve mantıklı yanıtlar üretebilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hr1wg9PLpLyUXm8WbE5dsA.png" /><figcaption>CoT Sample 1</figcaption></figure><p>Burada modele bir soru yönelttim ve sorumu adım adım düşünerek yanıtlamasını istedim. Yani modele adım adım düşünmesi ve açıklama yapması için bir direktif verdim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*1reojz99G30MmI7FWtfM5w.png" /><figcaption>CoT Sample 2</figcaption></figure><p>Burada ise tamamen başka bir session açıp bir önceki session’da modelden aldığım adımları kullanmasını söyledim. Yani yine modelden aldığım bilgiyi, modele göndereceğim başka bir prompt içerisinde kullandım ve bu adımları takip etmesi gerektiğini söyledim.</p><p><strong>Prompt Chunking: </strong>Karmaşık prompt’ları daha küçük, daha yönetilebilir chunk’lara yani parçalara bölmek için kullanılan bir yöntemdir. Bu daha küçük chunklar sayesinde daha odaklı ve bağlama duyarlı bir etkileşim sağlamış oluruz aslında. Bu yaklaşım, model tarafından oluşturulan yanıtların kalitesini arttırmaya ve yapay zekanın sorgunun her yönünü etkili bir şekilde anlamasına yardımcı olabilir. Tek seferde de bu sorguyu modele verebilirsiniz ancak burada token size limitinden dolayı bunu yapmaya ihtiyaç duyarız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*wiF_AdPjKdwwYJJJmBVwGw.png" /><figcaption>Token Size</figcaption></figure><p><em>Token &amp; Tokenization</em></p><p>Bu noktada biraz <strong>token </strong>kavramından bahsetmek istiyorum. Token bir metin verisinin veya dilin işlenmesi sırasında elde edilen, anlamlı olabilecek en küçük birimdir. Bu bir kelime, bir rakam, bir noktalama işareti veya birkaç karakter bile olabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*Z2gccCTRBk5QAvgUuORTUQ.png" /><figcaption><a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a></figcaption></figure><p><strong>Tokenization </strong>ise bir metni veya cümleyi bu anlamlı bileşenlere yani token’lara ayırmak için yapılan işlemdir.</p><p>Metin tokenlara ayrılırken, boşluklar, noktalama işaretleri ve dilbilgisel kurallar gibi faktörlere göre bir takım ayrımlar yapılır. Tokenization sırasında her token’a ayrı bir ağırlık (weight) değeri atanır. Bu ağırlık değeri, metinde o token’ın ne kadar sık görüldüğüne dayalı olarak belirlenir. Bu tip modellerde amaç sizin vereceğiniz inputa göre bir sonraki çıktıdaki token’ları tahmin etmeye çalışmaktır. Bu tahminleme yapılırken de bu token’lara verilen weight değerleri üzerinden bir hesaplama yapılır.</p><p>Verdiğiniz prompt içerisindeki token’lar modelde ne kadar çok görülmüşse ona o kadar büyük bir weight değeri verildiği için modelin bu token’ı ya da ilişkili token’ları yanıt verirken kullanma olasılığı da o kadar artıyor. Token ağırlığının büyük olması, modelin o token’a daha fazla dikkat etmesi gerektiği anlamına gelir. Özellikle bir token train verilerinde sıkça görülüyorsa, model bu token’ı daha fazla kullanmaya eğilimli olacaktır.</p><p>Yakın anlamlı kelimeler ve bağlamsal olarak ilgili diğer token’lar da model tarafından göz önünde bulundurulabilir ve yanıtlarda kullanılabilir. Model, verilen bir bağlam içinde anlamlı ve mantıklı yanıtlar üretme yeteneğine sahip olduğu için, yüksek ağırlığa sahip bir token’ın yanı sıra bu token’la bağlamsal olarak uygun diğer token’ları da kullanma eğiliminde olacaktır.</p><p>Örneğin, “güzel” kelimesi yüksek bir ağırlığa sahipse ve modelin eğitim verilerinde sıkça görülüyorsa, modelin yanıt verirken “hava bugün çok güzel” ifadesinde “güzel” kelimesini kullanma olasılığı daha yüksektir. Ancak, model aynı zamanda bağlamı dikkate alarak diğer kelimeleri ve ifadeleri de kullanabilir. Örneğin, “hava harika” veya “hava mükemmel” gibi benzer anlamlı ifadeler de üretebilir.</p><p>Özetle, daha yüksek ağırlığa sahip token’lar, modelin yanıtını belirlemede daha fazla etkiye sahip olacaktır.</p><p>Yukarıda bahsettiğimiz prompt chunking maddesine tekrar bakacak olursak, biz prompt’umuzu ne kadar uzun tutarsak oradaki token sayısı o kadar artacak ve modelin yanıtını belirleme sırasında her bir token için ayrılan ağırlık değeri daha küçük olacak. Dolayısıyla model bize daha az doğru ya da daha az mantıklı bir tahminleme yapacak. Bu da uzun prompt’ların yanıtlarda daha az etkili olabileceği anlamına gelir.</p><p>Bu makalemde <em>Prompt Engineering</em> kavramına olabildiğince değinmeye çalıştım. Umarım faydalı bir içerik olur. Şimdiden keyifli okumalar :)</p><p>Ek olarak, bu makale için araştırma yaparken sevgili Daron Yondem’in <a href="https://www.youtube.com/watch?v=J09R0Z5cjA8">Sıfırdan Azure OpenAI</a> eğitim videosu oldukça faydalı oldu benim için. Konuyla ilgili olanların mutlaka izlemesini tavsiye ederim.</p><p><em>Referanslar</em></p><ul><li><a href="https://www.youtube.com/watch?v=J09R0Z5cjA8"><em>https://www.youtube.com/watch?v=J09R0Z5cjA8</em></a></li><li><a href="https://docs.cohere.com/docs/model-prompting"><em>https://docs.cohere.com/docs/model-prompting</em></a></li><li><a href="https://www.promptingguide.ai/techniques/cot"><em>https://www.promptingguide.ai/techniques/cot</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fdcb15b0439" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/prompt-engineering-nedir-5fdcb15b0439">Prompt Engineering nedir?</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mutex vs. Semaphore]]></title>
            <link>https://medium.com/sabancidx/mutex-vs-semaphore-296b0cf5aa4?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/296b0cf5aa4</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[semaphore]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 16:08:20 GMT</pubDate>
            <atom:updated>2023-08-08T08:02:39.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCQZ1P8Y_WFTn8cPKYcMxg.png" /><figcaption>Mutex &amp; Semaphore</figcaption></figure><p>Herkese merhabalar. Bu yazımda <strong>mutex </strong>ve <strong>semaphore </strong>kavramlarının neler olduğundan ve birbirleri arasındaki farklardan bahsetmeye çalışacağım. Go ile bir takım örnekler uygulayarak konuyu pekiştirebilecek kod örnekleri göstereceğim.</p><p><strong><em>Critical Section</em></strong></p><p>Bir program eşzamanlı olarak çalıştığında, paylaşılan kaynakları yani shared resource dediğimiz alanı değiştiren kod bölümlerine aynı anda birden fazla thread tarafından erişilmemesi gerekir. Bu kısımlar, veri bütünlüğünü sağlamak ve race condition’lardan kaçınmak için her seferinde yalnızca bir işlem veya iş parçacığı tarafından yürütülmelidir. Paylaşılan kaynakları değiştiren bu kod bölümüne <strong>Critical Section</strong> denir. Critical Section, paylaşılan kaynaklara erişen ve bunları değiştiren bir program kodu parçasıdır aslında.</p><p><strong><em>Mutex nedir?</em></strong></p><p>Mutex (mutual exclusion), aynı anda paylaşılan bir kaynağa veya Critical Section’a yalnızca bir iş parçacığının ya da işlemin erişebilmesini sağlamak için eşzamanlı programlamada kullanılan bir yaklaşımdır.</p><p>Aynı anda shared resource bir alana birden fazla kez erişilmeye ve bir değişiklik yapılmaya çalışıldığında ortaya race condition dediğimiz bir problem çıkar. Bu gibi hataları önlemek için herhangi bir zamanda kodun Critical Section dediğimiz kısmını yalnızca bir thread veya goroutine’in çalıştırdığından emin olmak adına bir kilitleme mekanizması yani mutex kullanırız.</p><p>Bir iş parçacığı veya işlem, Critical Section’a girmek veya paylaşılan bir kaynağa erişmek istediğinde, mutex’i almaya çalışır. Mutex’in kilidi açılırsa, iş parçacığı veya işlem mutex’i başarılı bir şekilde alır ve kilitli hale getirerek işin yürütülmesine devam eder. Mutex zaten başka bir iş parçacığı veya işlem tarafından kilitlenmişse, istekte bulunan iş parçacığı veya işlem engellenir veya mutex’in kullanılabilir hale gelmesini bekleyen bir döngüde kalabilir.</p><p>Bir thread veya goroutine, Critical Section’daki işini bitirdiğinde, mutex’i serbest bırakarak kilidini kaldırır ve diğer goroutine’lerin onu alıp Critical Section’a girmesine izin verir.</p><p>Golang özelinde mutex, <a href="https://pkg.go.dev/sync">sync</a> paketi içerisinde mevcuttur ve built-in bir şekilde bu yapıyı kullanabiliriz. Mutex’te Lock (Kilitleme) ve Unlock (Kilit Açma) olmak üzere iki yöntem tanımlanmıştır.</p><p>Şimdi bir örnek üzerinden konuyu detaylandırmaya çalışalım. İlk olarak bir race condition örneği inceleyelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680fb368f8c0faab481537f0cfed63fa/href">https://medium.com/media/680fb368f8c0faab481537f0cfed63fa/href</a></iframe><p>Burada integer tipinde Price ve Name adlı iki alana sahip bir Product struct’ı tanımladık. Bu struct için bir setPrice metodu yazdık. Bu metot bir sync.WaitGroup pointer’ını parametre olarak alıyor ve içerisinde price değerini 1 artırarak goroutine’in execution işlemini tamamladığını bildirmek için WaitGroup’un Done() metodunu kullanıyor.</p><p>Main metodu içerisinde ise bir döngü başlattık. wg.Add(1) ile tek bir goroutine beklenmesi gerektiğini söyledik. Ardından, modelin setPrice metodunu eşzamanlı olarak yürüten go model.setName(&amp;wg) yazarak bir goroutine oluşturduk. Döngü ile tüm goroutine’leri oluşturduktan sonra, WaitGroup’un Wait() metodunu çağırdık. Bu, tüm goroutine’ler WaitGroup’ta Done metodunu çağırana kadar main goroutine’in execute edilmesini engellemek için yapılır. Son olarak da modelin price değerini ekrana yazdırdık.</p><p>Ancak buradaki kod örneğinde olası bir problem var. Birden fazla goroutine aynı model üzerinde aynı anda setPrice metodunu çağırıyor. Dolayısıyla biz bu kodu çalıştırmak istediğimizde her seferinde farklı bir Price çıktısı alacağız. Yani bir race condition problemi yaşayacağız.</p><p>İşte bu tarz bir problemi gidermek için mutex kullanabiliriz. Dolayısıyla kodu aşağıdaki şekilde güncelleyelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edd2d859c4fb9dc4ca9b9a7386c89099/href">https://medium.com/media/edd2d859c4fb9dc4ca9b9a7386c89099/href</a></iframe><p>Burada Product struct’ına bir sync.Mutex alanı ekledik. setPrice metodu, Price alanını değiştirmeden önce bu mutex’i lock’lyıp, daha sonra unlock yapıyor. Bu sayede, aynı anda yalnızca bir goroutine’nin shared resource bir alana erişmesini ve bunları değiştirmesini sağlayarak race condition’a engel oluyoruz. Dolayısıyla kodun çıktısında herhangi bir değişiklik olmayacak ve bizim için Price değeri her zaman 10000 olacak.</p><p><strong><em>Semaphore nedir?</em></strong></p><p>Semaphore, sınırlı sayıda kaynağa erişimi kontrol etmemize veya eşzamanlı işlem sayısını sınırlamamıza olanak sağlar. Semaphore’lar, birden fazla thread veya goroutine tarafından bir veya birden fazla sınırlı kaynağa erişimi kontrol etmek için kullanılabilir. Maksimum sınırın aşılmamasını sağlarken, belirli sayıda işlemin kaynaklara aynı anda erişmesine izin verirler. Bu sayede shared resource alanların verimli kullanılmasını sağlar ve birden fazla goroutine’nin aynı kaynağa aynı anda erişmeye çalıştığı durumlarda ortaya çıkabilecek race condition gibi problemlerin önüne geçer.</p><p>Bir kod örneği üzerinden gidelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/561af353300c1fccd558fed286b1fc02/href">https://medium.com/media/561af353300c1fccd558fed286b1fc02/href</a></iframe><p>Burada ilk olarak bir Semaphore struct’ı tanımladık. Bu struct içerisine concurrency kontrolü yapmak için concurrencyChan isimli bir channel ekledik.</p><p>Yazdığımız CreateSemaphore metodu parametre olarak bir integer değeri alıyor. Semaphore içerisinde eşzamanlı olarak çalışacak maksimum goroutine sayısını bu değerle belirtiyoruz.</p><p>Acquire metodu, semaphore’dan bir belirteç almaktan sorumludur. Yani bir goroutine’in shared resource bir alana erişmek için ilerleyebileceğini gösterir bize ve o alanı mevcut işlemler için kilitler. struct{}{} ifadesi Go dilinde genelde channel’larda veya bir takım senkronizasyon işlemlerinde kullanılır. Burada da amacımız herhangi bir özel veri taşımadan bir kaynağın kullanılabilirliğini ifade etmek olduğu için s.concurrencyChan &lt;- struct{}{} şeklinde bir atama işlemi yapıyoruz.</p><p>Release metodu ile boş struct’ı channel’dan çıkarıyoruz. Bu sayede channel bir sonraki değer için müsait hale gelecek. Aslında burada bir unblocking işlemi yapıyoruz.</p><p>Main içerisinde CreateSemaphore metodunu, maksimum eşzamanlılık değeri 10 olacak şekilde yeni bir Semaphore instance’ı oluşturmak için çağırdık. Tüm goroutine’ler tamamlandığında kontrol sağlamak için ise isDone isimli bir channel oluşturduk. Döngünün dışında main metodu, isDone channel’ından bir değer almak için bekleyecek (&lt;-isDone). Buradaki amacımız isDone değeri true olana kadar main goroutine’inini bloklamak aslında. Yani limit değerimize ulaştığımızda isDone true olacak ve main goroutine’i üzerindeki blok kalkacak.</p><p>Oluşturduğumuz bu yapı sayesinde en fazla 10 goroutine’nin aynı anda yürütülebilmesini sağlamış olduk.</p><p><strong><em>Mutex ve Semaphore arasındaki farklar</em></strong></p><ul><li>Mutex tek bir kaynağa veya critical section’a erişimi kontrol etmek için tasarlanmıştır ve aynı anda yalnızca bir iş parçacığının veya goroutine’in bu alana erişmesine izin verir. Semaphore ise birden çok kaynağa erişimi kontrol edebilir ve belirli sayıda iş parçacığının veya goroutine’in bu alanlara aynı anda erişmesine izin verebilir.</li><li>Semaphore, kullanılabilir kaynakların sayısını temsil eden bir değer tutar. Thread’ler veya goroutine’ler, bu sayıyı artırarak veya azaltarak kaynakları alabilir veya serbest bırakabilir. Dolayısıyla mutex’e benzer şekilde count’u 1 olan bir binary semaphore da kullanılabiliriz. Ancak mutex’in binary semaphore’dan farkı, mutex’i kilitleyen thread veya goroutine’le kilidi açan thread veya goroutine’nin aynı olması gerektiğidir.</li><li>Mutex’ler genellikle hassas senkronizasyon işlemleri için kullanılır ve aynı anda yalnızca bir iş parçacığına izin verilmesi gereken critical section dediğimiz kısmı korur. Öte yandan semaphore’lar, genellikle daha geniş senkronizasyon amaçları için kullanılır ve belirli sayıda iş parçacığının veya goroutine’in paylaşılan bir kaynağa aynı anda erişmesine izin verir.</li></ul><p>Bu yazımda mutex ve semaphore kavramlarına olabildiğince değinmeye çalıştım. Umarım faydalı bir içerik olmuştur. Keyifli okumalar :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=296b0cf5aa4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/mutex-vs-semaphore-296b0cf5aa4">Mutex vs. Semaphore</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vertical Slice Architecture ve CQRS & Mediator Implementasyonu]]></title>
            <link>https://medium.com/sabancidx/vertical-slice-architecture-ve-cqrs-mediator-implementasyonu-671b4b8943e8?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/671b4b8943e8</guid>
            <category><![CDATA[cqrs-pattern]]></category>
            <category><![CDATA[n-tier-architecture]]></category>
            <category><![CDATA[vertical]]></category>
            <category><![CDATA[mediator-pattern]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 21:17:57 GMT</pubDate>
            <atom:updated>2023-06-05T17:48:25.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4w0N6D80dW_0hUb2U0b7Aw.jpeg" /></figure><p>Herkese merhaba. Bu yılki Devnot Dotnet Konferansı’nda bu konuya dair bir sunum yapma şansım oldu. Sunumda aktarmaya çalıştığım bilgileri kalıcı hale getirmek adına bir makale yazısı hazırlamak istedim. Faydalı olması dileğiyle :)</p><p>Bu makalede size Vertical Slice mimarisi nedir, bize ne gibi avantajlar sağlar, Mediator ve CQRS pattern’lerini bu mimaride nasıl uygulayabiliriz, bunlardan bahsetmeye çalışacağım. Ancak bu kısma geçmeden önce aradaki farkları daha net görmek ve konuyu pekiştirmek adına geleneksel n-tier architecture nedir biraz bundan bahsedeceğim.</p><p><strong><em>N-tier Architecture nedir?</em></strong></p><p>N-tier arhctitecture uygulamamızı layer’lara bölen bir yazılım mimarisidir. Burada her katmanın kendi görevi kapsamında bir takım sorumlulukları vardır. Genellikle presentation, business logic ve data storage (access) olarak adlandırdığımız katmanlara ayrılır. Bu katmanlar uygulamanızın ihtiyaçlarına ve tercihlerinize göre daha fazla katmana seperate edilebilir. Ancak en standart haliyle bu şekilde kategorize edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*rpgJQVbnm6XU0ii2plKEAg.png" /><figcaption>N-tier Architecture</figcaption></figure><p>Buradaki katmanların kapsamını özetleyecek olursak;</p><ul><li><strong>Presentation layer: </strong>Kullanıcı arayüzündeki etkileşimden sorumludur, UI katmanımızdır. Bu katman web sayfalarını, bir takım arayüz kontrollerini içerir. Yine bu katmanda bazı request validation’lar da yapabiliriz (bir input değeri için iki karakter zorunlu, bir string değeri 50 karakterden fazla olmamalı gibi kontroller).</li><li><strong>Business logic layer: </strong>Bu katman gelen isteklerin işlenmesinden sorumludur. Genel olarak hesaplamalar, business validasyonlar (istenen id li kayıt database’de var mı gibi), bir takım uygulama kurallarını, business rule’ları işlediğimiz katmandır.</li><li><strong>Data access layer:</strong> Direkt olarak veri tabanıyla etkileşime giren, veri transferi yapabildiğimiz, CRUD işlemlemlerimizi gerçekleştirdiğimiz katmandır.</li></ul><p>Eğer düzgün tasarlanmış n-tier mimariye sahip bir uygulama geliştirdiysek burada presentation katmanının data katmanına doğrudan erişiminin olmamasını bekleriz. Çünkü presentation katmanı bir takım kullanıcı arayüzü işlemlerinden sorumludur ve data katmanıyla arasında direkt bir ilişki olmamalıdır. Yani UI’de yapacağınız bir değişiklik direkt olarak data katmanını etkilememeli, bozmamalı. Ek olarak data katmanı bu tarz bir mimaride çok merkezi bir konumda yer alıyor. Dolayısıyla burada kullanılan database teknolojisine oldukça bağımlıyız. Ayrıca herhangi bir verisel, şematik değişiklik yapmak istediğimizde uygulama kapsamında ciddi boyutta problemlerle karşılaşabiliyor veya ilgili değişiklik için bir çok katmanda bir takım güncellemeler, eklemeler yapmak zorunda kalabiliyoruz. Özetlemek gerekirse standart n-tier mimaride yukarıdan aşağıya doğru bir derleme bağımlılığına sahibiz. Yani katmanlar arasında tightly coupled diyebileceğimiz sıkı bir ilişki var.</p><p><strong><em>Clean Architecture</em></strong></p><p>Zaman içerisinde bu bağımlılığı daha az sıkı(loosly coupled) hale getirmek için Dependency Inversion, Domain Driven Design gibi yaklaşımlar uygulanmaya başlanmış. Abstraction (soyutlama) kullanılarak ihtiyaç duyulan işlevleri, detay vermeyecek şekilde bir üst katmana sunmak amaçlanmıştır.</p><p>Bu yaklaşımlarla birlikte isimlendirme olarak başlarda Hexagonal Architecture olarak duyduğumuz, son yıllarda ise Clean Architecture olarak isimlendirilen yeni bir mimariyle tanıştık.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*Xux8VYtyAMHbWWPuT7kTMg.png" /><figcaption><em>Clean Architecture</em></figcaption></figure><p>Clean architecture da özünde layer bazlı bir mimari yaklaşım, ancak n-tier mimariye göre daha modüler ve esnek bir yapıya sahip. Burada sorumluluklar daha modüler bir şekilde birbirinden ayrılır. Dolayısıyla Separation of Concerns prensibine çok daha uygundur. Burada DI sayesinde yüksek seviye modüller, düşük seviye modüllere değil soyutlamalara bağlı hale getirilmeye çalışılıyor. Dolayısıyla ihtiyaçlara ve teknolojik değişikliklere daha hızlı adapte olduğumuz yeni bir yapı sağlıyor bize.</p><p>Bu mimarideki katmanları detaylandıracak olursak;</p><ul><li>Bu mimaride uygulamanın merkezinde entity’ler ve core business rule’lar yer alır. Temel uygulama fonksiyonlarının diğer external bağımlılıklarla tightly coupled bir ilişkisinin olmaması gerekir. Buradaki amaç dış katmanlardan, teknolojilerden, frameworklerden olabidiğince bağımsız bir logic oturtmak.</li><li>Bir üst katmanda application business rule’lar yer alır. Burada da bir takım use case’lerimizi implemente edebiliriz.</li><li>Bu katmanın üzerinde ise presentation layer’larımız, gateway’lerimiz yer alır. Burası artık dış dünyaya açıldığımız katmandır ve bir takım client side kontrolleri gerçekleştiririz. Bu katmanda önemli bir business logic bulunmaz.</li><li>En dış katmanda ise gördüğünüz gibi framework, library ve çeşitli external tool’ları içeren bir katman var. Yani en az bağımlı olmak istemediğimiz katmanı en dışta tutmamız gerekiyor. Çünkü bir framework’e ya da bir teknolojiye bağlı kalmak istemiyoruz. Bu mimari yaklaşımdaki en önemli amaçlardan biri de bu.</li></ul><p>Son olarak örnek vermek gerekirse Onion Architecture, Clean Architecture uygulayabilmek için kullandığımız tasarım kalıplarından biridir. Belki bu şekilde daha pekiştirici bir açıklama yapmış olurum.</p><p><strong><em>Clean Architecture Dosya Yapısı</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*R2hLurJvadv8_tblCg1mEQ.png" /><figcaption>Folder Structure</figcaption></figure><p>Burada basit bir örnek üzerinden clean architecture bir projedeki dosya yapısını göstermek istiyorum. Buradaki katmanları amacına uygun olarak çok daha fazla katmana da bölebilirsiniz. Ancak daha basit bir uygulama örneği üzerinden gidecek olursak;</p><ul><li>Core katmanında entity’lerimiz ve uygulamaya özel use case’lerimiz yer alır. Repositroy interface’lerimiz bu katmanda bulunmalıdır.</li><li>Infrastructure katmanında database ile ilgili işlemlerimizi gerçekleştiririz ve repository interface’lerimizin implementasyonlarını burada yazarız. Burada farklı database teknolojileri kulanarak ilerleme şansımız var.</li><li>Shared katmanına projedeki ortak bir takım business logic’leri, helper’ları ekleyebiliriz.</li><li>Web katmanı ise standart presentation layer’ımızdır.</li></ul><p><strong><em>Olası Dezavantajlar</em></strong></p><p>Clean architecture bir çok problemi aşmaya yönelik ve daha esnek bir çalışma alanı sunmak için tasarlanmış bir mimari yaklaşım. Ancak bu mimarinin de kendi içerisinde bir takım dezavantajları var. Bunlar kesin bir şekilde dezavantajdır denemez ancak uygulamamızın kapsamı genişledikçe yaşabileceğimiz bir takım problemlerdir.</p><ul><li><strong>Monolotik yaklaşım</strong></li></ul><p>İlk olarak bu mimari monolitik bir yaklaşıma sahip. Dolayısıyla kod üzerinde bir ölçeklendirme yapmak, yeni bir özellik eklemek istediğimizde her katmanda bir takım değişiklikler yapmalıyız. Örnek vermek gerekirse, bir kütüphane otomasyonu uygulamanız var ve siz yeni bir request geliştirmesi yapmak istiyorsunuz. Mesela kitap ekleme işleminiz vardı, şimdi de yazar ekleme işlemi yapmak istiyorsunuz. Bunun için UI katmanında bir DTO modeli oluşturmalısınız, gerekiyorsa request validasyonlarını burada yazmalısınız. Core kısımda domain entity’si oluşturmalısınız. Yine burada bu işi yapacak abstract metotu tanımlamalısınız. Infrastructure ya da repository katmanında bu işi yapacak abstract metotu implemente etmelisiniz. Bu şekilde her katmanda ayrı ayrı bir takım geliştirmeler yapmanız gerekli. Zaman içerisinde domain objeleriniz, bunlar özelinde yapmanız gereken işlemler arttıkça uygulamayı scale etmeniz ve zamanla uygulamanızın bakımını yapmanız daha da güçleşebilir. Çünkü katman bazlı bir genişleme söz konusu olacak.</p><ul><li><strong>Test yazımı için mock data maliyeti</strong></li></ul><p>Diyelim ki anemic değil ama rich domain modelde bir uygulamanız var, dolayısıyla entity bazında behavioral işlemleriniz olacak. Bu noktada unit test yazmak çok zor olmayabilir, ancak integration ya da end-to-end testler yazmak söz konusu olduğunda durum biraz daha karmaşık hale gelebilir. Çünkü integration test yaparak katmanlar arası bir kontrol yapıyorsunuz, bir akışı test ediyorsunuz. Dolayısıyla aradaki bütün iletişim trafiğini, soyutlamaları testinize dahil etmeniz gerekir. Bu da çok fazla objeyi mocklamanıza neden olabilir.</p><ul><li><strong>Gereksiz soyutlamalar yapmak</strong></li></ul><p>Clean architecture mimarisi karmaşıklığa yol açabilecek çok fazla soyutlama veya katmanın eklenmesine eğilimlidir. Bu anlamda zaman içerisinde gereksiz soyutlamalar eklemek, okunabilirlik anlamında kodunuzun kalitesini düşürebilir. Bu da projeye yeni dahil olanların adapte olmasını yavaşlatabilir.</p><ul><li><strong>Performans düşüklüğü</strong></li></ul><p>Katmanlar yeterince optimize kodlanmamışsa bu bir performans düşüklüğüne sebep olabilir. Örneğin data katmanında kompleks bir query yazdınız ya da teknoloji bazlı bir probleminiz var. Bu verilerin alınmasıyla ilgili bir gecikmeye sebep olabilir ve verinin daha üstteki katmanlara aktarılma süresi uzayabilir. Ya da katmanlarınız bir network üzerinden iletişim kuruyor olabilir. Buradaki networksel bir aksama yine performans düşüklüğü oluşturabilir. Aynı servis metotlarına çok fazla yerden erişim sağlamanız da bir lock’lamaya sebep olup uygulamanızı yavaşlatabilir.</p><p><strong><em>Vertical Slice Architecture</em></strong></p><p>Bu noktadan sonra ana konumuz olan Vertical Slice Architecture’dan bahsetmek istiyorum. Vertical Slice Architecture’ın fikir sahibi aslında Jimmy Bogard. Kendisi “AutoMapper, MediatR” gibi library’leri de geliştiren kişi. <a href="https://jimmybogard.com/">Buradan</a> kendisinin blog yazılarına ulaşabilirsiniz.</p><p>Vertical Slice Architecture’ı kısaca VSA olarak ifade edelim ve bu şekilde devam edelim :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZTEM9VvW9KvRcoCQuhSOQ.png" /></figure><p>VSA anlatımı yapılırken genelde bir pasta dilimi örneği üzerinden gidilir. Ben de burada bu tarz bir anlatım yaparak konuyu anlatmaya çalışacağım. Şimdi yukarıda bahsettiğimiz gibi clean architecture’da infrasturcture, domain, application, presentation gibi katmanlarımız vardı. Bu katmanların her birinin pastadaki bir katman olduğunu düşünelim. Normal şartlarda bir pastayı yerken önce üstteki süslemeli soslu kısmı bitirip, sonra altındaki keki, sonrasında ise alttaki pastacı kremasını yiyelim gibi bir yaklaşım sergilemeyiz. Pastanın tepesinden dik bir şekilde bir çatal batırarak bütün katmanları aynı anda yemek isteriz. VSA’deki ana mantık da bu aslında. Yani siz bir request için bütün katmanlarda ayrı ayrı geliştirmeler yapmaktansa, tüm bu işlemleri tek bir class içerisinde gerçekleştirin ve bu class artık sizin için bir feature olsun.</p><p><strong><em>Feature nedir?</em></strong></p><p>Peki feature nedir biraz daha detaylandıralım. Yukarıda bahsettiğimiz kütüphane otomasyonu örneği üzerinden gidelim. Diyelim ki bir Book entity’miz var ve bu entity özelinde yapabileceğimiz işlemler yani request’ler aşağıdaki gibi olsun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjQwPlBhBwwOmemqndv52g.png" /></figure><p>VSA bize şunu söylüyor; bu request’ler için yazdığın servis metotlarını birer feature class’ına taşı ve bu request özelindeki tüm inputlarını, outputlarını, validasyonlarını, mapper’larını, database erişim işlemlerini tamemen bu feature’lar içerisinde yaz. Yani artık ben bu request işlemi için tek bir class yazacağım, bu class’ı da feature olarak adlandıracağım ve bahsettiğim tüm adımları bu feature içerisine yerleştireceğim.</p><p>Mesela burada AddBook, DeleteBook, GetAllBooks olarak tanımladığımız işlemlerin hepsi bizim için artık bir feature’a karşılık gelecek ve her biri birbirinden bağımsız olacak. Her bir feature sadece kendi görevi kapsamında bir işlem yapacak, kitap ekleme, silme, bir kitabın detayını alma gibi.</p><p>Dolayısıyla artık bir request döngüsü bizim için aşağıdaki gibi olacak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7fmxvlrY-F9AtdZRfSvVg.png" /></figure><p>Kullanıcı UI kısmından bir istekte bulunacak ve bu istek ilgili feature’a gönderilecek. Şimdi bu noktada şunu sorabilirsiniz; yine elimizde belli classlar(feature) var ve bizim bu class’lardaki handler’ları tetiklememiz için presentation layer’da örneğin controller’da bu class’ların bir instance’ını oluşturmamız ya da bu class’ları bir şekilde inject etmemiz gerekmez mi?</p><p><strong><em>Mediator Pattern</em></strong></p><p>İşte bu noktada yardımımıza mediator pattern koşuyor. Nedir peki mediator pattern?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHdrUqaoLiWV__qY0T7AGA.png" /></figure><p>Bu pattern, birbiriyle ilişkili nesneler arasında birebir bir ilişki kurmaktansa araya ortak bir arabulucu nesne yerleştirip iletişim trafiğini tamamen bu nesne üzerinden yapmamız gerektiğini söyler. Bu pattern anlatılırken genelde hep bir kontrol kulesi örneği verilir. Aslında ana mantığı anlatmak için bu çok güzel bir örnek. Bildiğiniz gibi uçaklar sadece kontrol kulesiyle haberleşir, birbirleriyle değil. Hangi uçak havaalanına inmeli, hangi uçak kalkışa geçmeli, anlık rota durumu vs gibi konularla ilgili sadece kontrol kulesiyle iletişimde olurlar. Mediator pattern de aslında bu mantıkla ilerlememizi söylüyor. Yani biz bir request işlemi yaptığımızda bu istek araya yerleştirdiğimiz mediator nesnesi sayesinde bizim gönderdiğimiz request tipine göre gitmesi gereken handler’a gidecek ve bizim ilgili class’ı direkt olarak kullanmamız gerekmeyecek.</p><p>Bu noktada birazdan vereceğim örneklerde mediator pattern’i uygulayabilmek için .Net özelinde bir uygulama örneği hazırladım ve bunun için MediatR Library’sinden yararlandım. Şimdi bu library’ye göre ben artık feature’ımı aşağıdaki şekilde güncelleyebilirim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*KzGgKN0-7cQgCZrJ4_IGVg.png" /></figure><p>Artık bizim request modelimiz yani inputumuz bir IRequest&lt;T&gt; objesinden türeyecek ve sonucumuz da yine bu T objesine bağlı olacak. Response tipi ile birlikte bir request’i temsil edecek aslında. Benzer şekilde handler’ımız da IRequestHandler interface’inden kalıtım alacak ve verdiğimiz request ve response tipine göre bir feature’ı temsil edecek. Buradaki IRequest ve IRequestHandler, MediatR kütüphanesinin bize sağladığı interface’ler. Artık sağladığımız bu generic yapı sayesinde mediator objesi bizim için verdiğimiz T objesine göre ilgili feature’ın handler’ına giderek yapması gereken işlemi gerçekleştirecek ve bir response dönecek.</p><p><strong><em>CQRS (Command Query Responsibility Segregation)</em></strong></p><p>Şimdi de biraz CQRS pattern’den bahsedelim. Bu pattern’deki ana mantık okuma ve yazma işlemlerimizi birbirinden ayırmaktır. Okuma işlemleri için query kavramını, yazma işlemleri için ise command kavramını kullanıyoruz. Yani sistemde bir değişiklik yapacak işlemler command, geriye sadece bir sonuç döndürecek ama herhangi bir değişikliğe sebep olmayacak işlemler query olarak adlandırılır.</p><p>Bu pattern’deki en önemli avantajlardan biri de yazma ve okuma işlemleri için ayrı database’ler ve tenolojiler kullanmamıza olanak sağlaması. Mesela yazma işlemleriniz için EF Core kullanırken okuma işlemleriniz için Dapper kullanabilirsiniz. Dapper aslında micro ORM diyebileceğimiz bir teknoloji ve EF Core’a göre daha performanslı bir ORM teknolojisi. EF core bize Unit of Work gibi bazı repostiory pattern’lar sağlayabiliyor ve yazma işlemlerimizi çok daha kolay hale getirebiliyor. Ancak komplike sorgulamalar yaparken performans anlamında bir takım sıkıntılar yaşatabiliyor. Dolayısıyla Dapper bu anlamda daha esnek ve perfromanslı. Burada statik bir takım scriptlerinizi, sorgularınızı ekleyebiliyorsunuz. Bu sorgular ADO.NET’e gönderilirken herhangi bir custom query’ye çevrilmiyor ve ek bir dönüşüm yapılmadan doğrudan ADO.NET’e gönderiliyor. Ayrıca ADO.NET’den dönen sonuç bir datasete’e doldurulurken, Dapper da ise bu sonuç bir objeye bind ediliyor. Tüm bunlar performans anlamında bir kazanım demek aslında. Dolayısıyla CQRS sayesinde bu gibi ORM tercihlerini yapma şansı bizim için çok önemli.</p><p>Şimdi biz her bir request’imiz için bir feature tanımladık. Bu feature’ların yaptığı işlemler okuma, yazma, ekleme, silme, listeleme gibi işlemler olabilir. Bu noktada bizim bu istekleri get ya da post olacak şekilde kategorize etmemiz yani CQRS pattern’e uymamız çok daha kolay hale gelecek. Mesela kitap ekleme feature’ı bir post işlemi olduğu için command, kitap listeleme bir get işlemi olduğu için artık bir query’dir diyebileceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnI3Xsff76flhhDnQls-WQ.png" /></figure><p>Burada şunu da söylemekte fayda var. Bildiğiniz gibi Domain Driven Design behavioral domain object mantığını yani rich domain model’i destekler. Yani DDD domain etrafında bir takım business gerekliliklerini modellemeye çalışır, böyle bir konsepte sahip. Biz de buradaki use case’leri feature bazında kategorize ediyoruz. Dolayısıyla bu konsepte uyumlu bir yaklaşım sergiliyoruz aslında. Yine CQRS ile bu modellemeyi okuma ve yazma bazında da ayırıyoruz ve tüm bu seperate edilmiş modeller arasında Mediator pattern yardımıyla iletişim sağlayabiliyoruz. Dolayısıyla DDD’nin bu konsepti, VSA, CQRS ve Meditor ile bütüncül bir şekilde örtüşüyor. Bu anlamda tüm bu yaklaşımları bir araya getirmek çok daha performanslı, maintain etmesi kolay uygulamalar geliştirmemizi sağlayabilecektir.</p><p><strong><em>VSA Dosya Yapısı</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*LdRLIsMGRcMsB5VJXt6r4Q.png" /></figure><p>Clean architecture özelinde gösterdiğimiz örneği VSA’ye uyarlayalım. Gördüğünüz gibi tek bir katman altında controller’larımız, domain’lerimiz, data katmanı ve feature’larımız var. Feature altında her bir domain için bir klasör bulunuyor. Her domain’in de kendine ait command ve query’ler için ilgili handler’ları farklı klasörler altında. Gördüğünüz gibi daha görünür ve bağımlılık açısından çok daha esnek bir yaklaşım elde etmiş olduk.</p><p>Bu kadar bahsettikten sonra şimdi de basit bir feature örneği verelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*-eq2wTb05hFusWgL" /><figcaption>AddBookHandler.cs</figcaption></figure><p>Burada AddBookCommand ve AddBookResponse modellerimizi görüyorsunuz. Bu modeller bizim input ve outputlarımıza karşılık geliyor. Bu feature’da bir ekleme işlemi yapacağımız için yani bir command uygulayacağımız için input’umuzu AddBookCommand olarak isimlendirdik ve Mediatr’dan yararlanabilmek için IRequest objesinden kalıtım aldık. Tabi burada çıktımızın AddBookResponse modeline bağlı olduğunu kalıtım yaparken belirttik.</p><p>Gördüğünüz gibi command nesnesinde kullanıcıdan almak istediğimiz alanlar var. Yani kullanıcı yeni bir kitap eklemek istediğinde bu kitabın adını, yazarının id’sini, yayınlanma yılını bize vermeli. Response modelinde ise işlem başarılı mı değil mi şeklinde Id property’si ile kayıt eklendiyse geçerli bir kitap id’si döneceğiz.</p><p>Daha sonra AddBookHandler class’ımızı ekledik. Yine burada IRequestHandler interface’inden kalıtım aldık ve input ve output tiplerimizi belirttik. Bu interface ilgili istek için default bir handler metodu implement etmemizi istiyor. Dolayısıyla daha sonra gelen requesti handle etmemizi sağlayacak metotu yazdık. Bu metot command’ımızı parametre olarak aldı. Önce bu kayıt database’de var mı diye küçük bir validasyon işlemi yaptık, kayıt yoksa command’dan gelen bilgileri Book entity’sine map ettik ve sonrasında database’e bir kayıt işlemi gerçekleştirdik. Son olarak da geçerli id’yi döndük.</p><p>Şimdi controller’dan bu feature’a nasıl eriştiğimize bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*1nSR4VbIqNIfjMCB" /><figcaption>Controller.cs</figcaption></figure><p>Controller tarafında ise gördüğünüz gibi sadece mediator objesi için bir injection işlemi yaptık. Uygulama ayağa kalktığında ve biz bir istek yapmak istediğimizde buradaki AddBookHandler feature’ına eklediğimiz command tipi sayesinde mediator objesi hangi handler’a gitmesi gerektiğini bilecek ve isteği oraya yönlendirecek.</p><p><strong><em>VSA’in sağladığı avantajlar</em></strong></p><p>Bu mimari beraberinde bize bir çok avantaj getiriyor. Bunları aşağıdaki şekilde listeleyebiliriz.</p><ul><li><strong>Refaktoring yapmaya teşvik etmesi</strong></li></ul><p>Feature’lardan bahsederken ne demiştik, her bir feature birbirinden bağımsız ve aralarındaki kod benzerlikleri minimum düzeyde olmalı. Ancak yine de feature’lar arasında zaman içerisinde bir kod benzerliği (code coupling) yaşanabilir, benzer businuess logicler yazabiliriz. VSA bu coupling’i olabildiğince minimize etmemizi ister. Dolayısıyla bizi periyodik olarak refaktoring yapmaya da teşvik eder.</p><ul><li><strong>Daha az conflict yaşanması</strong></li></ul><p>Feature bazlı çalışıldığı için merge conflict yaşama oranı çok daha düşük. Domain bazlı her bir feature’ımız farklı classlarla tanımlıdır. Dolayısıyla bir feature’da çalışan developer’ın yaptığı geliştirmeler başka bir feature’da çalışan developer’ı etkilemez.</p><ul><li><strong>Ölçeklenebilirlik (scalability) kolaylığı</strong></li></ul><p>N-tier architecture’da yeni bir özellik eklemek istediğimizde ya da var olan bir özelliği güncellemek istediğimizde ilgili bütün layer’ları scale etmemiz gerekirken burada sadece o feature class’ı içerisinde bir güncelleme ya da ekleme yapmamız gerekecek, çünkü hiç bir katmana bağımlı değiliz ve tek bir class özelinde çalışıyoruz.</p><ul><li><strong>Daha dokümante kod yapısı</strong></li></ul><p>Daha dokümante bir kod yapısı sağlar. Bakıldığı an hangi feature’ın nasıl bir görevinin olduğu bellidir. Bu feature bazındaki ihtiyaçlar yine bu feature içerisinde tanımlandığından farklı katmanlara gidip kodu inceleme ihtiyacı olmayacak. Bu özellikle projeye yeni dahil olan geliştiricilerin çok daha hızlı adapte olmasını sağlayacaktır. Benim için böyle olmuştu açıkçası :)</p><ul><li><strong>Farklı ORM teknolojileri kullanma şansı</strong></li></ul><p>Her bir feature’da farklı bir database teknolojisi kullanabilme şansınız var. Bir request’imizi EF Core kullanarak işlerken başka bir request’deki işlemi Dapper’la gerçekleştirebiliriz. Belli tanımlamalar için NoSQL bir teknoloji kullanmak isteyebiliriz gibi. Normalde mikroservislerde farklı teknolojiler kullanılabiliyorken, bu yaklaşımla bunu kod düzeyine indiriyoruz. Bu da bize ihtiyaca yönelik daha esnek olabilme şansı veriyor.</p><ul><li><strong>Planlamalarda işleri daha doğru eforlayabilme</strong></li></ul><p>Yine sprint planlamalarınızda alacağınız maddeleri size’larken daha doğru tahminler yapmanızı sağlar. Çünkü bir feature özelinde çalışacaksanız aslında yapmanız gereken iş, eklemeniz gereken modeller vs. daha nettir. Çünkü mevcut feature da ya da eklenecek yeni bir feature’da yapılacak tüm adımlar gözünüzün önündedir.</p><ul><li><strong>Test yazım kolaylığı</strong></li></ul><p>Yine VSA’de uçtan uca testler yazmanız çok daha kolay hale geliyor. Çünkü artık çok daha az bağımlılığa sahipsiniz. N-tier’da bunu yaparken bağımlı olduğunuz tüm abstract classları mock’lamak durumundasınız ki gerçek senaryoyu test edebilin. VSA’de ise testini yazmak istediğiniz feature’ın aldığı command ya da query modelini mock’lamanız sizin için yeterli olacak. Sonrasında da test etmek istediğiniz handler’ı tetikleyeceksiniz. Çünkü artık input, output modeliniz, validasyonlarınız, mappingleriniz, database erişim işlemleriniz, özetle bu feature’ın ihtiyacı olabilecek her şey yine bu class’ın içerisinde. Aşağıda bununla ilgili bir kod örneği vermek istiyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*HCiVErDNkgyKyDvr8UiXrg.png" /><figcaption>Integration Test</figcaption></figure><p>Başarılı şekilde bir kitap ekleme işlemi ve geçerli bir id alma senaryosu için bir test yazdık ve gördüğünüz gibi bir kaç adımda bu akışı test edebildik. Bunun için sadece bir command modeli mock’lamamız ve ilgili handler’a gidebilmek için bir mediator objesi inject etmemiz yeterli oldu.</p><p>Ek olarak VSA sayesinde daha hedef odaklı testler yazabiliriz. Çünkü o feature tek bir amaca hizmet ediyor. Bir şey ekleme, bir şey çıkarma, herhangi bir filtreye göre bir veri listesi çekmek gibi.</p><p>Özetlemek gerekirse, bu makalede salt bir şekilde n-tier mimariyi yermek değil, Vertical Slice Archtiecture’ın bize sağladığı tüm bu avantajların altını çizmek istedim. Tabi ki tercihlerinize ve ihtiyaçlarınıza göre monolitik çalışmak mı, n-tier bir yapıyı benimsemek mi, yoksa VSA kullanmak mı sizin için daha avantajlı buna siz karar vermelisiniz. Bu mimari yaklaşımlardan hangisi uygulamanızın kapmasına daha uygun olacaksa buna göre ilerlemelisiniz.</p><p>Vertical Slice örneğinde kullandığım uygulamanın reposuna <a href="https://github.com/ezgigokdemir/VerticalSliceBookApi">buradan</a> ulaşabilirsiniz.</p><p>Umarım faydalı bir içerik olmuştur. Şimdiden keyifli okumalar :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=671b4b8943e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sabancidx/vertical-slice-architecture-ve-cqrs-mediator-implementasyonu-671b4b8943e8">Vertical Slice Architecture ve CQRS &amp; Mediator Implementasyonu</a> was originally published in <a href="https://medium.com/sabancidx">SabancıDx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Garbage Collector]]></title>
            <link>https://ezgigokdemir.medium.com/go-garbage-collector-6d33622eaece?source=rss-b23914a50c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d33622eaece</guid>
            <category><![CDATA[garbage-collector]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ezgi Gökdemir]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 21:51:20 GMT</pubDate>
            <atom:updated>2023-02-06T14:28:34.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*d02JTO6X4Azbzpo7PaKV1A.png" /><figcaption>Go Garbage Collector</figcaption></figure><p>Herkese merhaba. Bu yazıda Garbage Collector nedir, Go ile bu sistem nasıl kullanılır ve Go dili bu anlamda ne gibi avantajlara sahiptir, bunlardan bahsetmeye çalışacağım.</p><p>Öncelikle Garbage Collector (kısaca GC) kavramının ne olduğunu anlamaya çalışalım.</p><p>GC, programda artık ihtiyaç duyulmayan bellek alanlarını otomatik şekilde boşaltan bir sistem yazılımı bileşenidir. C#, Java, Go gibi dillerde bu bellek yönetimi runtime’da otomatik bir şekilde yapılabilir ve bunun için harici bir kod yazmamıza gerek yoktur. Sadece bazen belli optimizasyonlar eklemek gerekebilir, belli değişkenlerin global yerine local’de tanımlanması gibi. Ancak C, C++ gibi dillerde deallocate işleminin tamamen manuel bir şekilde yapılması gerekir, burada görev kodu yazan geliştiricinindir.</p><p>GC’nin çalışma mantığını biraz daha detaylandırmaya çalışırsak; değişkenlerin <strong>heap </strong>ve <strong>stack </strong>olacak şekilde iki farklı hafıza biriminde tutulduğunu biliyoruz. Stack-allocated değerlerin kapladığı bellek, program bittiğinde otomatik olarak serbest bırakıldığı için GC’nin bu belleği yani stack’i yönetmesine gerek yoktur. Dolayısıyla GC sadece heap ile ilgilenir ve buraya depolanan referans tipli değişkenler üzerinde çalışır.</p><p><strong>Go’da Garbage Collector nasıl çalışır ve ne gibi avantajları vardır?</strong></p><p>GC’nin amacı diğer programlarda olduğu gibi Go’da da bellek yönetimi sağlamak ve kullanılmayan alanları iade etmektir. Go’da GC’ler için, collecting garbage maliyetini azaltmak ve programın performansının önemli ölçüde etkilenmemesini sağlamak için çeşitli algoritmalar ve optimizasyonlar kullanılır.</p><p>Bunlardan biri periodic tracing yaklaşımıdır. Periodic tracing, GC’ler tarafından bellek kullanımını izlemek ve programın artık ihtiyaç duymadığı belleği geri kazanmak için kullanılan bir tekniktir. Bu teknikte GC, nesneler arasındaki ilişkileri temsil etmek için bir nesne grafiği oluşturur ve programdaki herhangi bir değişken veya pointer tarafından artık erişilemeyen nesneleri belirlemek için heap’i periyodik olarak tarar. Bu şekilde deallocate işlemi yaparak bellek kullanımını iyileştirmeye ve bellek parçalanmasını azaltmaya yardımcı olur.</p><p>Tracing yapan tüm GC’ler arasındaki fark, hafızanın canlı olduğunu anladıklarında uygulayacakları yöntemdir. Go’da GC’ler ilerlemeyi yani tracing işlemini takip etmek için karşılaştıkları değerleri işaretlerler. Tracing işlemi tamamlandıktan sonra, GC heap’deki tüm belleği gözden geçirir ve işaretlenmemiş tüm belleği tahsis için uygun hale getirir. Bu yönteme ise mark-sweep tekniği denir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*J-vFmVCFG9XYkUXbvg-UGg.png" /><figcaption>Mark-Sweep example</figcaption></figure><p>Go Garbage Collector yapısının sahip olduğu bazı avantajları belirtirsek;</p><ul><li>Basit ve kullanımı kolay olacak şekilde tasarlandığı için geliştiricinin manuel olarak çok az durumda bellek yönetimi yapması gerekebilir, bazense hiç gerekmez.</li><li>Büyük bellek yığınlarını(heap) işlemek ve heap’in boyutu büyüdükçe ölçeklendirmek için tasarlanmıştır. Ölçeklenebilirliği artırdığı için yoğun bellek gerektiren uygulamalar için kullanılması çok daha avantajlı olur.</li><li>Eşzamanlı, çok iş parçacıklı ortamlarda iyi çalışacak şekilde tasarlanmıştır ve garbage collecting işleminin programın yürütülmesine müdahale etmeden diğer processlerle eş zamanlı olarak gerçekleşmesine olanak sağlar. Bu, diğer processleri bloke edebilen GC yapılarını kullanan diğer programlama dillerine göre çok önemli bir avantajdır.</li><li>CPU ve bellek kaynaklarını minimum seviyede kullanır, bu da onu daha verimli ve daha hızlı bir hale getirir.</li></ul><p>Son olarak küçük bir uygulama yardımıyla bazı bellek istatistiklerini görelim. Burada runtime paketi altındaki MemStats struct’ını kullanarak bu işlemleri yapacağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b65912f85e7236a5ff776c7fed746b8a/href">https://medium.com/media/b65912f85e7236a5ff776c7fed746b8a/href</a></iframe><p>Yukarıdaki kod bloğunda bir slice tanımladık ve iki kez boyutunu değiştirdik ve random tamsayılarla doldurduk. Her işlem sonrasında ise bellek istatistiklerini ekrana yazdırdık. Kodun çıktısına bakacak olursak;</p><pre>Size of slice: 0<br>Allocation: 114752<br>Total Allocation: 114752<br>Heap Allocation: 114752<br>NumGC: 0<br>------------------------<br>Size of slice: 1000000<br>Allocation: 8107488<br>Total Allocation: 8121504<br>Heap Allocation: 8107488<br>NumGC: 1<br>------------------------<br>Size of slice: 2000000<br>Allocation: 16111168<br>Total Allocation: 24129888<br>Heap Allocation: 16111168<br>NumGC: 2</pre><p>Burada yazdırdığımız istatistik değerleri için aşağıdaki tanımlamaları yapabiliriz;</p><ul><li>Alloc: Ayrılan ve halen kullanımda olan bellek miktarını byte olarak gösterir.</li><li>TotalAlloc: Program başladığı andan itibaren ayrılan kümülatif bellek miktarıdır.</li><li>HeapAlloc: Heap’te ayrılmış olan bellek miktarıdır.</li><li>NumGC: Çalışan GC döngülerinin sayısını belirtir.</li></ul><p>Çıktıyı inceleyecek olursak; ilk print işleminden sonra GC sayısı (NumGC) 0&#39;dır, yani henüz garbage collecting işlemi yapılmamıştır. For döngülerinden sonra yaptığımız print işlemlerinde NumGC değerleri sırasıyla 1 ve 2 geldi ve slice’ın boyutu arttıkça memory allocation, total memory allocation, heap allocation ve NumGC değerlerinin de arttığını görüyoruz.</p><p>Bu yazıda Garbage Collector nedir ve Go bu anlamda bize ne gibi avantajlar sunar bunları özetlemeye çalıştım. Daha detaylı bilgi almak adına <a href="https://tip.golang.org/doc/gc-guide">burayı</a> incelemenizi tavsiye ederim. Faydalı bir içerik olması dileğiyle, keyifli okumalar :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d33622eaece" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>