<?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 Mihai Nitulescu on Medium]]></title>
        <description><![CDATA[Stories by Mihai Nitulescu on Medium]]></description>
        <link>https://medium.com/@mieitza?source=rss-13b76a05877b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3n47efJu75atrLHklShZUA.jpeg</url>
            <title>Stories by Mihai Nitulescu on Medium</title>
            <link>https://medium.com/@mieitza?source=rss-13b76a05877b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:19:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mieitza/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[How to Implement a Novel Transformer Architecture From Scratch]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mieitza/how-to-implement-a-novel-transformer-architecture-from-scratch-1e44007feebb?source=rss-13b76a05877b------2"><img src="https://cdn-images-1.medium.com/max/1868/1*Op_FSvyo5WoJrzLCTmhtwQ.png" width="1868"></a></p><p class="medium-feed-snippet">The playbook I wish I&#x2019;d had on day one, extracted from a real debugging session and written up as something the next person can actually&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@mieitza/how-to-implement-a-novel-transformer-architecture-from-scratch-1e44007feebb?source=rss-13b76a05877b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mieitza/how-to-implement-a-novel-transformer-architecture-from-scratch-1e44007feebb?source=rss-13b76a05877b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e44007feebb</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[gemma-4]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mihai Nitulescu]]></dc:creator>
            <pubDate>Sat, 23 May 2026 08:22:44 GMT</pubDate>
            <atom:updated>2026-05-23T08:22:44.298Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building a Gemma 4 Inference Engine in Rust: Three Bugs That Took 11 Hours to Find]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@mieitza/building-a-gemma-4-inference-engine-in-rust-three-bugs-that-took-11-hours-to-find-fed899e36660?source=rss-13b76a05877b------2"><img src="https://cdn-images-1.medium.com/max/2000/1*JeT63nM2DkKyVkTwAA8Rhw.png" width="2000"></a></p><p class="medium-feed-snippet">How I built a single binary that runs Google&#x2019;s Gemma 4 models locally with an OpenAI-compatible API &#x2014; and the three architectural&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@mieitza/building-a-gemma-4-inference-engine-in-rust-three-bugs-that-took-11-hours-to-find-fed899e36660?source=rss-13b76a05877b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@mieitza/building-a-gemma-4-inference-engine-in-rust-three-bugs-that-took-11-hours-to-find-fed899e36660?source=rss-13b76a05877b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed899e36660</guid>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gemma-4]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Mihai Nitulescu]]></dc:creator>
            <pubDate>Fri, 22 May 2026 11:06:35 GMT</pubDate>
            <atom:updated>2026-05-23T09:46:43.891Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Self-Contained SOC/IR Agent (with Human-in-the-Loop + Phishing Playbook)]]></title>
            <link>https://medium.com/@mieitza/a-self-contained-soc-ir-agent-with-human-in-the-loop-phishing-playbook-7728190c4b53?source=rss-13b76a05877b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7728190c4b53</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[incident-response]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Mihai Nitulescu]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 06:38:02 GMT</pubDate>
            <atom:updated>2025-11-17T06:38:02.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l04CnfJjTbDcCbKvVtAmEQ.png" /></figure><p>Want an AI assistant that actually <em>runs</em> your SOC/IR playbooks — <em>but</em> never isolates a host or blocks an IOC without a human green-light? This article gives you a <strong>fully self-contained</strong> (copy-paste) template based on the multi-agent deep-dive we built earlier, tailored for <strong>Security Operations &amp; Incident Response</strong>:</p><ul><li>Action tools for SIEM, TheHive/Cortex, EDR, IAM, Firewall, Slack, Jira</li><li><strong>Human-review node</strong> that <strong>pauses</strong> and asks for approval before any non-dry-run action</li><li>A <strong>YAML Phishing playbook</strong> that the planner consumes to generate step-by-step actions</li><li>One file, runnable end-to-end</li></ul><blockquote><em>The integrations below are safe stubs. Swap them with your real APIs (Splunk/Elastic, TheHive/Cortex, CrowdStrike/Defender, Palo/Forti, Okta/Entra, Slack/Jira). The dangerous tools </em><strong><em>require approval</em></strong><em>.</em></blockquote><h3>Setup</h3><pre>python -m venv venv &amp;&amp; source venv/bin/activate<br>pip install -U langgraph langchain langchain-openai \<br>  sentence-transformers faiss-cpu pyyaml<br># Optional: use OpenAI (or swap to local models via Ollama/vLLM)<br>export OPENAI_API_KEY=sk-...</pre><h3>1) The one-file agent</h3><p>Create a file soc_ir_agent.py and paste everything below.</p><blockquote><em>It uses a light model for planning and a heavier one for final answers. Replace with your provider/models as needed.</em></blockquote><pre># soc_ir_agent.py<br># A self-contained SOC/IR agent with Human Review and a Phishing playbook.<br><br>import re, json, time, yaml<br>from typing import Annotated, Dict, Any, List, Literal<br>import operator<br><br># ------------------------------ Models --------------------------------------<br>from langchain_openai import ChatOpenAI<br><br>def light_llm():<br>    return ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br><br>def heavy_llm():<br>    return ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)<br><br># ------------------------------ State ---------------------------------------<br>from langchain_core.messages import AnyMessage, SystemMessage, AIMessage, HumanMessage<br><br>class State(dict):<br>    messages: Annotated[List[AnyMessage], operator.add]<br>    active: Literal[&quot;guard&quot;,&quot;plan&quot;,&quot;act&quot;,&quot;human_review&quot;,&quot;final&quot;]<br>    bag: Dict[str, Any]       # structured memory: case_id, iocs, pending_actions, approvals, etc.<br><br>def _ok(msg, **kw): return json.dumps({&quot;ok&quot;: True, &quot;msg&quot;: msg, **kw})<br>def _err(msg, **kw): return json.dumps({&quot;ok&quot;: False, &quot;error&quot;: msg, **kw})<br><br># ------------------------------ Tools (SAFE STUBS) --------------------------<br>from langchain_core.tools import tool<br><br>@tool<br>def siem_search(query: str, window: str=&quot;last_24h&quot;, index: str=&quot;main&quot;, dry_run: bool=True) -&gt; str:<br>    samples = [{&quot;@ts&quot;: time.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;), &quot;host&quot;: &quot;ws-104&quot;, &quot;user&quot;: &quot;cfo&quot;, &quot;src&quot;: &quot;185.71.67.5&quot;}]<br>    return _ok(&quot;siem_search&quot;, hits=len(samples), query=query, window=window, index=index, samples=samples, dry_run=dry_run)<br><br>@tool<br>def enrich_ip(ip: str) -&gt; str:<br>    intel = {&quot;ip&quot;: ip, &quot;score&quot;: &quot;suspicious&quot; if ip.startswith((&quot;185.&quot;,&quot;45.&quot;)) else &quot;unknown&quot;, &quot;sources&quot;: [&quot;abuse.ch&quot;]}<br>    return _ok(&quot;enrich_ip&quot;, intel=intel)<br><br>@tool<br>def enrich_domain(domain: str) -&gt; str:<br>    intel = {&quot;domain&quot;: domain, &quot;score&quot;: &quot;malicious&quot; if domain.endswith(&quot;.ru&quot;) else &quot;unknown&quot;}<br>    return _ok(&quot;enrich_domain&quot;, intel=intel)<br><br>@tool<br>def enrich_hash(sha256: str) -&gt; str:<br>    intel = {&quot;sha256&quot;: sha256, &quot;score&quot;: &quot;malicious&quot;, &quot;family&quot;: &quot;AgentTesla&quot;}<br>    return _ok(&quot;enrich_hash&quot;, intel=intel)<br><br>@tool<br>def hive_create_case(title: str, severity: Literal[1,2,3,4], tlp: Literal[0,1,2,3],<br>                     tags: List[str], description: str, dry_run: bool=True) -&gt; str:<br>    case_id = &quot;CASE-&quot; + str(int(time.time()))<br>    return _ok(&quot;hive_create_case&quot;, case_id=case_id, dry_run=dry_run)<br><br>@tool<br>def hive_add_observable(case_id: str, type: str, value: str, tags: List[str] | None=None,<br>                        dry_run: bool=True) -&gt; str:<br>    obs_id = &quot;OBS-&quot; + str(int(time.time()))<br>    return _ok(&quot;hive_add_observable&quot;, case_id=case_id, observable_id=obs_id, type=type, value=value, tags=tags or [], dry_run=dry_run)<br><br>@tool<br>def cortex_run_analyzer(case_id: str, observable_id: str, analyzer: str, dry_run: bool=True) -&gt; str:<br>    rep_id = &quot;REP-&quot; + str(int(time.time()))<br>    return _ok(&quot;cortex_run_analyzer&quot;, case_id=case_id, observable_id=observable_id, analyzer=analyzer, report_id=rep_id, dry_run=dry_run)<br><br># --- DESTRUCTIVE (require approval when dry_run=False) ----------------------<br>DESTRUCTIVE = {&quot;edr_isolate_host&quot;,&quot;iam_disable_user&quot;,&quot;fw_block_ioc&quot;}<br><br>@tool<br>def edr_isolate_host(hostname: str, reason: str, dry_run: bool=True) -&gt; str:<br>    return _ok(&quot;edr_isolate_host&quot;, hostname=hostname, reason=reason, dry_run=dry_run)<br><br>@tool<br>def iam_disable_user(username: str, reason: str, dry_run: bool=True) -&gt; str:<br>    return _ok(&quot;iam_disable_user&quot;, username=username, reason=reason, dry_run=dry_run)<br><br>@tool<br>def fw_block_ioc(ioc_type: Literal[&quot;ip&quot;,&quot;domain&quot;,&quot;url&quot;,&quot;sha256&quot;], value: str,<br>                 duration: str=&quot;24h&quot;, ticket: str | None=None, dry_run: bool=True) -&gt; str:<br>    return _ok(&quot;fw_block_ioc&quot;, ioc_type=ioc_type, value=value, duration=duration, ticket=ticket, dry_run=dry_run)<br><br>@tool<br>def slack_notify(channel: str, message: str) -&gt; str:<br>    return _ok(&quot;slack_notify&quot;, channel=channel, preview=message[:160])<br><br>@tool<br>def jira_open(project: str, summary: str, description: str, priority: str=&quot;P2&quot;, dry_run: bool=True) -&gt; str:<br>    key = f&quot;{project}-{int(time.time())%10000}&quot;<br>    return _ok(&quot;jira_open&quot;, key=key, priority=priority, dry_run=dry_run)<br><br>TOOLS = {t.name: t for t in [<br>    siem_search, enrich_ip, enrich_domain, enrich_hash,<br>    hive_create_case, hive_add_observable, cortex_run_analyzer,<br>    edr_isolate_host, iam_disable_user, fw_block_ioc,<br>    slack_notify, jira_open<br>]}<br><br># ------------------------------ Phishing Playbook (YAML) --------------------<br>PHISHING_YAML = &quot;&quot;&quot;<br>name: phishing<br>defaults:<br>  severity: 3         # 1 low .. 4 critical<br>  tlp: 2              # TLP:Amber<br>  slack_channel: &quot;#soc-ops&quot;<br>  url_analyzer: &quot;URLHaus&quot;<br>destructive_tools: [fw_block_ioc, iam_disable_user, edr_isolate_host]<br>stages:<br>  - ingest<br>  - enrich<br>  - analyze<br>  - notify<br>  - contain<br>&quot;&quot;&quot;<br><br>PLAYBOOK = yaml.safe_load(PHISHING_YAML)<br><br># ------------------------------ Helpers -------------------------------------<br>IOC_PATTERNS = {<br>    &quot;ip&quot;: re.compile(r&quot;\b(?:\d{1,3}\.){3}\d{1,3}\b&quot;),<br>    &quot;domain&quot;: re.compile(r&quot;\b([a-z0-9-]+\.)+[a-z]{2,}\b&quot;),<br>    &quot;sha256&quot;: re.compile(r&quot;\b[a-f0-9]{64}\b&quot;),<br>    &quot;url&quot;: re.compile(r&quot;\bhttps?://[^\s]+&quot;, re.I),<br>}<br><br>def extract_iocs(text: str):<br>    out = []<br>    for t, pat in IOC_PATTERNS.items():<br>        for m in pat.findall(text):<br>            # avoid counting IP-looking domains<br>            if t==&quot;domain&quot; and IOC_PATTERNS[&quot;ip&quot;].match(m):<br>                continue<br>            out.append({&quot;type&quot;: t, &quot;value&quot;: m})<br>    # de-dup<br>    uniq = {(d[&quot;type&quot;], d[&quot;value&quot;]) for d in out}<br>    return [{&quot;type&quot;: t, &quot;value&quot;: v} for t,v in uniq]<br><br># ------------------------------ Nodes ---------------------------------------<br># 1) Guard (policy + triage)<br>GUARD_SYS = &quot;&quot;&quot;You are a SOC guard. If the content is clearly illegal/harmful, respond with &#39;REFUSE&#39;.<br>Else summarize the request in one short sentence.&quot;&quot;&quot;<br>def guard_node(state: State) -&gt; State:<br>    llm = light_llm()<br>    out = llm.invoke([SystemMessage(content=GUARD_SYS)] + state[&quot;messages&quot;]).content<br>    if &quot;REFUSE&quot; in out:<br>        return {&quot;messages&quot;:[AIMessage(content=&quot;Sorry, I can’t help with that.&quot;)], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;final&quot;}<br>    state[&quot;bag&quot;][&quot;summary&quot;] = out<br>    state[&quot;active&quot;] = &quot;plan&quot;<br>    return {&quot;messages&quot;: [], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;: &quot;plan&quot;}<br><br># 2) Planner uses the YAML playbook to create steps with TOOL(...) calls<br>def plan_node(state: State) -&gt; State:<br>    last_user = next(m for m in reversed(state[&quot;messages&quot;]) if m.type==&quot;human&quot;)<br>    iocs = extract_iocs(last_user.content)<br>    state[&quot;bag&quot;][&quot;iocs&quot;] = iocs<br><br>    sev, tlp = PLAYBOOK[&quot;defaults&quot;][&quot;severity&quot;], PLAYBOOK[&quot;defaults&quot;][&quot;tlp&quot;]<br>    chan, analyzer = PLAYBOOK[&quot;defaults&quot;][&quot;slack_channel&quot;], PLAYBOOK[&quot;defaults&quot;][&quot;url_analyzer&quot;]<br><br>    steps = []<br>    steps.append(f&#39;NOTE: Extracted {len(iocs)} IOC(s): {iocs}&#39;)<br>    steps.append(f&#39;TOOL(name=&quot;hive_create_case&quot;, args={{&quot;title&quot;:&quot;Phishing investigation&quot;,&quot;severity&quot;:{sev},&quot;tlp&quot;:{tlp},&quot;tags&quot;:[&quot;phishing&quot;,&quot;auto&quot;],&quot;description&quot;:&quot;{state[&quot;bag&quot;][&quot;summary&quot;]}&quot;}})&#39;)<br>    # we don&#39;t know case_id yet; executer will capture from tool response and reuse<br><br>    for i in iocs:<br>        if i[&quot;type&quot;] in {&quot;ip&quot;,&quot;domain&quot;,&quot;url&quot;,&quot;sha256&quot;}:<br>            steps.append(f&#39;TOOL(name=&quot;hive_add_observable&quot;, args={{&quot;case_id&quot;:&quot;${{case_id}}&quot;,&quot;type&quot;:&quot;{i[&quot;type&quot;]}&quot;,&quot;value&quot;:&quot;{i[&quot;value&quot;]}&quot;,&quot;tags&quot;:[&quot;auto&quot;]}})&#39;)<br>    for i in iocs:<br>        if i[&quot;type&quot;]==&quot;ip&quot;:<br>            steps.append(f&#39;TOOL(name=&quot;enrich_ip&quot;, args={{&quot;ip&quot;:&quot;{i[&quot;value&quot;]}&quot;}})&#39;)<br>        if i[&quot;type&quot;]==&quot;domain&quot;:<br>            steps.append(f&#39;TOOL(name=&quot;enrich_domain&quot;, args={{&quot;domain&quot;:&quot;{i[&quot;value&quot;]}&quot;}})&#39;)<br>        if i[&quot;type&quot;]==&quot;sha256&quot;:<br>            steps.append(f&#39;TOOL(name=&quot;enrich_hash&quot;, args={{&quot;sha256&quot;:&quot;{i[&quot;value&quot;]}&quot;}})&#39;)<br>        if i[&quot;type&quot;]==&quot;url&quot;:<br>            # Analyzer needs observable id but we&#39;ll just log analysis in stub<br>            steps.append(f&#39;TOOL(name=&quot;cortex_run_analyzer&quot;, args={{&quot;case_id&quot;:&quot;${{case_id}}&quot;,&quot;observable_id&quot;:&quot;${{last_obs}}&quot;,&quot;analyzer&quot;:&quot;{analyzer}&quot;}})&#39;)<br><br>    steps.append(f&#39;TOOL(name=&quot;slack_notify&quot;, args={{&quot;channel&quot;:&quot;{chan}&quot;,&quot;message&quot;:&quot;Phishing triage started with ${{case_id}} and {len(iocs)} IOC(s).&quot; }})&#39;)<br><br>    # Propose containment (non-dry-run -&gt; requires approval)<br>    for i in iocs:<br>        if i[&quot;type&quot;] in {&quot;ip&quot;,&quot;domain&quot;}:<br>            steps.append(f&#39;TOOL(name=&quot;fw_block_ioc&quot;, args={{&quot;ioc_type&quot;:&quot;{i[&quot;type&quot;]}&quot;,&quot;value&quot;:&quot;{i[&quot;value&quot;]}&quot;,&quot;duration&quot;:&quot;24h&quot;,&quot;ticket&quot;:&quot;${{case_id}}&quot;,&quot;dry_run&quot;:false}})&#39;)<br>    steps.append(&#39;NOTE: If a compromised user or host identified, propose disabling user and isolating host (dry_run=false).&#39;)<br>    steps.append(&#39;TOOL(name=&quot;iam_disable_user&quot;, args={&quot;username&quot;:&quot;cfo&quot;,&quot;reason&quot;:&quot;Impossible travel; suspected compromise&quot;,&quot;dry_run&quot;:false})&#39;)<br>    steps.append(&#39;TOOL(name=&quot;edr_isolate_host&quot;, args={&quot;hostname&quot;:&quot;ws-104&quot;,&quot;reason&quot;:&quot;Containment - suspected compromise&quot;,&quot;dry_run&quot;:false})&#39;)<br><br>    y = {&quot;steps&quot;: steps, &quot;Notes&quot;: &quot;Generated from phishing playbook&quot;}<br>    plan_yaml = yaml.safe_dump(y, sort_keys=False)<br>    state[&quot;bag&quot;][&quot;plan_yaml&quot;] = plan_yaml<br>    state[&quot;active&quot;] = &quot;act&quot;<br>    return {&quot;messages&quot;:[AIMessage(content=f&quot;Planned steps:\n```yaml\n{plan_yaml}\n```&quot;)], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;act&quot;}<br><br># 3) Human review node (approvals)<br>REVIEW_PROMPT = &quot;&quot;&quot;The following non-dry-run actions require approval:<br>{actions}<br><br>Reply with one of:<br>- &quot;approve all&quot;<br>- &quot;approve: fw_block_ioc, edr_isolate_host&quot;<br>- &quot;deny all&quot;<br>- or a short explanation.<br>&quot;&quot;&quot;<br><br>def human_review_node(state: State) -&gt; State:<br>    # parse the latest human reply to update approvals<br>    last = next((m for m in reversed(state[&quot;messages&quot;]) if m.type==&quot;human&quot;), None)<br>    pending = state[&quot;bag&quot;].get(&quot;pending_actions&quot;, [])<br>    allowed = set(state[&quot;bag&quot;].get(&quot;allowed_actions&quot;, []))<br><br>    if last and &quot;approve all&quot; in last.content.lower():<br>        state[&quot;bag&quot;][&quot;approval_token&quot;] = &quot;approved&quot;<br>        allowed = {&quot;*&quot;}<br>    elif last and &quot;deny&quot; in last.content.lower():<br>        state[&quot;bag&quot;][&quot;approval_token&quot;] = None<br>        allowed = set()<br>        state[&quot;bag&quot;][&quot;pending_actions&quot;] = []  # clear<br>        return {&quot;messages&quot;:[AIMessage(content=&quot;Denied. No destructive actions will be executed.&quot;)],<br>                &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;final&quot;}<br>    elif last and &quot;approve:&quot; in last.content.lower():<br>        items = re.findall(r&quot;approve:\s*(.*)&quot;, last.content, flags=re.I)<br>        if items:<br>            names = [n.strip() for n in items[0].split(&quot;,&quot;)]<br>            allowed.update(names)<br>            state[&quot;bag&quot;][&quot;approval_token&quot;] = &quot;approved-partial&quot;<br><br>    state[&quot;bag&quot;][&quot;allowed_actions&quot;] = list(allowed)<br><br>    # if user just arrived here, ask for approval<br>    if pending:<br>        listing = &quot;\n&quot;.join(f&quot;- {p}&quot; for p in pending)<br>        msg = REVIEW_PROMPT.format(actions=listing)<br>        return {&quot;messages&quot;:[AIMessage(content=msg)], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;human_review&quot;}<br><br>    # if no more pending, resume acting<br>    return {&quot;messages&quot;:[], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;act&quot;}<br><br># 4) Executor (runs tools; pauses for approval when needed)<br>TOOL_RE = re.compile(r&#39;TOOL\(name=&quot;(?P&lt;name&gt;[^&quot;]+)&quot;,\s*args=(?P&lt;args&gt;.+)\)&#39;)<br><br>def act_node(state: State) -&gt; State:<br>    y = yaml.safe_load(state[&quot;bag&quot;][&quot;plan_yaml&quot;]) or {&quot;steps&quot;:[]}<br>    logs = state[&quot;bag&quot;].get(&quot;action_log&quot;, [])<br>    pending = []<br>    case_id, last_obs = state[&quot;bag&quot;].get(&quot;case_id&quot;), None<br>    allowed = set(state[&quot;bag&quot;].get(&quot;allowed_actions&quot;, []))<br>    allow_all = &quot;*&quot; in allowed<br><br>    for step in y[&quot;steps&quot;]:<br>        m = TOOL_RE.search(step)<br>        if not m:<br>            logs.append(step)<br>            continue<br><br>        name = m.group(&quot;name&quot;)<br>        args = json.loads(m.group(&quot;args&quot;))<br><br>        # variable interpolation<br>        if case_id and isinstance(args, dict):<br>            for k,v in list(args.items()):<br>                if isinstance(v, str) and &quot;${case_id}&quot; in v:<br>                    args[k] = v.replace(&quot;${case_id}&quot;, case_id)<br>                if isinstance(v, str) and &quot;${last_obs}&quot; in v and last_obs:<br>                    args[k] = v.replace(&quot;${last_obs}&quot;, last_obs)<br><br>        # approval gate<br>        non_dry = (name in DESTRUCTIVE) and (args.get(&quot;dry_run&quot;, True) is False)<br>        if non_dry and not (allow_all or name in allowed):<br>            pending.append(f&#39;{name} {args}&#39;)<br>            continue<br><br>        # run tool<br>        tool = TOOLS.get(name)<br>        if not tool:<br>            logs.append(f&quot;ERROR: unknown tool {name}&quot;)<br>            continue<br>        result = tool.invoke(args)<br><br>        # capture case_id / observable_id from stub responses<br>        try:<br>            data = json.loads(result)<br>            if name == &quot;hive_create_case&quot; and data.get(&quot;ok&quot;):<br>                case_id = data[&quot;case_id&quot;]; state[&quot;bag&quot;][&quot;case_id&quot;] = case_id<br>            if name == &quot;hive_add_observable&quot; and data.get(&quot;ok&quot;):<br>                last_obs = data[&quot;observable_id&quot;]<br>        except Exception:<br>            pass<br><br>        logs.append(f&quot;{name} -&gt; {result}&quot;)<br><br>    state[&quot;bag&quot;][&quot;action_log&quot;] = logs<br>    state[&quot;bag&quot;][&quot;pending_actions&quot;] = pending<br><br>    if pending:<br>        state[&quot;active&quot;] = &quot;human_review&quot;<br>        return {&quot;messages&quot;:[AIMessage(content=&quot;Approval required for pending actions.&quot;)], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;human_review&quot;}<br><br>    state[&quot;active&quot;] = &quot;final&quot;<br>    return {&quot;messages&quot;:[AIMessage(content=&quot;Actions completed. See log.&quot;)], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;final&quot;}<br><br># 5) Finalizer (clear, short summary)<br>FINAL_SYS = &quot;&quot;&quot;You are an IR assistant. Summarize the investigation outcome using ACTION_LOG.<br>If a case_id exists, include it. If actions were blocked awaiting approval, say so.&quot;&quot;&quot;<br>def final_node(state: State) -&gt; State:<br>    bag = state[&quot;bag&quot;]<br>    log_txt = &quot;\n&quot;.join(bag.get(&quot;action_log&quot;, []))<br>    notes = []<br>    if bag.get(&quot;pending_actions&quot;):<br>        notes.append(f&quot;Pending approval: {len(bag[&#39;pending_actions&#39;])} action(s).&quot;)<br>    if bag.get(&quot;case_id&quot;):<br>        notes.append(f&quot;TheHive case: {bag[&#39;case_id&#39;]}&quot;)<br>    context = f&quot;ACTION_LOG:\n{log_txt}\n&quot; + (&quot;\n&quot;.join(notes) if notes else &quot;&quot;)<br><br>    llm = heavy_llm()<br>    out = llm.invoke([SystemMessage(content=FINAL_SYS + &quot;\n\n&quot; + context)]).content<br>    return {&quot;messages&quot;:[AIMessage(content=out)], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;final&quot;}<br><br># ------------------------------ Graph ---------------------------------------<br>from langgraph.graph import StateGraph, END<br>from langgraph.checkpoint.memory import MemorySaver<br><br>g = StateGraph(State)<br>g.add_node(&quot;guard&quot;, guard_node)<br>g.add_node(&quot;plan&quot;, plan_node)<br>g.add_node(&quot;act&quot;, act_node)<br>g.add_node(&quot;human_review&quot;, human_review_node)<br>g.add_node(&quot;final&quot;, final_node)<br><br>g.set_entry_point(&quot;guard&quot;)<br>g.add_edge(&quot;guard&quot;,&quot;plan&quot;)<br>g.add_edge(&quot;plan&quot;,&quot;act&quot;)<br>g.add_edge(&quot;act&quot;,&quot;human_review&quot;)<br>g.add_edge(&quot;human_review&quot;,&quot;act&quot;)<br>g.add_edge(&quot;act&quot;,&quot;final&quot;)<br>g.add_edge(&quot;final&quot;, END)<br><br>app = g.compile(checkpointer=MemorySaver())<br><br># ------------------------------ Demo ----------------------------------------<br>if __name__ == &quot;__main__&quot;:<br>    cfg = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;soc-demo&quot;}}<br><br>    print(&quot;\n=== 1) Phishing triage (no approvals yet) ===&quot;)<br>    msg = (&quot;We received a phishing email. Sender IP 185.71.67.5 and link http://promo-payments.ru. &quot;<br>           &quot;Open a TheHive case, add observables, enrich, analyze URL, notify #soc-ops and block the IOC. &quot;<br>           &quot;If CFO is impacted, disable the user and isolate host ws-104.&quot;)<br>    res = app.invoke({&quot;messages&quot;: [HumanMessage(msg)], &quot;bag&quot;: {}}, config=cfg)<br>    print(res[&quot;messages&quot;][-1].content)<br><br>    print(&quot;\n=== 2) Review pending actions ===&quot;)<br>    res = app.invoke({&quot;messages&quot;: [HumanMessage(&quot;approve: fw_block_ioc&quot;)], &quot;bag&quot;: res[&quot;bag&quot;]}, config=cfg)<br>    print(res[&quot;messages&quot;][-1].content)<br><br>    print(&quot;\n=== 3) Final summary ===&quot;)<br>    res = app.invoke({&quot;messages&quot;: [HumanMessage(&quot;continue&quot;)], &quot;bag&quot;: res[&quot;bag&quot;]}, config=cfg)<br>    print(res[&quot;messages&quot;][-1].content)</pre><h3>2) How it works</h3><ul><li><strong>Guard node</strong> triages &amp; summarizes the request.</li><li><strong>Planner</strong> reads the embedded <strong>YAML phishing playbook</strong>, extracts IOCs from the user’s text, and emits a YAML list of <strong>TOOL(…)</strong> steps (TheHive case → observables → enrichment → analyzer → Slack → <em>containment proposals</em>).</li><li><strong>Executor</strong> runs tools, but <strong>pauses</strong> and routes to <strong>Human Review</strong> whenever it sees a <strong>destructive</strong> tool with dry_run: false (e.g., fw_block_ioc, iam_disable_user, edr_isolate_host).</li><li><strong>Human Review</strong> presents the pending actions and waits for a reply like approve all or approve: fw_block_ioc. Partial approval is supported.</li><li><strong>Finalizer</strong> converts the action log into a concise analyst-friendly summary.</li></ul><blockquote><em>All “dangerous” tools require approval </em><strong><em>by design</em></strong><em>. You can change which tools are considered destructive by editing DESTRUCTIVE or the playbook.</em></blockquote><h3>3) Try it</h3><pre>python soc_ir_agent.py</pre><p>You’ll see three phases:</p><ol><li>Planning + safe actions (case, enrich, analyze, notify).</li><li>A pause asking you to approve the non-dry-run steps.</li><li>After approval, the agent executes and summarizes.</li></ol><p>If you reply with deny all, the agent ends the run and states that destructive actions were not executed.</p><h3>4) Swap stubs for real systems</h3><ul><li><strong>TheHive/Cortex</strong>: replace stubs with thehive4py / cortex4py and pass actual TLP/Severity enums. Capture case_id and observable_id from real responses.</li><li><strong>SIEM</strong>: Splunk Search API or Elastic _search. Ensure queries are templated &amp; escaped.</li><li><strong>EDR</strong>: CrowdStrike RTR/containment or Defender network isolation. Log approvals with analyst ID, ticket, and reason.</li><li><strong>IAM</strong>: Okta/Entra Graph; enforce break-glass rules and MFA on the approval itself.</li><li><strong>Firewall</strong>: Palo Alto pan-os-python or FortiManager REST; use dynamic tags and rule expiry.</li></ul><h3>5) Extending the playbook</h3><p>Because the <strong>planner</strong> builds steps from PHISHING_YAML, you can add stages or change defaults (Slack channel, analyzers, severity). For multiple playbooks (Malware on Endpoint, C2 Beacon, Priv-Esc), store each YAML and choose one in plan_node using simple heuristics or a small classifier.</p><p><strong>Example tweak</strong> (block only if enrichment score ≥ suspicious):</p><ul><li>Set dry_run: true in containment steps.</li><li>In act_node, inspect previous enrich_* results; if an IOC is marked suspicious/malicious, move it to the <strong>pending </strong>list with dry_run: false and request approval automatically.</li></ul><h3>6) Why this structure works</h3><ul><li><strong>Safety first</strong>: destructive actions are allowed only after explicit approval.</li><li><strong>Auditability</strong>: action log is structured JSON lines; easy to store in SIEM.</li><li><strong>Explainability</strong>: the final answer summarizes <em>what</em> was done and <em>why</em>.</li><li><strong>Composable</strong>: replace the planner, tools, or model tiers without touching the graph.</li></ul><h3>7) Quick checklist before production</h3><ul><li>Replace stubs with real adapters + secrets manager</li><li>Add JSON Schema validation on tool inputs</li><li>Attach ticket IDs to every action (Jira, TheHive task)</li><li>Persist bag to a DB (case_id, approvals, logs)</li><li>Add a <strong>reviewer identity</strong> (who approved) and reason codes</li><li>Build a tiny eval set (10–20 alerts) and regression-test the plan/execution</li></ul><p>That’s it — one file, human-safe SOC/IR automation you can build on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7728190c4b53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep-Dive: Composing 8 LLM Types into One Cohesive Agent (with runnable skeleton)]]></title>
            <link>https://medium.com/@mieitza/a-deep-dive-composing-8-llm-types-into-one-cohesive-agent-with-runnable-skeleton-025440fe60b1?source=rss-13b76a05877b------2</link>
            <guid isPermaLink="false">https://medium.com/p/025440fe60b1</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mihai Nitulescu]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 05:02:00 GMT</pubDate>
            <atom:updated>2025-11-14T05:02:00.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdU_2wDMuXpxVMrDw_hMiA.png" /></figure><p>As i mentioned in the previous article, i want to share a full LangGraph template that wires several of these types into one cohesive agent.</p><p>Below is a practical, end-to-end template that wires the eight model “roles” into a single <strong>LangGraph</strong> application:</p><ul><li><strong>SLM</strong>: input guard + light classification</li><li><strong>LCM</strong>: concept extraction &amp; routing</li><li><strong>HLM</strong>: planner/manager that decomposes work</li><li><strong>LRM</strong>: RAG reasoning chain</li><li><strong>LAM</strong>: structured tool calling (do real actions)</li><li><strong>VLM</strong>: image/screenshot understanding</li><li><strong>GPT/MoE</strong>: heavyweight generalist / “escalate” reasoner</li><li>Shared memory + budgets + observability</li></ul><p>You can copy this into a repo and replace providers (OpenAI, Anthropic, local models via Ollama/vLLM).</p><h3>Setup</h3><pre>pip install -U langgraph langchain langchain-openai \<br>  sentence-transformers faiss-cpu networkx pydantic pillow<br># For VLM demo:<br>pip install -U transformers accelerate safetensors</pre><p>Set your keys (or swap to local models):</p><pre>export OPENAI_API_KEY=sk-...</pre><h3>1) Core state and config</h3><p>We’ll keep conversation history, last active node, a running <strong>budget</strong>, and a <strong>context bag</strong> where modules drop structured facts (confirmations, citations, extracted fields).</p><pre># state.py<br>from typing import Annotated, Literal, Dict, Any<br>import operator<br>from langchain_core.messages import AnyMessage<br><br>class Cfg:<br>    HEAVY_REASONER = &quot;gpt-4o&quot;           # or &quot;mistralai/Mixtral-8x7B-Instruct-v0.1&quot;<br>    LIGHT_REASONER = &quot;gpt-4o-mini&quot;      # swap to phi-3/llama via Ollama if you prefer<br>    MAX_STEPS = 16<br>    STEP_BUDGET = 1.50                  # $ budget cap (illustrative)<br><br>class AgentState(dict):<br>    messages: Annotated[list[AnyMessage], operator.add]<br>    active: Literal[&quot;guard&quot;,&quot;concepts&quot;,&quot;route&quot;,&quot;plan&quot;,&quot;rag&quot;,&quot;act&quot;,&quot;vision&quot;,&quot;reason&quot;]<br>    bag: Dict[str, Any]                 # structured memory / blackboard<br>    spent: float                        # approximate cost tracker</pre><h3>2) Models &amp; helpers</h3><pre># models.py<br>from langchain_openai import ChatOpenAI<br><br>def light_llm():<br>    return ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br><br>def heavy_llm():<br>    return ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)</pre><p>If you want all-local: replace with ChatOllama(model=”phi3:mini”) / ChatOllama(model=”llama3.1:70b”) etc.)</p><h3>3) SLM Guardrail (input filter + quick intent)</h3><p>This uses a <strong>small</strong> model or simple rules to cheaply catch disallowed content and triage easy routes.</p><pre># nodes/guard.py<br>from langchain_core.messages import SystemMessage<br>from models import light_llm<br><br>SYS = &quot;&quot;&quot;You are a policy and triage gate.<br>1) Reject clearly harmful/illegal content with a short refusal.<br>2) Otherwise return a JSON with fields:<br>   { &quot;ok&quot;: true, &quot;intent&quot;: &quot;&lt;qa|action|vision|other&gt;&quot;, &quot;notes&quot;: &quot;&lt;short&gt;&quot; }&quot;&quot;&quot;<br><br>def guard_node(state):<br>    llm = light_llm()<br>    msgs = [SystemMessage(content=SYS)] + state[&quot;messages&quot;]<br>    out = llm.invoke(msgs).content<br>    state[&quot;bag&quot;][&quot;guard&quot;] = out<br>    state[&quot;active&quot;] = &quot;concepts&quot;<br>    return {&quot;messages&quot;: [], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;: &quot;concepts&quot;}</pre><h3>4) LCM Concept Layer (concept inventory + routing features)</h3><p>We maintain a small <strong>concept inventory</strong> and map the user message to the top few concepts. This is great for governance, analytics, and deterministic routing.</p><pre># nodes/concepts.py<br>from sentence_transformers import SentenceTransformer<br>from sklearn.neighbors import NearestNeighbors<br>import json<br><br>CONCEPTS = [<br>  &quot;billing/refund policy&quot;, &quot;SLA&quot;, &quot;security/PCI&quot;, &quot;kubernetes&quot;,<br>  &quot;vector database&quot;, &quot;incident response&quot;, &quot;travel/booking&quot;, &quot;RAG&quot;<br>]<br>_embedder = SentenceTransformer(&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>C = _embedder.encode(CONCEPTS)<br>_nn = NearestNeighbors(n_neighbors=3, metric=&quot;cosine&quot;).fit(C)<br><br>def infer_concepts(text: str, k=3):<br>    q = _embedder.encode([text])<br>    idx = _nn.kneighbors(q, return_distance=False)[0]<br>    return [CONCEPTS[i] for i in idx]<br><br>def concepts_node(state):<br>    last_user = next(m for m in reversed(state[&quot;messages&quot;]) if m.type==&quot;human&quot;)<br>    feats = infer_concepts(last_user.content)<br>    state[&quot;bag&quot;][&quot;concepts&quot;] = feats<br>    state[&quot;active&quot;] = &quot;route&quot;<br>    return {&quot;messages&quot;: [], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;: &quot;route&quot;}</pre><h3>5) Router</h3><p>Simple rules that choose the next lane based on guard intent + concepts.</p><pre># nodes/route.py<br>import json<br><br>def router_node(state):<br>    guard = state[&quot;bag&quot;].get(&quot;guard&quot;,&quot;{}&quot;)<br>    try:<br>        g = json.loads(guard)<br>    except Exception:<br>        g = {&quot;ok&quot;: True, &quot;intent&quot;: &quot;qa&quot;}<br><br>    if not g.get(&quot;ok&quot;, True):<br>        # refusal already included by guard; end turn<br>        return {&quot;messages&quot;: [], &quot;active&quot;: &quot;reason&quot;}<br><br>    feats = state[&quot;bag&quot;].get(&quot;concepts&quot;, [])<br>    if &quot;travel/booking&quot; in feats or g[&quot;intent&quot;] == &quot;action&quot;:<br>        nxt = &quot;plan&quot;     # HLM handles decomposition + tools<br>    elif any(f in feats for f in [&quot;RAG&quot;,&quot;security/PCI&quot;,&quot;SLA&quot;,&quot;vector database&quot;,&quot;kubernetes&quot;]) or g[&quot;intent&quot;]==&quot;qa&quot;:<br>        nxt = &quot;rag&quot;      # knowledge/RAG lane<br>    else:<br>        nxt = &quot;vision&quot; if g[&quot;intent&quot;]==&quot;vision&quot; else &quot;reason&quot;<br>    return {&quot;messages&quot;: [], &quot;active&quot;: nxt}</pre><h3>6) HLM Planner (manager → workers)</h3><p>Planner breaks tasks into subtasks; executor resolves each (possibly with tools). In a minimal demo we keep both in one node and emit structured actions.</p><pre># nodes/plan.py<br>from models import light_llm<br>from langchain_core.messages import SystemMessage<br><br>SYS = &quot;&quot;&quot;You are a project manager. Break the user&#39;s request into 2-6 ordered steps.<br>If any step requires calling a tool, format as:<br>  TOOL(name=&quot;&lt;tool_name&gt;&quot;, args=&lt;json&gt;)<br>Tools available: search_flights(query), book_flight(id), search_hotels(query), book_hotel(id)<br>Return YAML:<br>steps:<br>  - &lt;text or TOOL(...)&gt;<br>&quot;&quot;&quot;<br><br>def plan_node(state):<br>    llm = light_llm()<br>    msgs = [SystemMessage(content=SYS)] + state[&quot;messages&quot;]<br>    plan = llm.invoke(msgs).content<br>    state[&quot;bag&quot;][&quot;plan&quot;] = plan<br>    state[&quot;active&quot;] = &quot;act&quot;<br>    return {&quot;messages&quot;: [], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;: &quot;act&quot;}</pre><h3>7) LAM Tools (action execution)</h3><p>We wire simple tools. In production, you’ll wrap these with auth, schema validation, retries, and audit.</p><pre># nodes/tools.py<br>from langchain_core.tools import tool<br><br>@tool<br>def search_flights(query: str) -&gt; str:<br>    return &quot;F123 NYC→SFO 10:30–14:00 $249&quot;<br><br>@tool<br>def book_flight(id: str) -&gt; str:<br>    return f&quot;Booked {id}. CF-9812&quot;<br><br>@tool<br>def search_hotels(query: str) -&gt; str:<br>    return &quot;H777 Midtown Boutique $189&quot;<br><br>@tool<br>def book_hotel(id: str) -&gt; str:<br>    return f&quot;Booked {id}. HT-5521&quot;<br><br>TOOLS = {t.name: t for t in [search_flights, book_flight, search_hotels, book_hotel]}</pre><p>An <strong>executor</strong> that scans the YAML plan and runs tool steps:</p><pre># nodes/act.py<br>import re, json, yaml<br>from nodes.tools import TOOLS<br>from langchain_core.messages import AIMessage<br><br>TOOL_RE = re.compile(r&#39;TOOL\(name=&quot;(?P&lt;name&gt;[^&quot;]+)&quot;,\s*args=(?P&lt;args&gt;.+)\)&#39;)<br><br>def act_node(state):<br>    plan = state[&quot;bag&quot;].get(&quot;plan&quot;,&quot;steps: []&quot;)<br>    y = yaml.safe_load(plan) or {&quot;steps&quot;:[]}<br>    logs = []<br>    for step in y[&quot;steps&quot;]:<br>        m = TOOL_RE.search(step)<br>        if m:<br>            name = m.group(&quot;name&quot;)<br>            args = json.loads(m.group(&quot;args&quot;))<br>            res  = TOOLS[name].invoke(args)<br>            logs.append(f&quot;{name} -&gt; {res}&quot;)<br>        else:<br>            logs.append(f&quot;NOTE: {step}&quot;)<br>    msg = AIMessage(content=&quot;Action log:\n&quot; + &quot;\n&quot;.join(logs))<br>    state[&quot;bag&quot;][&quot;actions&quot;] = logs<br>    # After actions, summarize for user -&gt; heavy reasoner fallback to craft final<br>    state[&quot;active&quot;] = &quot;reason&quot;<br>    return {&quot;messages&quot;:[msg], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;reason&quot;}</pre><h3>8) LRM: RAG lane</h3><p>Create a tiny vector store and a RetrievalQA chain. Replace the toy corpus with your docs.</p><pre># nodes/rag.py<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.vectorstores import FAISS<br>from langchain.embeddings import HuggingFaceEmbeddings<br>from langchain.chains import RetrievalQA<br>from langchain_openai import ChatOpenAI<br>from langchain.docstore.document import Document<br><br>emb = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>texts = [<br>  &quot;PCI compliance requires encryption of cardholder data at rest and in transit.&quot;,<br>  &quot;A vector database stores dense vectors and supports similarity search.&quot;,<br>  &quot;Kubernetes uses Deployments to manage stateless Pods.&quot;<br>]<br>docs  = [Document(page_content=t) for t in texts]<br>vs    = FAISS.from_documents(docs, emb)<br><br>def rag_node(state):<br>    last_user = next(m for m in reversed(state[&quot;messages&quot;]) if m.type==&quot;human&quot;)<br>    qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0),<br>                                     retriever=vs.as_retriever(search_kwargs={&quot;k&quot;:2}))<br>    ans = qa.invoke({&quot;query&quot;: last_user.content})<br>    state[&quot;bag&quot;][&quot;citations&quot;] = [d.page_content for d in vs.similarity_search(last_user.content, k=2)]<br>    state[&quot;active&quot;] = &quot;reason&quot;<br>    return {&quot;messages&quot;:[ans], &quot;bag&quot;: state[&quot;bag&quot;], &quot;active&quot;:&quot;reason&quot;}</pre><h3>9) VLM lane (image/QA)</h3><p>For a self-contained demo we call an open VLM such as <strong>LLaVA 1.5</strong>. (Swap for your provider if needed.)</p><pre># nodes/vision.py<br>from PIL import Image<br>from transformers import AutoProcessor, AutoModelForCausalLM<br>import torch<br>from langchain_core.messages import AIMessage<br><br># load once (you may want lazy-init)<br>VLM_ID = &quot;llava-hf/llava-1.5-7b-hf&quot;<br>vlm_proc = AutoProcessor.from_pretrained(VLM_ID)<br>vlm = AutoModelForCausalLM.from_pretrained(VLM_ID, torch_dtype=torch.float16, device_map=&quot;auto&quot;)<br><br>def vision_node(state):<br>    # expect user to have uploaded/pointed to image path in last message<br>    last_user = next(m for m in reversed(state[&quot;messages&quot;]) if m.type==&quot;human&quot;)<br>    path = last_user.content.strip()<br>    img = Image.open(path)<br>    prompt = &quot;USER: Extract key facts from this image and summarize in 5 bullets.\nASSISTANT:&quot;<br>    inputs = vlm_proc(images=img, text=prompt, return_tensors=&quot;pt&quot;).to(vlm.device)<br>    out = vlm.generate(**inputs, max_new_tokens=180)<br>    text = vlm_proc.decode(out[0], skip_special_tokens=True)<br>    state[&quot;active&quot;] = &quot;reason&quot;<br>    return {&quot;messages&quot;:[AIMessage(content=text)], &quot;active&quot;:&quot;reason&quot;, &quot;bag&quot;: state[&quot;bag&quot;]}</pre><h3>10) Finalizer / Heavy Reasoner (GPT or MoE)</h3><p>The “closer” turns partial results (actions, citations, notes) into a crisp answer. You can also <strong>escalate</strong> here if the step budget allows.</p><pre># nodes/reason.py<br>from models import heavy_llm<br>from langchain_core.messages import SystemMessage, AIMessage<br><br>SYS = &quot;&quot;&quot;You are the finalizer. Using the context in &lt;BAG&gt;, produce a clear, safe answer.<br>- If actions were executed, summarize confirmations.<br>- If citations exist, append a short &#39;Sources&#39; list with 1-2 bullets.<br>- Be concise; numbered steps are welcome.<br>&lt;BAG&gt;<br>{bag}<br>&lt;/BAG&gt;&quot;&quot;&quot;<br><br>def reason_node(state):<br>    llm = heavy_llm()<br>    bag_txt = &quot;\n&quot;.join([f&quot;{k}: {v}&quot; for k,v in state[&quot;bag&quot;].items()])<br>    msgs = [SystemMessage(content=SYS.format(bag=bag_txt))] + state[&quot;messages&quot;]<br>    out = llm.invoke(msgs)<br>    return {&quot;messages&quot;:[AIMessage(content=out.content)], &quot;active&quot;:&quot;guard&quot;}</pre><h3>11) Wiring it with LangGraph</h3><pre># app.py<br>from langgraph.graph import StateGraph, END<br>from langgraph.checkpoint.memory import MemorySaver<br>from langchain_core.messages import HumanMessage<br>from state import AgentState<br>from nodes.guard import guard_node<br>from nodes.concepts import concepts_node<br>from nodes.route import router_node<br>from nodes.plan import plan_node<br>from nodes.act import act_node<br>from nodes.rag import rag_node<br>from nodes.vision import vision_node<br>from nodes.reason import reason_node<br><br>g = StateGraph(AgentState)<br>g.add_node(&quot;guard&quot;, guard_node)<br>g.add_node(&quot;concepts&quot;, concepts_node)<br>g.add_node(&quot;route&quot;, router_node)<br>g.add_node(&quot;plan&quot;, plan_node)<br>g.add_node(&quot;act&quot;, act_node)<br>g.add_node(&quot;rag&quot;, rag_node)<br>g.add_node(&quot;vision&quot;, vision_node)<br>g.add_node(&quot;reason&quot;, reason_node)<br><br>g.set_entry_point(&quot;guard&quot;)<br>g.add_edge(&quot;guard&quot;,&quot;concepts&quot;)<br>g.add_edge(&quot;concepts&quot;,&quot;route&quot;)<br>g.add_edge(&quot;route&quot;,&quot;plan&quot;)<br>g.add_edge(&quot;route&quot;,&quot;rag&quot;)<br>g.add_edge(&quot;route&quot;,&quot;vision&quot;)<br>g.add_edge(&quot;plan&quot;,&quot;act&quot;)<br>g.add_edge(&quot;act&quot;,&quot;reason&quot;)<br>g.add_edge(&quot;rag&quot;,&quot;reason&quot;)<br>g.add_edge(&quot;vision&quot;,&quot;reason&quot;)<br>g.add_edge(&quot;reason&quot;, END)<br><br>app = g.compile(checkpointer=MemorySaver())<br><br># --- quick demo run ---<br>if __name__ == &quot;__main__&quot;:<br>    cfg = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;demo-1&quot;}}<br>    # Knowledge question (RAG lane)<br>    res = app.invoke({&quot;messages&quot;:[HumanMessage(&quot;Do we need encryption for PCI? Provide a short answer.&quot;)]}, config=cfg)<br>    print(res[&quot;messages&quot;][-1].content)<br><br>    # Action request (Planner + Tools lane)<br>    res = app.invoke({&quot;messages&quot;:[HumanMessage(&quot;Book me a flight to SFO on Friday and a Midtown hotel.&quot;)]}, config=cfg)<br>    print(res[&quot;messages&quot;][-1].content)<br><br>    # Vision request (Vision lane)<br>    # res = app.invoke({&quot;messages&quot;:[HumanMessage(&quot;invoice.png&quot;)]}, config=cfg)<br>    # print(res[&quot;messages&quot;][-1].content)</pre><h3>12) Observability, budgets, and tests</h3><p><strong>Budgets</strong>: track spend and escalate only if remaining budget permits (pseudo-code hook inside reason_node or a middleware).</p><pre># middleware-ish idea<br>def charge(state, amount):<br>    state[&quot;spent&quot;] = round(state.get(&quot;spent&quot;,0) + amount, 4)<br>    if state[&quot;spent&quot;] &gt; 1.50:<br>        state[&quot;bag&quot;][&quot;budget_warning&quot;] = f&quot;Budget exceeded: {state[&#39;spent&#39;]}&quot;</pre><p><strong>Unit tests</strong> you can actually run:</p><pre>def test_router_travel_goes_to_plan():<br>    s = {&quot;messages&quot;:[], &quot;bag&quot;:{&quot;guard&quot;:&#39;{&quot;ok&quot;:true,&quot;intent&quot;:&quot;action&quot;}&#39;, &quot;concepts&quot;:[&quot;travel/booking&quot;]}, &quot;active&quot;:&quot;route&quot;}<br>    nxt = router_node(s)[&quot;active&quot;]<br>    assert nxt == &quot;plan&quot;<br><br>def test_concepts_pick_top3():<br>    from nodes.concepts import infer_concepts<br>    feats = infer_concepts(&quot;How do I ensure PCI for card data?&quot;)<br>    assert any(&quot;PCI&quot; in f for f in feats)</pre><h3>What you can do next</h3><ul><li>Replace the stubs in nodes/tools.py with real systems (Jira, Zendesk, SQL, Slack).</li><li>Swap ChatOpenAI with <strong>Ollama</strong> or <strong>vLLM</strong> to run fully local.</li><li>Add a <strong>MoE</strong> heavy reasoner (e.g., Mixtral) in reason_node with a simple “difficulty estimator” that decides when to escalate.</li><li>Break plan_node into full <strong>HLM</strong>: manager emits subtasks → a pool of SLM/GPT workers executes in parallel with app.stream.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=025440fe60b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Types of LLMs You’ll See Inside AI Agents (and when to use each)]]></title>
            <link>https://medium.com/@mieitza/8-types-of-llms-youll-see-inside-ai-agents-and-when-to-use-each-0485f0af29c8?source=rss-13b76a05877b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0485f0af29c8</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mihai Nitulescu]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 05:42:02 GMT</pubDate>
            <atom:updated>2025-11-13T05:42:02.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcHvH7AmuUVfDtJ9YG8IAQ.png" /></figure><p>That graphic floating around sums it up nicely: modern AI agents aren’t powered by “one model to rule them all.” We mix <strong>different LLM types</strong> — each optimized for a job — and wire them together. Below is a quick tour of the eight categories, how they show up in real systems, and short code snippets you can lift into your projects.</p><h3>1) GPT — General-Purpose Generative Pretrained Transformer</h3><p><strong>What it’s for:</strong> the default “text in → text out” brain: reasoning, drafting, synthesis, light tool use.</p><p><strong>Pros:</strong> strongest generalization, easy to steer.</p><p><strong>Cons:</strong> can be overkill (and expensive) for simple tasks.</p><p><strong>Minimal example (Hugging Face, tiny model to keep it light):</strong></p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline<br>import torch<br><br>model_id = &quot;TinyLlama/TinyLlama-1.1B-Chat-v1.0&quot;<br>tok = AutoTokenizer.from_pretrained(model_id)<br>mdl = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map=&quot;auto&quot;)<br><br>chat = pipeline(&quot;text-generation&quot;, model=mdl, tokenizer=tok)<br>print(chat(&quot;You are a concise assistant.\nUser: Explain vector databases in 2 lines.\nAssistant:&quot;, max_new_tokens=80)[0][&quot;generated_text&quot;])</pre><h3>2) MoE — Mixture of Experts</h3><p><strong>What it’s for:</strong> bigger effective parameter counts without paying full compute every token. A <strong>router</strong> activates a few “expert” sub-networks per step.</p><p><strong>Pros:</strong> great <strong>throughput/$$</strong>; specialists learn different niches.</p><p><strong>Cons:</strong> routing stability; larger memory footprint for inference.</p><p><strong>Example (run an MoE like Mixtral):</strong></p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer<br>import torch<br><br>model_id = &quot;mistralai/Mixtral-8x7B-Instruct-v0.1&quot;   # MoE<br>tok = AutoTokenizer.from_pretrained(model_id)<br>mdl = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map=&quot;auto&quot;)<br><br>prompt = &quot;You are a travel expert. Create a 3-day Tokyo food itinerary with neighborhoods.&quot;<br>ids = tok(prompt, return_tensors=&quot;pt&quot;).to(mdl.device)<br>out = mdl.generate(**ids, max_new_tokens=300, temperature=0.7)<br>print(tok.decode(out[0], skip_special_tokens=True))</pre><blockquote><em>When you need scale without crushing latency, MoE is often the first “big-iron” upgrade.</em></blockquote><h3>3) LRM — Large Reasoning Model</h3><p><strong>What it’s for:</strong> long, multi-step reasoning + tool use + RAG. Think chain-of-thought, self-consistency, and search-grounded answers.</p><p><strong>Pros:</strong> more reliable complex reasoning; verifiable with citations.</p><p><strong>Cons:</strong> slower; needs good retrieval + routing.</p><p><strong>Tiny Reason+RAG sketch (LangChain):</strong></p><pre>from langchain_openai import ChatOpenAI<br>from langchain_community.vectorstores import FAISS<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain.embeddings import HuggingFaceEmbeddings<br>from langchain.docstore.document import Document<br>from langchain import hub<br>from langchain.chains import RetrievalQA<br><br># Build a mini vector store<br>texts = [&quot;PostgreSQL uses MVCC.&quot;, &quot;Kafka is a distributed log.&quot;, &quot;Vector DBs index dense embeddings.&quot;]<br>docs  = [Document(page_content=t) for t in texts]<br>emb   = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>vs    = FAISS.from_documents(docs, emb)<br><br># Reason + retrieve<br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br>qa  = RetrievalQA.from_chain_type(llm=llm, retriever=vs.as_retriever())<br>print(qa.invoke({&quot;query&quot;: &quot;Compare Kafka to a vector database in two bullets.&quot;}))</pre><h3>4) VLM — Vision-Language Model</h3><p><strong>What it’s for:</strong> image understanding + text. Screenshots, diagrams, UIs, receipts, product photos.</p><p><strong>Pros:</strong> turn pixels into structured insights.</p><p><strong>Cons:</strong> heavier; prompt formatting matters.</p><p><strong>Example (LLaVA-1.5):</strong></p><pre>from PIL import Image<br>from transformers import AutoProcessor, AutoModelForCausalLM<br>import torch<br><br>model_id = &quot;llava-hf/llava-1.5-7b-hf&quot;<br>processor = AutoProcessor.from_pretrained(model_id)<br>model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map=&quot;auto&quot;)<br><br>img = Image.open(&quot;invoice.png&quot;)<br>prompt = &quot;USER: Extract vendor, total amount, and date from this invoice.\nASSISTANT:&quot;<br>inputs = processor(images=img, text=prompt, return_tensors=&quot;pt&quot;).to(model.device)<br>output = model.generate(**inputs, max_new_tokens=128)<br>print(processor.decode(output[0], skip_special_tokens=True))</pre><h3>5) SLM — Small Language Model</h3><p><strong>What it’s for:</strong> on-device or edge agents, fast control loops, data-local governance.</p><p><strong>Pros:</strong> cheap, fast, private.</p><p><strong>Cons:</strong> narrow capability; needs tight prompts/tools.</p><p><strong>CPU-friendly example (Phi-3 Mini with Ollama):</strong></p><pre># one-line local server; great for tiny agents and unit tests<br>ollama run phi3:mini &quot;Summarize: Event storming in domain-driven design.&quot;</pre><p>Or via Transformers:</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline<br>tok = AutoTokenizer.from_pretrained(&quot;microsoft/phi-3-mini-4k-instruct&quot;)<br>mdl = AutoModelForCausalLM.from_pretrained(&quot;microsoft/phi-3-mini-4k-instruct&quot;, device_map=&quot;auto&quot;)<br>pipe = pipeline(&quot;text-generation&quot;, model=mdl, tokenizer=tok)<br>print(pipe(&quot;Give 3 K8s troubleshooting tips:&quot;, max_new_tokens=80)[0][&quot;generated_text&quot;])</pre><h3>6) LAM — Large Action Model</h3><p><strong>What it’s for:</strong> turning language into <strong>actions</strong> via tools/APIs. Great for automation (“book flight”, “create JIRA”, “query DB”).</p><p><strong>Pros:</strong> real work gets done; deterministic via schemas.</p><p><strong>Cons:</strong> safety &amp; guardrails; need strong input validation.</p><p><strong>Structured tool-calling (LangChain style):</strong></p><pre>from langchain_core.tools import tool<br>from langchain_openai import ChatOpenAI<br><br>@tool<br>def book_flight(destination: str, date: str) -&gt; str:<br>    &quot;&quot;&quot;Books a flight and returns a confirmation code.&quot;&quot;&quot;<br>    return f&quot;Booked to {destination} on {date}. Confirm: CF-1234&quot;<br><br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0).bind_tools([book_flight])<br><br>msgs = [<br>  (&quot;system&quot;,&quot;You are a flight-booking assistant.&quot;),<br>  (&quot;human&quot;,&quot;Book me to NYC on Nov 20th. Use tools when needed.&quot;)<br>]<br>print(llm.invoke(msgs))  # model will emit a tool call</pre><blockquote><em>In production, wrap tools with auth, rate-limits, and schema validators.</em></blockquote><h3>7) HLM — Hierarchical Language Model</h3><p><strong>What it’s for:</strong> <strong>planner–worker</strong> stacks. A top model decomposes tasks; specialists execute subtasks.</p><p><strong>Pros:</strong> transparency, modularity, parallelism.</p><p><strong>Cons:</strong> orchestration complexity, error propagation if plans are bad.</p><p><strong>Mini planner → executors (no extra deps):</strong></p><pre>from typing import List<br>from openai import OpenAI<br>client = OpenAI()  # set OPENAI_API_KEY<br><br>def plan(task: str) -&gt; List[str]:<br>    prompt = f&quot;Break the task into 3-5 numbered subtasks.\nTask: {task}&quot;<br>    steps = client.chat.completions.create(model=&quot;gpt-4o-mini&quot;,<br>        messages=[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:prompt}]).choices[0].message.content<br>    return [s.split(&quot;. &quot;,1)[-1] for s in steps.split(&quot;\n&quot;) if s.strip()]<br><br>def execute(step: str) -&gt; str:<br>    # route to appropriate worker; here we just ask the same LLM<br>    return client.chat.completions.create(model=&quot;gpt-4o-mini&quot;,<br>        messages=[{&quot;role&quot;:&quot;system&quot;,&quot;content&quot;:&quot;You are a detail-oriented executor.&quot;},<br>                  {&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:step}]).choices[0].message.content<br><br>task = &quot;Migrate a monolith service to Kubernetes with zero downtime.&quot;<br>for i, s in enumerate(plan(task), 1):<br>    print(f&quot;Step {i}: {s}&quot;)<br>    print(&quot;Result:&quot;, execute(s))</pre><p>(Replace execute with real tools or smaller task-specific models.)</p><h3>8) LCM — Large Concept Model</h3><p><strong>What it’s for:</strong> mapping inputs to <strong>interpretable concepts</strong> (skills, entities, risks) before generating text. Useful for policy, safety, knowledge graphs, and explainable decisions.</p><p><strong>Pros:</strong> controllable, auditable, easy to ground in KGs.</p><p><strong>Cons:</strong> extra engineering (schemas, concept stores).</p><p><strong>Toy “concept bottleneck” pipeline:</strong></p><pre>import json, networkx as nx<br>from sentence_transformers import SentenceTransformer<br>from sklearn.neighbors import NearestNeighbors<br><br># 1) Concept inventory<br>concepts = [&quot;refund policy&quot;,&quot;SLA&quot;,&quot;PCI compliance&quot;,&quot;PTO&quot;,&quot;on-call&quot;,&quot;RAG&quot;,&quot;vector database&quot;,&quot;Kubernetes&quot;]<br>embed = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>C = embed.encode(concepts)<br><br># 2) Encode a query and pick top concepts<br>def concepts_for(text, k=3):<br>    q = embed.encode([text])<br>    nn = NearestNeighbors(n_neighbors=k, metric=&quot;cosine&quot;).fit(C)<br>    idx = nn.kneighbors(q, return_distance=False)[0]<br>    return [concepts[i] for i in idx]<br><br># 3) Route generation using concepts (here we just print)<br>user = &quot;How do we secure card data in our payment service?&quot;<br>selected = concepts_for(user, k=2)<br>print(&quot;Concepts:&quot;, selected)<br><br># 4) Optionally link to a knowledge graph<br>G = nx.Graph(); G.add_edges_from([(&quot;PCI compliance&quot;,&quot;tokenization&quot;),(&quot;PCI compliance&quot;,&quot;encryption&quot;)])<br>neighbors = list(G.neighbors(&quot;PCI compliance&quot;))<br>print(&quot;Related nodes:&quot;, neighbors)<br><br># Downstream: feed concepts + KG neighbors into the prompt for grounded answers.</pre><h3>Choosing the right type (cheat sheet)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*QrRNYZtOjyGdJtQu9UkUlw.png" /></figure><h3>Putting it together in an Agent</h3><p>A pragmatic production stack often looks like:</p><ol><li><strong>SLM</strong> guardrail filters inputs.</li><li><strong>LCM</strong> extracts concepts; routes queries.</li><li><strong>LRM</strong> (with RAG) answers;</li><li><strong>LAM</strong> executes actions safely;</li><li><strong>HLM</strong> coordinates the flow;</li><li><strong>VLM</strong> jumps in for screenshots or documents;</li><li><strong>MoE/GPT</strong> step in for heavy reasoning.</li></ol><p>The art of agent design is choosing the <strong>smallest</strong> model that does the job and composing it with the right neighbors. Start simple (GPT/SLM + LAM), add RAG for grounding, then scale to MoE/HLM/LCM as your use cases harden.</p><p>If you want a follow-up deep dive, I can share a full LangGraph template that wires several of these types into one cohesive agent.</p><p>In the next article i will do a follow-up deep dive, and share a full LangGraph template that wires several of these types into one cohesive agent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0485f0af29c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Swarm of AI Agents with LangGraph]]></title>
            <link>https://medium.com/@mieitza/build-a-swarm-of-ai-agents-with-langgraph-2ef9fcb287f8?source=rss-13b76a05877b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ef9fcb287f8</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mihai Nitulescu]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 08:22:23 GMT</pubDate>
            <atom:updated>2025-11-12T08:22:23.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="LangGraph’s multi-agent swarm is a clean way to coordinate several specialized agents that can hand off control to one another while remembering which agent was last active. Think of it as a relay team: each runner (agent) is great at a specific leg, and the baton (conversation state) moves to whoever is best suited next." src="https://cdn-images-1.medium.com/max/658/1*hNqo99iuIClNyMF2RdkoaA.png" /></figure><p><em>A hands-on guide (with code) to the “multi-agent swarm” pattern</em></p><p>LangGraph’s <strong>multi-agent swarm</strong> is a clean way to coordinate several specialized agents that can <strong>hand off</strong> control to one another while remembering which agent was last active. Think of it as a relay team: each runner (agent) is great at a specific leg, and the baton (conversation state) moves to whoever is best suited next.</p><p>Below, we’ll build a tiny <strong>travel concierge</strong>: a <strong>Flight Agent</strong> and a <strong>Hotel Agent</strong> that cooperate. You’ll see:</p><ul><li>shared conversation state (memory),</li><li>tool use (search / book),</li><li>dynamic handoffs,</li><li>streaming + persistence so the convo resumes with the last active agent.</li></ul><h3>TL;DR: what we’re building</h3><ul><li>A <strong>LangGraph</strong> state machine where each node is an agent.</li><li>Agents call <strong>tools</strong> to act, and can invoke a <strong>handoff tool</strong> to pass control.</li><li>The graph <strong>remembers</strong> the last active agent so the next user message resumes with it.</li></ul><h3>Setup</h3><pre>pip install -U langgraph langchain langchain-openai<br># or swap OpenAI for your preferred LLM provider (anthropic, etc.)</pre><p>Set your key:</p><pre>export OPENAI_API_KEY=sk-...</pre><h3>1) Define the shared state</h3><p>We keep the running message history and track which agent currently owns the conversation.</p><pre>from typing import TypedDict, Annotated, Literal<br>import operator<br>from langchain_core.messages import AnyMessage<br><br>class AgentState(TypedDict):<br>    messages: Annotated[list[AnyMessage], operator.add]  # running chat log<br>    active: Literal[&quot;flight&quot;, &quot;hotel&quot;]                   # last active agent</pre><h3>2) Tools the agents can use</h3><p>These are stubbed so you can run end-to-end. Replace with real integrations later.</p><pre>from langchain_core.tools import tool<br><br>@tool<br>def search_flights(query: str) -&gt; str:<br>    &quot;&quot;&quot;Find flight options. Ex: &#39;NYC to SFO on 2025-11-20&#39;.&quot;&quot;&quot;<br>    return &quot;Found flight F123: NYC→SFO 10:30–14:00, $249&quot;<br><br>@tool<br>def book_flight(flight_id: str) -&gt; str:<br>    &quot;&quot;&quot;Book a flight by ID, returns a confirmation code.&quot;&quot;&quot;<br>    return f&quot;Flight {flight_id} booked. Confirmation: CF-9812&quot;<br><br>@tool<br>def search_hotels(query: str) -&gt; str:<br>    &quot;&quot;&quot;Find hotel options. Ex: &#39;Times Square 11/20–11/22&#39;.&quot;&quot;&quot;<br>    return &quot;Found hotel H777: Midtown Boutique, $189/night&quot;<br><br>@tool<br>def book_hotel(hotel_id: str) -&gt; str:<br>    &quot;&quot;&quot;Book a hotel by ID, returns a confirmation code.&quot;&quot;&quot;<br>    return f&quot;Hotel {hotel_id} booked. Confirmation: HT-5521&quot;</pre><p>Two <strong>handoff</strong> tools let agents explicitly pass the baton:</p><pre>@tool<br>def handoff_to_hotel(reason: str) -&gt; str:<br>    &quot;&quot;&quot;Signal that the Hotel agent should take over.&quot;&quot;&quot;<br>    return &quot;HANDOFF_TO_HOTEL&quot;<br><br>@tool<br>def handoff_to_flight(reason: str) -&gt; str:<br>    &quot;&quot;&quot;Signal that the Flight agent should take over.&quot;&quot;&quot;<br>    return &quot;HANDOFF_TO_FLIGHT&quot;</pre><h3>3) The agents</h3><p>Each agent is just an LLM bound to the tools it’s allowed to use, plus a tiny system prompt describing its role.</p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.messages import SystemMessage, AIMessage, HumanMessage<br><br>flight_llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0) \<br>    .bind_tools([search_flights, book_flight, handoff_to_hotel])<br><br>hotel_llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0) \<br>    .bind_tools([search_hotels, book_hotel, handoff_to_flight])<br><br>FLIGHT_SYS = SystemMessage(content=(<br>    &quot;You are the Flight Agent. You ONLY handle flights. &quot;<br>    &quot;Use tools to search/book flights. When the user asks for hotels, &quot;<br>    &quot;call handoff_to_hotel with a brief reason.&quot;<br>))<br><br>HOTEL_SYS = SystemMessage(content=(<br>    &quot;You are the Hotel Agent. You ONLY handle hotels. &quot;<br>    &quot;Use tools to search/book hotels. When the user asks for flights, &quot;<br>    &quot;call handoff_to_flight with a brief reason.&quot;<br>))</pre><p>Agent node functions:</p><pre>def flight_agent(state: AgentState) -&gt; AgentState:<br>    msgs = [FLIGHT_SYS] + state[&quot;messages&quot;]<br>    ai = flight_llm.invoke(msgs)<br>    return {&quot;messages&quot;: [ai], &quot;active&quot;: &quot;flight&quot;}<br><br>def hotel_agent(state: AgentState) -&gt; AgentState:<br>    msgs = [HOTEL_SYS] + state[&quot;messages&quot;]<br>    ai = hotel_llm.invoke(msgs)<br>    return {&quot;messages&quot;: [ai], &quot;active&quot;: &quot;hotel&quot;}</pre><h3>4) Wiring the graph</h3><p>We’ll use LangGraph’s ToolNode to execute tool calls, and conditional edges to (a) run tools when the model asks, and (b) detect <strong>handoff</strong>.</p><pre>from langgraph.graph import StateGraph, END<br>from langgraph.prebuilt import ToolNode, tools_condition<br>from langchain_core.messages import ToolMessage<br><br># Tool executors per agent<br>flight_tools_node = ToolNode([search_flights, book_flight, handoff_to_hotel])<br>hotel_tools_node  = ToolNode([search_hotels,  book_hotel,  handoff_to_flight])<br><br># After tools run, decide who should speak next<br>def route_after_flight_tools(state: AgentState):<br>    # If the last tool result contains our handoff sentinel, switch agents<br>    last = state[&quot;messages&quot;][-1]<br>    if isinstance(last, ToolMessage) and &quot;HANDOFF_TO_HOTEL&quot; in last.content:<br>        return &quot;hotel&quot;<br>    return &quot;flight&quot;<br><br>def route_after_hotel_tools(state: AgentState):<br>    last = state[&quot;messages&quot;][-1]<br>    if isinstance(last, ToolMessage) and &quot;HANDOFF_TO_FLIGHT&quot; in last.content:<br>        return &quot;flight&quot;<br>    return &quot;hotel&quot;<br><br># Router: who starts for this turn (whichever was last active)<br>def entry_router(state: AgentState):<br>    return state.get(&quot;active&quot;, &quot;flight&quot;)</pre><p>Build the graph:</p><pre>builder = StateGraph(AgentState)<br><br># nodes<br>builder.add_node(&quot;flight&quot;, flight_agent)<br>builder.add_node(&quot;hotel&quot;, hotel_agent)<br>builder.add_node(&quot;flight_tools&quot;, flight_tools_node)<br>builder.add_node(&quot;hotel_tools&quot;, hotel_tools_node)<br><br># start -&gt; whichever agent was last active<br>builder.set_entry_point(&quot;router&quot;)<br>builder.add_node(&quot;router&quot;, lambda s: s)  # no-op pass-through<br>builder.add_conditional_edges(&quot;router&quot;, entry_router, {<br>    &quot;flight&quot;: &quot;flight&quot;,<br>    &quot;hotel&quot;: &quot;hotel&quot;<br>})<br><br># agents -&gt; if they requested tools, run them; else end the turn<br>builder.add_conditional_edges(&quot;flight&quot;, tools_condition, {<br>    &quot;tools&quot;: &quot;flight_tools&quot;,<br>    END: END<br>})<br>builder.add_conditional_edges(&quot;hotel&quot;, tools_condition, {<br>    &quot;tools&quot;: &quot;hotel_tools&quot;,<br>    END: END<br>})<br><br># after tools -&gt; return to same agent OR hand off<br>builder.add_conditional_edges(&quot;flight_tools&quot;, route_after_flight_tools, {<br>    &quot;flight&quot;: &quot;flight&quot;,<br>    &quot;hotel&quot;: &quot;hotel&quot;<br>})<br>builder.add_conditional_edges(&quot;hotel_tools&quot;, route_after_hotel_tools, {<br>    &quot;hotel&quot;: &quot;hotel&quot;,<br>    &quot;flight&quot;: &quot;flight&quot;<br>})<br><br># (optional) memory/persistence so the thread resumes with the last agent<br>from langgraph.checkpoint.memory import MemorySaver<br>memory = MemorySaver()<br><br>app = builder.compile(checkpointer=memory)</pre><h3>5) Try it out</h3><p><strong>First message</strong>: the Flight agent is a sensible default.</p><pre>from langchain_core.messages import HumanMessage<br><br>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;user-123&quot;}}<br><br>result = app.invoke(<br>    {&quot;messages&quot;: [HumanMessage(&quot;Book me a flight to NYC on Friday and a hotel near Times Square.&quot;)]},<br>    config=config<br>)<br>print(result[&quot;messages&quot;][-1].content)</pre><p>You should see the Flight Agent respond, likely searching flights and then calling handoff_to_hotel, which triggers the graph to execute hotel tools and switch control.</p><p><strong>Streaming</strong> (to watch the baton pass in real time):</p><pre>for event in app.stream(<br>    {&quot;messages&quot;: [HumanMessage(&quot;Ok, lock the best price and then find a 4-star hotel with breakfast.&quot;)]},<br>    config=config<br>):<br>    print(event)</pre><p><strong>Follow-up message</strong>: the graph <strong>remembers</strong> the last active agent (e.g., Hotel) and resumes there automatically.</p><pre>app.invoke({&quot;messages&quot;: [HumanMessage(&quot;Great—book that hotel too.&quot;)]}, config=config)</pre><h3>6) Why the swarm pattern works</h3><ul><li><strong>Specialization, not monoliths</strong>: Each agent has a narrow system prompt and toolset, which improves tool selection and reduces prompt bloat.</li><li><strong>Explicit control transfer</strong>: The handoff tool makes the baton pass <em>observable</em> and testable.</li><li><strong>Stateful UX</strong>: The active field ensures users don’t wrestle with “which agent do I address?” — they just keep talking.</li><li><strong>Composable</strong>: Add more agents (payments, support, itinerary) by copying the pattern and adding routes.</li></ul><h3>7) Extending the example</h3><ul><li><strong>Guardrails</strong>: Insert a policy node before tools that validates arguments (dates, budgets).</li><li><strong>Observation memory</strong>: Store structured results (PNRs, confirmation codes) into state so later agents can reference them without re-calling tools.</li><li><strong>Human-in-the-loop</strong>: Route certain intents (e.g., high spend) to a human_review node.</li><li><strong>Persistence</strong>: Swap MemorySaver for a DB-backed checkpointer to resume sessions across processes.</li></ul><h3>8) Minimal tests</h3><p>Handoff logic is just functions → easy to unit test:</p><pre>from langchain_core.messages import ToolMessage<br><br>def test_handoff_to_hotel():<br>    s = {&quot;messages&quot;: [ToolMessage(tool_call_id=&quot;x&quot;, content=&quot;HANDOFF_TO_HOTEL&quot;)], &quot;active&quot;: &quot;flight&quot;}<br>    assert route_after_flight_tools(s) == &quot;hotel&quot;<br><br>def test_stay_on_flight():<br>    s = {&quot;messages&quot;: [ToolMessage(tool_call_id=&quot;x&quot;, content=&quot;OK&quot;)], &quot;active&quot;: &quot;flight&quot;}<br>    assert route_after_flight_tools(s) == &quot;flight&quot;</pre><h3>Closing thoughts</h3><p>The <strong>multi-agent swarm</strong> pattern in LangGraph gives you a pragmatic, observable way to orchestrate specialists that <em>feel</em>like one cohesive assistant. Start with two agents and a simple handoff; you’ll quickly see how easy it is to grow into a real, production-ready workflow.</p><p>If you ship something fun with this template — travel, IT ops, incident response, concierge — tell me how you wired your agents and what tools made the biggest difference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ef9fcb287f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Full-Stack LLM in an Afternoon with Karpathy’s nanochat (step-by-step, with code)]]></title>
            <link>https://medium.com/@mieitza/build-a-full-stack-llm-in-an-afternoon-with-karpathys-nanochat-step-by-step-with-code-041b434ec066?source=rss-13b76a05877b------2</link>
            <guid isPermaLink="false">https://medium.com/p/041b434ec066</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mihai Nitulescu]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 13:55:10 GMT</pubDate>
            <atom:updated>2025-11-11T13:55:10.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="If you’ve ever wanted to see every layer of an LLM — tokenizer, pretraining, alignment, and a simple chat UI — without wading through a giant monorepo, nanochat is the clean, dependency-minimal “from scratch” pipeline that gets you there fast. Think of it as a speedrun from raw text to a tiny-but-capable ChatGPT-style web app." src="https://cdn-images-1.medium.com/max/953/1*ho9L-J3FESHb3_5vz_Cuew.png" /></figure><p>If you’ve ever wanted to see <em>every layer</em> of an LLM — tokenizer, pretraining, alignment, and a simple chat UI — without wading through a giant monorepo, <strong>nanochat</strong> is the clean, dependency-minimal “from scratch” pipeline that gets you there fast. Think of it as a speedrun from raw text to a tiny-but-capable ChatGPT-style web app.</p><p>Below is a practical, copy-pasteable walkthrough you can follow on a single GPU cloud box. You’ll set up the machine, grab the repo, teach the model to <em>read</em> (tokenizer + text modeling), then <em>talk</em> (instruction tuning), and finally launch a web chat.</p><blockquote><em>⚠️ Heads-up: command names and flags occasionally change upstream. Use these as templates — if a script name differs, ls the scripts/ or tools/ folder and adapt.</em></blockquote><h3>What you’ll build</h3><ul><li>A small LLM trained end-to-end on a clean web dataset (e.g., <strong>FineWeb</strong> or similar).</li><li>A tokenizer you train yourself (BPE/SentencePiece style).</li><li>A “mid-training”/SFT stage that teaches the model to answer questions, converse naturally, and solve basic logic/math.</li><li>A minimal ChatGPT-like <strong>web UI</strong> to talk to your model.</li></ul><h3>Prerequisites</h3><ul><li><strong>GPU</strong>: 1× A100 40–80GB (works on 24GB+ with smaller configs).</li><li><strong>OS</strong>: Ubuntu 22.04+ (or similar).</li><li><strong>Python</strong>: 3.10+</li><li><strong>CUDA</strong>: 12.x, drivers installed.</li><li><strong>Disk</strong>: 150–300GB free (datasets + checkpoints).</li></ul><p>Run this right after you SSH in:</p><pre># sanity checks<br>nvidia-smi<br>python3 - version || sudo apt-get update &amp;&amp; sudo apt-get install -y python3 python3-venv python3-pip<br># optional: a few niceties<br>sudo apt-get install -y git tmux htop nvtop<br># (recommended) use a fresh venv<br>python3 -m venv ~/.venvs/nanochat<br>source ~/.venvs/nanochat/bin/activate<br>python -m pip install - upgrade pip wheel</pre><h3>1) Clone the repo and speedrun the setup</h3><pre>git clone https://github.com/karpathy/nanochat.git<br>cd nanochat<br><br># install python deps<br>pip install -r requirements.txt<br># if the project supports flash-attn or xformers, you can install them here for faster training:<br># pip install flash-attn --no-build-isolation</pre><p>Many runs can be kicked off with a single script (often called speedrun.sh). It typically:</p><ul><li>downloads and filters a clean web dataset,</li><li>trains a tokenizer,</li><li>starts a small LLM pretraining job,</li><li>spins up a simple web UI (optionally) when a checkpoint is ready</li></ul><pre># one-and-done (adjust flags to taste)<br>bash scripts/speedrun.sh \<br>  --data_root /data/nanochat \<br>  --model_size tiny \<br>  --steps 20000 \<br>  --eval_every 1000</pre><p>If the repo doesn’t ship that exact script, the next sections show the <em>explicit</em> steps.</p><h3>2) Teach it to read: build your tokenizer</h3><p>Tokenizers turn text into integer tokens. Training your own ensures the vocabulary matches the data distribution you’ll actually model.</p><pre># Example tokenizer training (BPE/SentencePiece style)<br># Inputs:<br>#   --dataset points at a local dir or a downloader key (e.g., &quot;fineweb-edu-10B&quot;)<br>#   --vocab_size balances compression vs. sequence length<br>#   --output becomes the tokenizer model you’ll reuse later<br>python tools/train_tokenizer.py \<br>  --dataset fineweb-edu-10B \<br>  --vocab_size 65536 \<br>  --lowercase true \<br>  --output artifacts/tokenizer.model</pre><p>Peek at it:</p><pre>python tools/inspect_tokenizer.py artifacts/tokenizer.model --show-ids &quot;Hello, nanochat!&quot;</pre><p><strong>Tip:</strong> If VRAM is tight, prefer a smaller vocab (e.g., 32k). If you plan on multi-lingual or code-heavy text, keep vocab ≥50k.</p><h3>3) Pretrain a small language model on clean web text</h3><p>This is the <em>self-supervised</em> stage where the model learns general language structure.</p><pre># A small, fast config to get a working checkpoint in a few hours<br>cat &gt; configs/tiny.yaml &lt;&lt;&#39;YAML&#39;<br># toy-ish config; tune as you like<br>model:<br>  n_layers: 12<br>  n_heads: 12<br>  d_model: 768<br>  d_ff: 3072<br>  vocab_size: 65536<br>  max_seq_len: 2048<br>  dropout: 0.0<br>train:<br>  batch_size: 64          # use gradient accumulation if memory bound<br>  micro_batch_size: 4<br>  lr: 3e-4<br>  warmup_steps: 1000<br>  total_steps: 20000<br>  eval_every: 1000<br>  ckpt_every: 2000<br>  precision: bf16         # or fp16; use fp8 if supported<br>data:<br>  dataset: fineweb-edu-10B<br>  tokenizer: artifacts/tokenizer.model<br>  num_workers: 8<br>YAML<br><br># Kick off pretraining<br>python train.py --config configs/tiny.yaml --out out/pretrain_tiny</pre><p>Checkpoint artifacts will land in out/pretrain_tiny/. You can resume training anytime:</p><pre>python train.py --config configs/tiny.yaml --out out/pretrain_tiny --resume latest</pre><h3>4) Teach it to talk: instruction tuning / mid-training</h3><p>Now we help the model behave conversationally: follow instructions, reason step-by-step, and answer questions naturally. A tiny JSONL format works great:</p><pre>mkdir -p data/sft<br>cat &gt; data/sft/smalltalk.jsonl &lt;&lt;&#39;JSONL&#39;<br>{&quot;system&quot;:&quot;You are a helpful assistant.&quot;,&quot;user&quot;:&quot;Explain overfitting like I&#39;m new to ML.&quot;,&quot;assistant&quot;:&quot;Overfitting is when a model memorizes training examples instead of learning general patterns, so it performs well on training data but poorly on new data.&quot;}<br>{&quot;system&quot;:&quot;You are a helpful assistant.&quot;,&quot;user&quot;:&quot;2+2*5?&quot;,&quot;assistant&quot;:&quot;2 + 2*5 = 2 + 10 = 12.&quot;}<br>{&quot;system&quot;:&quot;You are a helpful assistant.&quot;,&quot;user&quot;:&quot;Give me a haiku about GPUs.&quot;,&quot;assistant&quot;:&quot;Silent fans awaken\nParallel thoughts in silicon—\nNight turns into light.&quot;}<br>JSONL</pre><p>Train (SFT) on that and any public instruction datasets you’ve downloaded:</p><pre>python sft.py \<br>  --base_ckpt out/pretrain_tiny/latest.ckpt \<br>  --tokenizer artifacts/tokenizer.model \<br>  --train_files data/sft/smalltalk.jsonl \<br>  --epochs 2 \<br>  --lr 5e-5 \<br>  --out out/sft_tiny</pre><p><strong>Optional evals</strong> (swap in tasks you have locally):</p><pre>python eval.py --ckpt out/sft_tiny/latest.ckpt --task mmlu<br>python eval.py --ckpt out/sft_tiny/latest.ckpt --task gsm8k</pre><h3>5) Open the chat window (simple web UI)</h3><p>Most minimal stacks ship a tiny Gradio/Flask/FastAPI app. Typical usage:</p><pre># Launch a local chat server<br>python webui.py \<br>  --ckpt out/sft_tiny/latest.ckpt \<br>  --tokenizer artifacts/tokenizer.model \<br>  --port 7860</pre><p>Then point your browser at http://&lt;your-instance-ip&gt;:7860 and chat.</p><p>Prefer an API? A trivial FastAPI server looks like this:</p><pre># serve.py — ultra-minimal inference API<br>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from your_inference_lib import NanoChatModel  # thin wrapper around your model<br><br>app = FastAPI()<br>model = NanoChatModel(<br>    checkpoint=&quot;out/sft_tiny/latest.ckpt&quot;,<br>    tokenizer_path=&quot;artifacts/tokenizer.model&quot;<br>)<br><br>class ChatIn(BaseModel):<br>    system: str = &quot;You are a helpful assistant.&quot;<br>    messages: list[str]  # alternating user/assistant, last must be user<br><br>@app.post(&quot;/chat&quot;)<br>def chat(req: ChatIn):<br>    reply = model.generate(system=req.system, messages=req.messages, max_new_tokens=256)<br>    return {&quot;reply&quot;: reply}</pre><p>Run it:</p><pre>uvicorn serve:app --host 0.0.0.0 --port 8000</pre><p>Test it:</p><pre>curl -s http://localhost:8000/chat \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;system&quot;:&quot;You are a helpful assistant.&quot;,&quot;messages&quot;:[&quot;Hi! Who are you?&quot;]}&#39;</pre><h3>6) Add your own data (quick RAG sketch)</h3><p>A simple retrieval-augmented generation loop can make your tiny model feel far more capable with <em>your</em> docs:</p><pre># rag.py — tiny local RAG utility<br>import glob, json<br>from sentence_transformers import SentenceTransformer<br>from your_inference_lib import NanoChatModel<br>from sklearn.neighbors import NearestNeighbors<br><br># 1) embed your docs<br>docs = []<br>for p in glob.glob(&quot;my_docs/*.txt&quot;):<br>    docs.append(open(p, &quot;r&quot;, encoding=&quot;utf-8&quot;).read())<br><br>embedder = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>X = embedder.encode(docs)<br><br># 2) build a tiny index<br>nn = NearestNeighbors(n_neighbors=3, metric=&quot;cosine&quot;).fit(X)<br><br># 3) query then chat<br>def rag_answer(query: str):<br>    qv = embedder.encode([query])<br>    idx = nn.kneighbors(qv, return_distance=False)[0]<br>    context = &quot;\n\n&quot;.join(docs[i][:1500] for i in idx)  # trim context<br><br>    prompt = f&quot;&quot;&quot;Use ONLY the CONTEXT to answer.<br>CONTEXT:<br>{context}<br><br>QUESTION: {query}<br>ANSWER:&quot;&quot;&quot;<br>    model = NanoChatModel(&quot;out/sft_tiny/latest.ckpt&quot;, &quot;artifacts/tokenizer.model&quot;)<br>    return model.generate(messages=[prompt], max_new_tokens=256)<br><br>print(rag_answer(&quot;What is our refund policy?&quot;))</pre><h3>7) Troubleshooting &amp; performance tips</h3><ul><li><strong>VRAM OOM?</strong> Lower micro_batch_size, vocab size, or sequence length; use gradient accumulation; try bf16/fp16; enable flash-attention if supported.</li><li><strong>Slow dataloading?</strong> Increase num_workers; store datasets on local NVMe (avoid networked disks if you can).</li><li><strong>Loss plateaus early?</strong> Warmup a bit longer, lower LR, or check tokenization stats (too tiny vocab or too aggressive filtering can hurt).</li><li><strong>Chat feels terse?</strong> Nudge decoding: temperature=0.7–0.9, add penalty terms, or increase max_new_tokens.</li></ul><h3>8) Costs &amp; time (very rough)</h3><ul><li>A <strong>tiny</strong> config can produce a playful model in <strong>~4–8 hours</strong> on 1× A100 80GB.</li><li>SFT adds another <strong>1–3 hours</strong> depending on dataset size and batch settings.</li><li>Disk use swings with datasets (tens to low hundreds of GB).</li></ul><p>(Your mileage will vary — these are “ballpark for speedrun” numbers.)</p><h3>9) Where to go next</h3><ul><li>Scale the config (more layers/heads, longer context).</li><li>Add <strong>RLHF</strong> or DPO for preference-aligned behavior.</li><li>Swap in domain corpora (code, biomedical, legal).</li><li>Quantize to <strong>INT8/4</strong> and test latency on smaller GPUs/CPUs.</li><li>Wrap the API with authentication + logging and ship internally.</li></ul><h3>Appendix: All-in-one “tiny” script</h3><pre>#!/usr/bin/env bash<br>set -euo pipefail<br><br># paths<br>ROOT=${1:-$PWD}<br>DATA_ROOT=${DATA_ROOT:-$ROOT/data}<br>ARTI=$ROOT/artifacts<br>OUT=$ROOT/out<br><br>mkdir -p &quot;$DATA_ROOT&quot; &quot;$ARTI&quot; &quot;$OUT&quot;<br><br>echo &quot;[1/4] Train tokenizer&quot;<br>python tools/train_tokenizer.py \<br>  --dataset fineweb-edu-10B \<br>  --vocab_size 65536 \<br>  --output $ARTI/tokenizer.model<br><br>echo &quot;[2/4] Pretrain tiny LLM&quot;<br>python train.py \<br>  --config configs/tiny.yaml \<br>  --out $OUT/pretrain_tiny<br><br>echo &quot;[3/4] SFT on small talk&quot;<br>python sft.py \<br>  --base_ckpt $OUT/pretrain_tiny/latest.ckpt \<br>  --tokenizer $ARTI/tokenizer.model \<br>  --train_files data/sft/smalltalk.jsonl \<br>  --epochs 2 \<br>  --lr 5e-5 \<br>  --out $OUT/sft_tiny<br><br>echo &quot;[4/4] Launch web UI (Ctrl+C to stop)&quot;<br>python webui.py \<br>  --ckpt $OUT/sft_tiny/latest.ckpt \<br>  --tokenizer $ARTI/tokenizer.model \<br>  --port 7860</pre><h3>Wrap-up</h3><p>Karpathy’s <strong>nanochat</strong> makes the LLM stack feel approachable: you see the moving parts, you can swap any of them, and you get a tangible result — a chatty model with a tiny UI — by the end of the afternoon. From there, you can scale, specialize, or productize. Have fun hacking, and if you build something neat with your own data, I’d love to hear about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=041b434ec066" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>