„Помош! Нашите трошоци за модел на АИ се преку покривот!“ Додека ChatGPT и неговите браќа и сестри предизвикаа златна брзина на апликации наменети за вештачка интелигенција, реалноста на градење апликации врз основа на LLMs е покомплексна од преземање на API повик на веб интерфејс. Секој ден, мојот LinkedIn прелистува со нови "AI-помогнати" производи. Некои анализираат правни документи, други пишуваат маркетиншки копии, а храбрите неколку дури и се обидуваат да го автоматизираат развојот на софтвер. Овие "компании за обложување" (како што понекогаш се нарекуваат непристојно) можеби не ги обучуваат сопствените модели, но многумина ги решаваат вистинските проблеми за клиентите и наоѓаат вистински производ-маркет соодветен врз основа на тековните барања од претпријатијата. But here's the thing: Even when you're not training models from scratch, scaling an AI application from proof-of-concept to production is like navigating a maze blindfolded. You've got to balance performance, reliability, and costs while keeping your users happy and your finance team from having a collective heart attack. За подобро да го разбереме, ајде да го скршиме ова со пример од реалниот свет. Замислете дека градиме „ResearchIt“ (не вистински производ, но носете со мене), апликација која им помага на истражувачите да дигестираат академски трудови. Сакате брз преглед на тој десен дел од методологијата? Треба да ги извлечете клучните наоди од 50-страничен документ? Version 1.0: The Naive Approach Верзија 1.0: The Naive Approach We're riding high on the OpenAI hype train - Our first version is beautifully simple: Истражувачот поставува парчиња од хартија (специфични, релевантни делови) Нашиот backend го пренесува текстот на GPT-5 со напомена како "Вие сте корисен истражувачки асистент. Анализирајте го следниот текст и испорачајте увид строго од делот обезбеден од корисникот..." Магијата се случува, а нашите корисници ги добиваат своите увид Едноставноста е убава.Цената?Не толку. As more researchers discover our tool, our monthly API bills are starting to look like phone numbers. The problem is that we’re sending every query to GPT-5, the Rolls-Royce of language models, when a Toyota Corolla would often do just fine. Yes, GPT-5 is powerful, with its 128k context window and strong reasoning abilities, but at $1.25 per 1M input tokens and $10 per 1M output tokens, costs add up fast. For simpler tasks like summarization or classification, smaller models such as GPT-5 mini (around 20% of the cost), GPT-5 nano (around 4%), or Gemini 2.5 Flash-Lite (around 5%) deliver great results at a fraction of the price. Open-source models like Meta’s LLaMA (3 or 4 series) or various models from Mistral or also offer flexible and cost-efficient options for general or domain-specific tasks, though fine-tuning them is often unnecessary for lighter workloads. Изборот навистина зависи од следниве работи: Output Quality: Can the model consistently deliver the accuracy your application needs? Does the model support the language that you want to work with? Response Speed: Will your users wait those extra milliseconds for better results? Typical response time for any app should be within the 10-second mark for users not to lose interest, so speed definitely matters. Data Integrity: How sensitive is your data, and what are your privacy requirements? Resource Constraints: What's your budget, both for costs and engineering time? За нашиот аналитичар на истражувачки труд, не ни е потребна поезија за квантната физика; ни е потребна сигурен, економичен сумирање. Bottom Line: Know Your Application Needs Bottom Line: Знајте ги вашите потреби за апликација Choose your LLM based on your actual requirements, not sheer power. If you need a quick setup, proprietary models may justify the cost. If affordability and flexibility matter more, open-source models are a strong choice, especially when small quality trade-offs are acceptable (although there might be some infrastructure overhead). Истражувачите го сакаат начинот на кој ги сумира густите академски трудови, а нашата корисничка база расте брзо. Но сега, тие сакаат повеќе; наместо само да ги сумираат деловите што ги испраќаат, тие сакаат флексибилност да поставуваат насочени прашања низ целата хартија на ефикасен начин. Звучи едноставно, нели? Само испратете го целиот документ на GPT-5 и нека работи својата магија. Не толку брзо. Академските статии се долги. Дури и со великодушниот 128K токен лимит на GPT-5, испраќањето на целосни документи по барање е скапо убивање. Плус, студиите покажаа дека како што должината на контекстот се зголемува, перформансите на LLM може да , which is detrimental when performing cutting-edge research. деградација деградација Значи, што е решението? Version 2.0: Smarter chunking and retrieval Version 2.0: Smarter chunking and retrieval The key question here is how do we scale to satisfy this requirement without setting our API bill on fire and also maintain accuracy in the system? **Answer is: \ На овој начин не треба да го испраќаме целиот документ секој пат до LLM за да ги зачуваме токените, туку исто така да се осигураме дека релевантните парчиња се преземаат како контекст за LLM да одговори користејќи го. Retrieval-Augmented Generation Retrieval-Augmented Generation There are 3 important aspects to consider here: Чункинг Складирање и Chunk Retrieval Рафинирање со користење на напредни техники за враќање. Чекор 1: Чункирање – Интелигентно поделба на документот Before we can retrieve relevant sections, we need to break the paper into manageable chunks. A naive approach might split text into fixed-size segments (say, every 500 words), but this risks losing context mid-thought. Imagine if one chunk ends with: "The experiment showed a 98% success rate in..." …and the next chunk starts with: "...reducing false positives in early-stage lung cancer detection." Neither chunk is useful in isolation. Instead, we need a semantic chunking strategy: : Use document structure (titles, abstracts, methodology, etc.) to create logical splits. Section-based chunking Преклопување на прозорецот: Преклопување на парчињата малку (на пример, преклопување со 200 токени) за да се зачува контекстот низ границите. : Dynamically adjust chunk sizes based on sentence boundaries and key topics. Adaptive chunking Section-based chunking Sliding window chunking Adaptive chunking Чекор 2: Интелигентно складирање и враќање Once your document chunks are ready, the next challenge is storing and retrieving them efficiently. With modern LLM applications handling millions of chunks, your storage choice directly impacts performance. Traditional approaches that separate storage and retrieval often fall short. Instead, the storage architecture should be designed with retrieval in mind, as different patterns offer distinct trade-offs for speed, scalability, and flexibility. Конвенционалното разликување на користењето на релациона база на податоци за структурирани податоци и NoSQL за неструктурирани податоци сè уште се применува, но со еден пресврт: LLM апликациите складираат не само текст, туку семантички претставувања (вградувања). In a traditional setup, document chunks and their embeddings might be stored in PostgreSQL or MongoDB. This works for small to medium-scale applications but has clear limitations as data and query volume grow. The challenge here isn't storage, it's the retrieval mechanism. Traditional databases excel at exact matches and range queries, but they weren't built for semantic similarity searches. You'd need to implement additional indexing strategies or use extensions like to enable vector similarity searches. This is where vector databases truly shine - they’re purpose-built for the store-and-retrieve pattern that LLM applications demand - treating embeddings as the primary attribute for querying, optimizing specifically for nearest neighbour searches. The real magic lies in how they handle similarity calculations. While traditional databases often require complex mathematical operations at query time, vector databases use specialized indexing structures such as (Hierarchical Navigable Small World) or Inverted File Index) to make similarity searches blazingly fast. pgvector HNSW ИВФ pgvector HNSW ИВФ Тие обично поддржуваат две примарни метрики за сличност: Euclidean Distance: Better suited when the absolute differences between vectors matter, particularly useful when embeddings encode hierarchical relationships. Cosine Similarity: Standard choice for semantic search - it focuses on the direction of vectors rather than magnitude. This means that two documents with similar meanings but different lengths can still be matched effectively. Изборот на вистинската векторска база на податоци е од клучно значење за оптимизирање на перформансите за пребарување во апликациите на LLM, бидејќи влијае на скалабилност, ефикасност на прашањата и оперативната комплексност. and offer fast ANN search with efficient recall - they handle scaling automatically making them ideal for dynamic workloads with minimal operational overhead. Self-hosted options like (IVF-based) offer more control and cost-effectiveness at scale, but require careful tuning. pgvector integrated with Postgres enables hybrid search, though it may hit limits under high-throughput workloads. The choice finally depends on workload size, query patterns, and operational constraints. Пинекони Weaviate Milvus Пинекони Weaviate Milvus Step 3: Advanced Retrieval Strategies Изградбата на ефикасен систем за пребарување бара повеќе од само водење на основно пребарување за сличност на векторите. Додека густите вградувања овозможуваат моќно семантичко споделување, реалните апликации често бараат дополнителни слоеви на рафинирање за да се подобри точноста, релевантноста и ефикасноста. Пребарувањето врз основа на клучни зборови (на пример, BM25, TF-IDF) е одлично за наоѓање точни термини, но се бори со семантичко разбирање. Од друга страна, векторското пребарување (на пример, FAISS, HNSW или IVFFlat) се одликува во фаќањето семантички односи, но понекогаш може да врати лошо поврзани резултати кои пропуштаат клучни клучни зборови. За да се надмине ова, хибридната стратегија за враќање ги комбинира силните страни на двата метода. This involves: Пребарување на кандидати – извршување на пребарување за сличност на клучни зборови и вектори паралелно. Резултати за спојување – контрола на влијанието на секој метод за пребарување врз основа на типот на прашањето и потребите на апликацијата. Повторно рангирање за оптимално рангирање – обезбедување на најрелевантните информации да се појават на врвот врз основа на семантичките барања. Друг предизвик е дека традиционалното пребарување на векторите ги презема најблиските вградувања на врвот К. LLM се потпираат на контекстните прозорци, што значи дека слепото избирање на резултатите од врвот К може да внесе неважни информации или да пропушти клучни детали. Едно решение за овој проблем е да се користи самиот LLM за рафинирање. Поконкретно, ги испраќаме пребараните кандидати до LLM за да ја провериме кохерентноста и релевантноста врз основа на прашањето на корисникот. Некои техники кои се користат за LLM рафинирање се како што следува: : Instead of feeding raw top-K results, the LLM evaluates whether the retrieved documents follow a logical progression related to the query. By ranking passages for semantic cohesion, only the most contextually relevant information is used. Semantic Coherence Filtering Модели како што се Cohere Rerank, BGE или MonoT5 можат повторно да ги проценат добиените документи, зафаќајќи фини обрасци на релевантност и подобрување на резултатите надвор од суровите резултати за сличност. Проширување на контекстот со итеративно враќање: Статичкото враќање може да пропушти индиректно релевантни информации. LLMs можат да идентификуваат празнини, да генерираат барања за следење и динамички да ја прилагодат стратегијата за враќање за да ги соберат недостасува контекст. Semantic Coherence Filtering Relevance-Based Reranking Context Expansion with Iterative Retrieval Сега, со овие ажурирања, нашиот систем е подобро опремен за справување со комплексни прашања во повеќе делови од хартија, додека одржувањето на точноста со темелирање на одговорите строго во обезбедената содржина. но што се случува кога еден извор не е доволен? Version 3.0 - Building a Comprehensive and Reliable System Version 3.0 - Building a Comprehensive and Reliable System By this point, “ResearchIt” has matured from a simple question-answering system into a capable research assistant that extracts key sections from uploaded papers, highlights methods, and summarises technical content with precision. Yet, as users push the system further, new expectations emerge. What began as a system designed to summarize or interpret a single paper has now become a tool researchers want to use for deep, cross-domain reasoning. Researchers want it to reason across multiple sources, not just read one paper at a time. Новиот бран на прашања изгледа како: “Which optimization techniques for transformers demonstrate the best efficiency improvements when combining insights from benchmarks, open-source implementations, and recent research papers?” "Како резултатите од компресијата на моделите пријавени во овој документ се усогласуваат со перформансите објавени во други документи или бенчмаркови податоци?" Тие веќе не се едноставни задачи за враќање. - the ability to integrate and interpret complex information, plan and adapt, use tools effectively, recover from errors, and produce grounded, evidence-based synthesis. multi-source reasoning Despite its strong comprehension abilities, “ResearchIt” 2.0 struggles with two major limitations when reasoning across diverse information sources: Cross-Sectional Analysis: When answers require both interpretation and computation (e.g., extracting FLOPs or accuracy from tables and comparing them across conditions). The model must not only extract numbers but also understand context and significance. Крос-изворна синтеза: Кога релевантните податоци живеат низ повеќе системи - PDFs, експериментални дневници, GitHub repos, или структурирани CSVs - и моделот мора да го координира пребарувањето, да ги спои конфликтните наоди и да произведе едно кохерентно објаснување. These issues aren’t just theoretical. They reflect real-world challenges in AI scalability. As data ecosystems grow more complex, organizations need to move beyond basic retrieval toward reasoned orchestration - systems that can plan, act, evaluate, and continuously adapt. Да го земеме првото прашање околу анализата на техниката за оптимизација на трансформаторите - како би го решиле овој проблем како луѓе? A group of researchers or students would work on “literature review, i.e, collating papers on the topics, researching open source github repos, and identifying benchmark datasets. They would then extract data and metrics like FLOPs, latency, accuracy from these resources, normalize and compute aggregations and validate the results produced. This is not a one-shot process; it’s iterative, involving multiple rounds of refinement, data validation, and synthesis, after which an aggregated summary of verified results would be generated. So, what exactly did we do here? Разделете го општото прашање на помали, фокусирани подпроблеми - кои извори да ги пребарувате, кои метрики да ги анализирате и како треба да се извршат споредби. Consult domain experts or trusted sources to fill knowledge gaps, cross-verify metrics, and interpret trade-offs. Конечно, синтетизирајте ги увидоците во кохезивен, доказен заклучок, споредувајќи ги резултатите и истакнувајќи конзистентни или влијателни наоди преку итерации. Ова е, во суштина, размислена оркестрација - координираниот процес на планирање, собирање, анализирање и синтезирање на информации низ повеќе системи и перспективи. Чекор 1: Верига на размислување / планирање To tackle the first aspect, the ability to reason through multiple steps before answering, the concept of CoT им овозможува на моделите да планираат пред извршување, предизвикувајќи структурирано размислување кое ја подобрува нивната интерпретабилност и конзистентност.На пример, при анализирање на техники за оптимизација на трансформатори, моделот CoT прво ќе го опише својот начин на размислување - дефинирајќи го опсегот (обука за ефикасност / модел перформанси / скалабилност), идентификувајќи ги релевантните извори, избирајќи ги критериумите за проценка и методот за споредба и воспоставување на секвенца на извршување. Chain of Thought Chain of Thought This structured reasoning approach became the foundation for LangChain-based orchestrations. As questions grew more complex, a single “chain” of reasoning evolved into Tree of Thought (ToT) or Graph of Thought (GoT) approaches - enabling branched reasoning and “thinking ahead” behaviors, where models explore multiple possible solution paths before converging on the best one. These techniques underpin today’s “thinking models,” trained on CoT datasets to generate interpretable reasoning tokens that reveal how the model arrived at a conclusion. Се разбира, усвојувањето на овие модели тешки за размислување воведува практични размислувања - првенствено, трошоци. Closed-source models like OpenAI’s o3 and o4-mini, which offer high reasoning quality and strong orchestration capabilities. Алтернативи со отворен код како DeepSeek-R1, кои обезбедуваат транспарентно размислување со поголема флексибилност / инженеринг напор за прилагодување. Додека не-мислење LLMs (како LLaMA 3) се уште може да го имитира размислување преку CoT поттикнување, вистински CoT или ToT модели инхерентно извршуваат структурирано размислување natively. Step 2: Multi-source workflows- Function Calling to Agents Breaking down complex problems into logical steps is only half the battle. The system must then coordinate across different specialized tools - each acting as an "expert" - to answer sub-questions, execute tasks, gather data, and refine its understanding through iterative interaction with its environment. OpenAI introduced as the first step to address this situation. Function calling/ tools gave the LLMs its first real ability to rather than simply predict text. You provide the model with a toolkit - for example, functions like or and the model decides which one to call, when to call it, and in what order. Let’s take a simple example: Функција на повик take action екстракт_таблица(), екстракт_таблица(), Статистичка статистика ( Функција на повик Task: “Compute the average reported accuracy for BERT fine-tuning.” Моделот кој користи функција повик може да одговори со извршување на линеарна синџир како ова: search_papers("BERT прецизност на фино прилагодување") extract_table() for each paper calculate_statistics() to compute the mean This dummy example of a simple deterministic pipeline where an LLM and a set of tools are orchestrated through predefined code paths is straightforward and effective and can often serve the purpose for a variety of use cases. However, it’s and . When more complexity is warranted, an може да биде подобра опција кога се потребни флексибилност, подобри перформанси на задачите и донесување на одлуки врз основа на модели (со компромис на латенцијата и трошоците). linear non-adaptive agentic workflow agentic workflow Iterative agentic workflows are systems that don’t just execute once but . Like a human researcher, the model learns to recheck its steps, refine its queries, and reconcile conflicting data before drawing conclusions. Рефлектирај, ревидирај и повторно трчај Размислете за тоа како добро координирана истражувачка лабораторија, каде што секој член игра посебна улога: Retrieval Agent: The information scout. It expands the initial query, runs both semantic and keyword searches across research papers, APIs, github repos, and structured datasets, ensuring that no relevant source is overlooked. Екстракција агент: на податоци wrangler. Тоа анализира PDFs, табели и JSON излези, а потоа стандардизира извлечените податоци - нормализирање на метриките, помирување на единици, и подготовка на чисти влезови за анализа надолу. Computation Agent: The analyst. It performs the necessary calculations, statistical tests, and consistency checks to quantify trends and verify that the extracted data makes sense. Агент за валидација: Заштитник на квалитетот. Тој ги идентификува аномалиите, недостасувачките записи или конфликтните наоди, и ако нешто изгледа надвор, автоматски предизвикува повторно извршување или дополнителни пребарувања за да ги пополни празнините. Synthesis Agent: The integrator. It pulls together all verified insights and composes the final evidence-backed summary or report. Секој од нив може да побара разјаснувања, да ги рестартира анализите или да предизвика нови пребарувања кога контекстот е нецелосен, во суштина формирајќи лак за само-корекција - еволутивен дијалог меѓу специјализирани системи за размислување кои го одразуваат начинот на кој работат вистинските истражувачки тимови. Да го преведеме ова во поконкретен пример за тоа како овие агенси би влегле во игра за нашето прашање за ефикасноста на трансформаторите: Initial Planning (Reasoning LLM): The orchestrator begins by breaking the task into sub-objectives discussed before. First Retrieval Loop: The Retrieval Agent executes the plan by gathering candidate materials — academic papers, MLPerf benchmark results, and open-source repositories related to transformer optimization. During this step, it detects that two benchmark results reference outdated datasets and flags them for review, prompting the orchestrator to mark those as lower confidence. Extraction & Computation Loop: Next, the Extraction Agent processes the retrieved documents, parsing FLOPs and latency metrics from tables and converting inconsistent units (e.g., TFLOPs vs GFLOPs) into a standardized format. The cleaned dataset is then passed to the Computation Agent, which calculates aggregated improvements across optimization techniques. Meanwhile, the Validation Agent identifies an anomaly - an unusually high accuracy score from one repository. It initiates a follow-up query and discovers the result was computed on a smaller test subset. This correction is fed back to the orchestrator, which dynamically revises the reasoning plan to account for the new context. Iterative Refinement: Following the Validation Agent’s discovery that the smaller test set introduced inconsistencies in the reported results - the Retrieval Agent initiates a secondary, targeted search to gather additional benchmark data and papers on quantization techniques. The goal is to fill missing entries, verify reported accuracy-loss trade-offs, and ensure comparable evaluation settings across sources. The Extraction and Computation Agents then process this newly retrieved data, recalculating averages and confidence intervals for all optimization methods. An optional Citation Agent could examine citation frequency and publication timelines to identify which techniques are gaining traction in recent research. Final Synthesis: Once all agents agree, the orchestrator compiles a verified, grounded summary like - “ ” Across 14 evaluated studies, structured pruning yields 40–60 % FLOPs reduction with < 2 % accuracy loss (Chen 2023; Liu 2024). Quantization maintains ≈ 99 % accuracy while reducing memory by 75 % (Park 2024). Efficient-attention techniques achieve linear-time scaling (Wang 2024) with only minor degradation on long-context tasks (Zhao 2024). Recent citation trends show a 3× rise in attention-based optimization research since 2023, suggesting a growing consensus toward hybrid pruning + linear-attention approaches. What’s powerful here isn’t just the end result - it’s the . Процесот Each agent contributes, challenges, and refines the others’ work until a stable, multi-source conclusion emerges. In this orchestration framework, interoperability is powered by the и MCP стандардизира како моделите и алатките разменуваат структурирани информации - како што се добиени документи, анализирани табели или пресметени резултати - обезбедувајќи дека секој агент може да ги разбере и изгради врз резултатите на другите. Дополнувајќи го ова, A2A комуникацијата им овозможува на агентите директно да се координираат едни со други - споделување на интермедиумски состојби на размислување, барање појаснувања или активирање на акција за следење без интервенција. Model Context Protocol (MCP) Agent-to-Agent (A2A) Model Context Protocol (MCP) Agent-to-Agent (A2A) Чекор 3: Обезбедување на основаност и сигурност Во оваа фаза, сега имате агентски систем кој е способен да ги распадне релативно сложените и апстрактните истражувачки прашања во логички чекори, да собира податоци од повеќе извори, да врши пресметки или трансформации каде што е потребно, и да ги собере резултатите во кохерентен, докази поддржани резиме. facts - they predict the next most likely token based on patterns in their training data. That means their output is fluent and convincing, but not always . While improved datasets and training objectives help, the real safeguard comes from adding mechanisms that can verify and correct what the model produces in real time. know правилно Here are a few techniques that make this possible: Rule-Based Filtering: Define domain-specific rules or patterns that catch obvious errors before they reach the user. For example, if a model outputs an impossible metric, a missing data field, or a malformed document ID, the system can flag and regenerate it. Автоматски повторно пребарување на доверливи API, структурирани бази на податоци или бенчмаркови за да се потврдат клучните броеви и факти.Ако моделот вели "структурирано намалување ги намалува FLOPs за 50%", системот го пребарува тоа против бенчмаркови податоци пред да го прифати. Self-Consistency Checks: Generate multiple reasoning passes and compare them. Hallucinated details tend to vary between runs, while factual results remain stable - so the model keeps only the majority-consistent conclusions. Заедно, овие слоеви ја сочинуваат конечната гаранција – затворање на лукот на размислување.Секој одговор кој системот го произведува не е само добро структуриран, туку . verified И еве - она што започна како едноставен модел базиран на пребарување сега еволуираше во силен истражувачки асистент: оној кој не само што одговара на основни прашања и прашања, туку и се занимава со длабоки аналитички прашања со интегрирање на податоци од повеќе извори, извршување на пресметки и производство на заземени увид, додека активно се брани против халуцинации и дезинформации.