<?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 Yingbiao(Bill) Huang on Medium]]></title>
        <description><![CDATA[Stories by Yingbiao(Bill) Huang on Medium]]></description>
        <link>https://medium.com/@yingbiao?source=rss-f9f914e94fe0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-7jbB1rHfqL1AP54yvaJkA.jpeg</url>
            <title>Stories by Yingbiao(Bill) Huang on Medium</title>
            <link>https://medium.com/@yingbiao?source=rss-f9f914e94fe0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:00:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yingbiao/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[Skills-Driven Ralph Agents in Action]]></title>
            <link>https://medium.com/@yingbiao/skills-driven-ralph-agents-in-action-01d4713c0c4c?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/01d4713c0c4c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 18:30:51 GMT</pubDate>
            <atom:updated>2026-01-21T20:09:17.779Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>You may heard about Ralph — the autonomous agent loop that lets AI work for hours without babysitting.</p><p>What if you could make Ralph smarter by giving it <strong>Skills</strong> — reusable recipes that tell it exactly what to do, how to evaluate success, and when to stop?</p><p>This guide will help you understand:</p><ul><li>What is Ralph and why it works</li><li>What are Skills and how they supercharge Ralph</li><li>Hands-on: Build a Skills-Driven Ralph Agent</li></ul><h3>1. What is Ralph?</h3><p><a href="https://ghuntley.com/ralph/"><strong>Ralp</strong></a> (named after the Simpsons character who “just keeps going”) is an autonomous agent loop pattern. The core idea is simple:</p><blockquote><strong>Giving the agent a belief and letting it fight to the bitter end.</strong></blockquote><p><strong>Traditional Agent vs Ralph Agent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhgXOmORK0ybUgeLdGe01g.png" /></figure><p><strong>When to Use Which?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8rVVszSp405InvEorVuDA.png" /></figure><p>But basic Ralph agent has a problem: <strong>how does the agent know how to do well?</strong></p><p>&gt;&gt;&gt;&gt;That’s where Skills come in.&lt;&lt;&lt;&lt;</p><h3><strong>2. What is a Skill?</strong></h3><p>A <a href="https://code.claude.com/docs/en/skills">Skill</a> is a markdown file (`SKILL.md`) that with natural language telling Ralph agent exactly:</p><ul><li>The target of the task</li><li>How to process the task</li><li>How to evaluate success</li><li>When to say “DONE”</li></ul><h3>3. Ralph + Skills: Why It Matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZOqMGOzxhmbIQL_ZXZMQQ.png" /></figure><p>Using Ralph mode alone, the agent aims for a final target and keeps iterating. But without guidelines, two things can happen:</p><p>1. <strong>Never reach the target</strong> — or take way too long</p><p>2. <strong>Reach the target but not the right direction</strong> — like the Coldplay song “<a href="https://genius.com/Coldplay-fix-you-lyrics">Fix You</a>”: <strong><em>When you get what you want, but not what you need</em></strong></p><p>Skills solve this by giving the agent a process to follow during each iteration.</p><p><strong>Here is an example:</strong></p><p>Imagine you own a restaurant and want your chef to create the next popular dish with pineapple.</p><p><strong>Ralph only:</strong></p><p>You let your chef try freely. They work hard, experiment randomly. Maybe the final result is… canned pineapple that appeals to kids. Technically it works, but not what you wanted.</p><p><strong>Ralph + Skills:</strong></p><p>You give your chef the recipe guidelines from your best-selling dish. They still create something new with pineapple, but follow your proven process. The result: a new pineapple dish that matches your restaurant’s quality standards.</p><p><strong>Skills-Driven Ralph = Agent keep processing with the right way, EVERY TIME.</strong></p><h3>4. Hands-On</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvsdFVjx0YqEEFlQzllokA.png" /></figure><p>Here is my project that implements the Skills-Driven Ralph Agent with a ready-to-use pipeline. As a user, you only need to add skills for tasks you want.</p><p>There are 2 built-in skills in this project:</p><p>1. <strong>youtube-learner</strong>— Learn any topic from YouTube transcripts, create a comprehensive report</p><p>2. <strong>html-game-builder</strong> — Create playable HTML games from descriptions</p><p>The agent follows best practices: based on user target, it uses the right skill, follows the skill’s workflow, and iterates until passing the success criteria.</p><p><strong>Full source code:</strong></p><p><a href="https://github.com/billpku/skilled-ralph-agents.git">GitHub - billpku/skilled-ralph-agents: A skill-driven autonomous agent system that iteratively improves outputs through self-evaluation loops</a></p><p><strong>Result Showcase:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTuwKHoEr-Vza0qfMtuPjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FdHjH3kOwizjZS6bETeQQ.png" /></figure><h3>5.Summary</h3><p>With ralph mode and skills, your agents not only work hard, but smart, then you can have more time to chill!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01d4713c0c4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeepAgents with (Claude)Skills in Action 2026]]></title>
            <link>https://medium.com/@yingbiao/deepagents-with-claude-skills-in-action-2026-adcc2d43a854?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/adcc2d43a854</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 19:06:37 GMT</pubDate>
            <atom:updated>2026-01-09T19:47:49.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>AI agents are systems that autonomously complete tasks by planning and executing commands.</p><p>Unlike standard LLMs that only generate text, agents can <strong>take action</strong> — running commands, modifying files, and using external tools.</p><p>This guide will help you understand:</p><ul><li>What is DeepAgent</li><li>What is Skill</li><li>Hand on to create Skill and let agent take action</li></ul><h3>1. What is DeepAgent?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtCpFxJ-WAdBdN1iZ3WYtQ.png" /></figure><p><a href="https://docs.langchain.com/oss/python/deepagents/overview"><strong>DeepAgents</strong></a> is a Python library built on LangGraph for creating task-oriented agents. But why use it instead of just calling an LLM with prompt directly?</p><p>The answer: <strong>DeepAgents lets agents take action on your behalf.</strong></p><p>A standard LLM can only generate text, but DeepAgents agents can:</p><ul><li><strong>Run shell commands</strong> — Execute yt-dlp, git, cd or any CLI tool</li><li><strong>Modify files</strong> — Create, edit, and manage files as a persistent memory</li><li><strong>Use APIs and MCP servers</strong> — Connect to external services and tools</li><li><strong>Plan with todos</strong> — Break complex tasks into steps and track progress</li></ul><p>Think of it as the difference between asking someone for directions versus having them drive you there.</p><p>DeepAgents agents don’t just tell you what to do — <strong>they do it.</strong></p><h3>2. What is Skill?</h3><p><a href="https://code.claude.com/docs/en/skills"><strong>Claude Skill</strong></a> is a folder containing a <strong>`SKILL.md`</strong> file with instructions the agent follows.</p><p>You may wonder, but why use Skills instead of just writing Python code?</p><blockquote><strong>Skills Work Like Restaurant Recipes</strong></blockquote><p>Imagine you run a restaurant. Every chef must follow the same recipe to ensure every dish tastes identical. You don’t want creativity in how the pasta is cooked — you want consistency.</p><p><strong>Skills are recipes for agents.</strong> They ensure the same workflow runs every time, producing consistent results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qtxy1cGUBnDGkkKmcb_fXw.png" /></figure><p>The key advantage of Skills: they leverage the agent’s ability to<strong> interpret user intent</strong>. If the user says “summarize this video” or “give me a TLDR of this clip”, the agent understands both mean the same thing and follows the skill accordingly.</p><p>Hardcoded solutions would need explicit handling for each variation.</p><p><strong>Skill Example<br></strong>Folder structure:</p><pre>skills/<br>└── youtube-tldr/<br>    └── SKILL.md</pre><p>The SKILL.md has YAML frontmatter and workflow instructions:</p><pre>---<br>name: youtube-tldr<br>description: Summarizes YouTube videos using yt-dlp<br>---<br><br># YouTube TLDR Skill<br>1. Download transcript with yt-dlp<br>2. Clean the text<br>3. Generate summary</pre><p>Following <a href="https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices"><strong>Anthropic’s progressive disclosure pattern</strong></a>, only metadata loads at startup — the full instructions load when the skill is invoked, with this way, the agent can smartly save the context window.</p><h3>3. Hands-On</h3><p>Now let’s put theory into practice. We’ll build a CLI tool that summarizes any YouTube video using a skill-guided agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viZx_LE9X6s3nCDNgaMWKg.png" /></figure><p><strong>Full source code</strong></p><p><a href="https://github.com/billpku/deepagents-youtube-tldr.git">GitHub - billpku/deepagents-youtube-tldr: YouTube TLDR Summarizer using DeepAgents with Skills pattern</a></p><p><strong>Result</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBvThhqYVwmxiu8K-7Bnww.png" /></figure><h3>Summary</h3><p>DeepAgents turns ideas into action. With Skills, your agents follow clear, repeatable workflows — delivering results, not just words.</p><p>Let your agents do more, write recipes, not scripts.</p><h3>Resources</h3><ul><li><a href="https://github.com/langchain-ai/deepagents">DeepAgents GitHub</a></li><li><a href="https://github.com/yt-dlp/yt-dlp">yt-dlp Tool</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adcc2d43a854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeepSeed-R1 Local API & Chatbot in Action]]></title>
            <link>https://medium.com/@yingbiao/deepseed-r1-local-api-chatbot-in-action-9efb6206fe18?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9efb6206fe18</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 00:05:39 GMT</pubDate>
            <atom:updated>2025-02-06T00:05:39.480Z</atom:updated>
            <content:encoded><![CDATA[<p>The rise of open-source reasoning models like DeepSeek-R1 enables developers to run powerful AI locally without relying on cloud services.</p><p>This technology has recently created a hype on the internet, and you may be wondering how to take advantage of this model locally.</p><p>This guide walks through 2 key scenarios:</p><ul><li><strong>For casual users: </strong>Creating a ChatGPT-like interface</li><li><strong>For developers: </strong>Integrating the model into applications via API</li></ul><p>Before starting, if you’re interested in learning about the background of DeepSeek-R1 to better understand the following process, check out my <a href="https://medium.com/@yingbiao/deepseed-r1-in-theory-beginner-friendly-25211c3113bf">DeepSeed-R1 in Theory(Beginner Friendly)</a></p><h3>🛠 Local Setup Essentials</h3><h3>1. Ollama Installation</h3><p>Install <a href="https://ollama.com/">Ollama</a> by downloading from their official website in <a href="https://ollama.com/download">HERE</a> for macOS M series or Windows, or use the command line for Linux:</p><pre>curl -fsSL &lt;https://ollama.com/install.sh&gt; | sh</pre><p>This installs the model runner with automatic GPU acceleration (Metal for Apple M-series, CUDA for NVIDIA).</p><p>Think of Ollama as a tool that helps you download the DeepSeek-R1 model and host it locally on your machine, allowing other applications to use this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCPPii2I31AQcPIzKjctsA.png" /></figure><h3>2. Download DeepSeek-R1</h3><p>Choose a model variant based on your hardware. You can find a list of DeepSeek-R1 versions at <a href="https://ollama.com/library/deepseek-r1">https://ollama.com/library/deepseek-r1</a>. These versions are smaller than the original DeepSeek-R1 model because they’re distilled versions — think of it like a teacher (the original model) passing knowledge to students (smaller models).</p><p>While these compact versions retain much of the original model’s capabilities, their smaller size allows for lower latency and reduced hardware requirements. Generally, larger models are more powerful, but for local hosting, choose one that fits your GPU’s capacity.</p><p>And fortunately, there’s a compact model, DeepSeek-R1-Distill-Qwen-1.5B, that uses only ~1GB VRAM and can even run on an M1 MacBook Air with 8GB memory. We’ll use this model as our example, but feel free to explore other larger models listed at <a href="https://ollama.com/library/deepseek-r1">https://ollama.com/library/deepseek-r1</a></p><p>Pull and host the DeepSeek-R1 model with Ollama with this commandline:</p><pre>ollama run deepseek-r1:1.5b # Balanced speed/quality (~1.1GB VRAM)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23exrr7bcuxd-eCezEa-rQ.png" /></figure><h3>📱 Scenario 1: ChatGPT-Style Interface</h3><p>If you want to experience the DeepSeek model as a ChatGPT-like chatbot, you can utilize the UI here — it works perfectly with the locally hosted Ollama model.</p><p>Deploy <a href="https://github.com/open-webui/open-webui">Open WebUI</a> for a user-friendly chatbot experience with <a href="https://docs.docker.com/engine/install/">docker</a>:</p><pre>docker run -d -p 3000:8080 -v ollama:/root/.ollama -v open-webui:/app/backend/data \\\\<br>--add-host=host.docker.internal:host-gateway --name open-webui ghcr.io/open-webui/open-webui:main</pre><p>Visit http://localhost:3000, create an account, and select deepseek-r1:1.5b from the model dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1Tr0v1mvPw2n2YCP876oQ.png" /></figure><p>Using a local LLM with the Chat UI offers several benefits:</p><ul><li>Easy access to try different open-source models</li><li>Offline and local chatting capabilities, allowing you to use ChatGPT-like services to boost productivity even without internet access</li><li>Enhanced privacy, since Ollama and Open WebUI keep all chat interactions local, preventing sensitive information leaks</li></ul><h3>💻 Scenario 2: API Integration for Developers</h3><p>If you have already hosted DeepSeek-R1 locally, as a developer, you can easily integrate with the model since Ollama exposes an OpenAI-compatible API at <a href="http://localhost:11434/v1.">http://localhost:11434/v1</a></p><h3>With OpenAI Python Client:</h3><pre>from openai import OpenAI</pre><pre>from openai import OpenAI<br><br># Configure the client to use Ollama&#39;s local endpoint <br>client = OpenAI(<br>base_url=&quot;http://localhost:11434/v1&quot;,  # Ollama server address     <br>api_key=&quot;no-api-key-needed&quot;,  # Ollama doesn&#39;t require an API key <br>)</pre><h3>With LangChain:</h3><pre>from langchain_ollama import ChatOllama</pre><pre># Configure the Ollama client to use local endpoint<br>llm = ChatOllama(<br>    base_url=&quot;http://localhost:11434&quot;,  # Ollama server address<br>    model=&quot;deepseek-r1:1.5b&quot;,  # Specify the model you host in Ollama<br>)</pre><p>All related code and setup can be find here:</p><p><a href="https://github.com/billpku/DeepSeek-R1-local-API-in-Action">GitHub - billpku/DeepSeek-R1-local-API-in-Action</a></p><h3>Summary</h3><p>Here’s a quick overview of the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHQdYhJ9VHka1KGOC47qRA.png" /></figure><p>With Ollama and DeepSeek-R1, you can now run powerful AI locally with GPU acceleration, access a ChatGPT-like interface through Open WebUI, and integrate AI capabilities into your applications using standard APIs — all while maintaining privacy and working offline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9efb6206fe18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeepSeed-R1 in Theory(Beginner Friendly)]]></title>
            <link>https://medium.com/@yingbiao/deepseed-r1-in-theory-beginner-friendly-25211c3113bf?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/25211c3113bf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 22:09:36 GMT</pubDate>
            <atom:updated>2025-01-31T23:23:09.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>DeepSeek R1 is a groundbreaking AI model that’s turning heads in the tech world with its remarkable blend of intelligence and efficiency. It’s designed to reason like humans and is the first AI to develop advanced reasoning capabilities purely through reinforcement learning, marking a significant milestone in AI development.</p><p>Let&#39;s break down what makes it special with some easy-to-understand Q&amp;A pairs.</p><h3>1. How Can I Use DeepSeed R1?</h3><ul><li><strong>Model Experience: </strong>If you want to instantly try this model as a chatbot similar to ChatGPT, you can use the DeepSeek official online chatbot <a href="https://chat.deepseek.com/">HERE</a> (when using it, remenber to click the <em>“DeepThink R1”</em> button)</li><li><strong>Local Hosting</strong>: For develper you can run smaller versions of the model (like 7B or 14B parameters) on your own machine using tools like <a href="https://ollama.com/">Ollama</a>. You can download the open-source model <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1">HERE</a>. <em>(I intend to develop a hands-on guide for this process in the future)</em></li><li><strong>Online Hosting:</strong> For business, some platforms ( <a href="https://blogs.nvidia.com/blog/deepseek-r1-nim-microservice/">Nvidia’s NIM</a> and <a href="https://aws.amazon.com/blogs/aws/deepseek-r1-models-now-available-on-aws/">AWS</a> already host R1 model. You can directly integrate with their API</li><li><strong>Model Reproduction:</strong> For researchers interested in the technical details, you can find the DeepSeek technical documentation <a href="https://arxiv.org/pdf/2501.12948">HERE</a>. While the documentation doesn’t cover every training detail, you can follow this project <a href="https://github.com/huggingface/open-r1">HERE</a> to see how community try to reproduce the whole process.</li></ul><h3>2. Is DeepSeed R1 Just Another Chatbot?</h3><p><strong>Yes</strong> and <strong>no</strong>.</p><p><strong>Yes</strong> — it generates answers based on given questions and context, processing responses token by token like other language models.</p><p><strong>No</strong> <strong>— it’s a “Thinking Partner.”</strong> This is a special kind of <strong>reasoning model</strong>. Imagine having a teacher who doesn’t just give answers but walks you through <em>every step</em> of their thinking.</p><p>Here’s the difference between chat models and reasoning models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnxLedFRTtJR-bTZRBJ1oQ.png" /></figure><h3>3. How Was DeepSeed R1 Trained?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOVgnb_WsQRNYHD8DNbiQg.png" /></figure><p>Let’s explore the sophisticated training process behind DeepSeek R1. The process transforms the chat model (DeepSeek-V3) into a reasoning model by developing its logical thinking abilities.</p><h3>Phase 1: Cold Start SFT</h3><p>In this process, will use SFT (Supervised Fine-Tuning) to help the base model (DeepSeek-V3) establish basic reasoning patterns and readable formatting through learning labeled data.</p><p><strong>SFT (Supervised Fine-Tuning):</strong> Imagine teaching a student by showing them question and answer pairs. The AI learns by studying high-quality examples with step-by-step solutions, improving its abilities through carefully crafted examples.</p><p>In this stage, researchers will focus on:</p><ul><li>Curating detailed Chain-of-Thought examples with clear formatting</li><li>Training the model to separate reasoning processes from final answers</li><li>Fixing language mixing issues that happened in DeepSeed-R1-Zero</li></ul><h3>Phase 2: Reasoning-Oriented RL</h3><p>In this process, the model will maximize its mathematical and coding accuracy through trial-and-error using the <strong>Reinforcement Learning</strong> (RL) method.</p><p><strong>Reinforcement Learning</strong> (RL): Think of it like teaching a pet new tricks:</p><ul><li><strong>Learning by Doing:</strong> Just as a puppy learns to “sit” through treats and praise, the AI learns by trying things out and getting “rewards” for good answers</li><li><strong>Trial and Error:</strong> Like how a child learns to ride a bike by falling and getting back up, the AI improves by making mistakes and learning from them</li><li><strong>Reward System:</strong> Guides the model to distinguish right from wrong</li></ul><p>This makes DeepSeek R1 special because it learned complex reasoning naturally through experience, rather than just <em>memorizing answers</em>. Similar to how <a href="https://deepmind.google/discover/blog/alphago-zero-starting-from-scratch/">Google’s AlphaGo </a>used reinforcement learning to master the game of Go, DeepSeek R1 develops its reasoning abilities through repeated interactions and feedback, learning from millions of iterations to discover effective problem-solving strategies.</p><h3>Phase 3: Rejection Sampling + Multi-Domain SFT</h3><p>In this phase, the model expands its capabilities beyond pure reasoning by learning from other domains.</p><p>To create the learning data, the RL model first generates 600K high-quality responses through <strong>rejection sampling</strong> (keeping only correct/readable outputs), then combines these with 200K examples covering:</p><ol><li>General capability data (writing, Q&amp;A, translation)</li><li>Safety-aligned responses</li><li>Multi-turn conversation examples</li></ol><p>The model then learns from this combined dataset, similar to phase 1. This process provides several benefits:</p><ul><li>Balances reasoning strength with general usability</li><li>Maintains base model’s knowledge retention</li><li>Filters out chaotic/mixed-language responses</li></ul><h3>Phase 4: Final Alignment</h3><p>In this phase, the model output is tuned to align with human preferences.</p><p>The final <strong>reinforcement learning</strong> considers:</p><ul><li>Helpfulness</li><li>Harmlessness (full response safety)</li><li>Reasoning accuracy</li></ul><p>This process uses a combination of:</p><ul><li>Rule-based rewards for technical tasks</li><li>Neural reward models for subjective quality</li><li>Diverse prompt distribution covering all scenarios</li></ul><p>Then after all the 4 phases, we will get the DeepSeek-R1 reasoning model that we are using now, here is the summary for these processes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5nFUB1nnBrMqSxkp4bTuQ.png" /></figure><p>Terminology explained:</p><ul><li><strong>CoT</strong>: Chain-of-Thought — Breaking down problems step-by-step</li><li><strong>GRPO</strong>: Group Relative Policy Optimization, which helps avoid the need for a separate critic model, prevents reward hacking, and enables the natural emergence of reflection and verification behaviors in RL process</li><li><strong>RLHF</strong>: Reinforcement Learning with Human Feedback — Aligning to human preferences</li></ul><h3>4. Key Findings About this Research</h3><p><strong>a. No Training Wheels</strong></p><p>Unlike most models that need pre-labeled data, when training DeepSeek-R1-Zero, the team made the model learn reasoning <em>purely through trial and error</em> (RL). This marks the first time reinforcement learning has successfully trained LLMs. Think of it as learning to ride a bike without stabilizers.</p><p><strong>b. Distillation Magic</strong></p><p>After training the DeepSeek-R1 model, the team successfully distilled its knowledge into multi smaller models(like: <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-7B">DeepSeek-R1-Distill-Qwen-7B</a>, <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B">DeepSeek-R1-Distill-Llama-8B</a>).</p><p><strong>Distillation Model:</strong> This process allows smaller models to learn from the larger model by studying its inputs and outputs — similar to how students learn from a teacher’s examples. Through this method, the smaller models can perform well while requiring less computing power for training and inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVZz5-NeabZ5NH9n8ENdjQ.png" /></figure><p>When comparing distillation versus reinforcement learning for improving small model performance, DeepSeek found that the distillation method proved to be a more efficient approach for enhancing small model performance. <strong><em>And I personally think this is the most crucial discovery for the R1 model reseach</em></strong></p><h3>5. DeepSeed R1 vs. Zero vs. V3: What’s the Difference?</h3><ul><li><strong>DeepSeed R1 Zero</strong>: The “rough draft” trained purely through reinforcement learning (RL). The model didn’t learn from labeled data and was powerful but messy (e.g., mixed languages in answers). The RL techniques developed in this model inspired the training for <strong>DeepSeed R1</strong></li><li><strong>DeepSeed V3</strong>: The base model that R1 builds upon. It’s a chat model similar to OpenAI GPT4o. During training, the team utilized <a href="https://arxiv.org/pdf/2412.19437">various engineering techniques</a> to improve its performance while keeping costs low</li><li><strong>DeepSeed R1</strong>: The polished version — better structured, safer, with enhanced reasoning capabilities, suitable for multiple scenarios</li></ul><h3>6. Why Is DeepSeed R1 Creating Such Hype?</h3><p>This model is the <strong>“David vs. Goliath”</strong> of AI:</p><ul><li><strong>Budget Smarts: </strong>The company claimed that training this R1 model used less than 10% of the budget of giants like OpenAI.</li><li><strong>Open-Source Edge: </strong>Unlike closed-source models, you can host it locally while maintaining high quality. They also open-source many small models that can run on your PC or Mac, making it ideal for privacy-focused apps or niche tasks.</li><li><strong>Benchmark Beast: </strong>Achieves performance on par with <a href="https://openai.com/o1/">OpenAI&#39;s O1</a> model on benchmarks, while being significantly more cost-effective too.</li></ul><h3>Summary</h3><p>DeepSeed R1 isn’t just another AI — it’s a leap toward machines that <em>think</em>, not just respond. Whether you’re a developer or a curious user, its open-source nature and reasoning prowess make it a tool worth exploring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25211c3113bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent Flow with LangGraph in Action]]></title>
            <link>https://medium.com/@yingbiao/agent-flow-with-langgraph-in-action-01b7531b5ee9?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/01b7531b5ee9</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 18:52:53 GMT</pubDate>
            <atom:updated>2025-01-19T20:08:20.362Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The concept of AI agents has gained significant popularity recently, particularly in how Large Language Models (LLMs) can be leveraged for reasoning and action-taking.</p><p>In this article, I’ll demonstrate how to build an intelligent agent using <a href="https://www.langchain.com/langgraph"><strong>LangGraph</strong></a>. By the end of this article, you’ll understand:</p><ul><li>Core concepts of Agent-based workflows</li><li>How to build an agent with action flows using LangGraph</li></ul><h3>Agent Flow</h3><p>When building LLM-powered AI features, we often have a clear process in mind. To ensure our agent follows this process precisely, we can implement an agent flow.</p><p>Think of an agent flow as a structured, step-by-step approach to problem-solving. This framework allows us to guide the agent through predefined processes to reach solutions systematically.</p><p>Building an agent flow is similar to creating a process workflow. Here are the basic concepts you need to understand when building agent flows with LangChain.</p><p><strong>Basic Components</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfsk1Zq6aAPf048xgniMQg.png" /></figure><ul><li><strong>Start</strong>: The entry point where the process begins</li><li><strong>Node</strong>: Individual process units that function as discrete steps in LangGraph</li><li><strong>Edge</strong>: Connections between nodes that maintain the process order</li><li><strong>Conditional Edge</strong>: A specialized edge that routes to different nodes based on specific conditions (e.g., Route to X when condition A is met, route to Y when condition B is met), adding flexibility to the flow</li><li><strong>End</strong>: The terminal point where the process concludes</li><li><strong>State</strong>: The context passed between different nodes, managing how information is updated and maintained throughout the flow</li></ul><p><strong>Creating an Agent Flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHQBFidbhgtAiN2jV74GRQ.png" /></figure><p>To build an effective agent flow in LangGraph, follow these steps:</p><ol><li>Design your action flow diagram, detailing:</li></ol><ul><li>The action of each step</li><li>Data flow between steps</li></ul><p>2. Develop the technical components:</p><ul><li>Define the state structure</li><li>Create functions for each process step</li></ul><p>3. Construct the agent flow by connecting nodes with appropriate edges</p><p>This structured approach ensures your agent operates in a predictable and efficient manner.</p><h3>Step-by-Step Code Explanation</h3><p>Let me walk you through the process of building an agent flow with LangGraph. We’ll create <a href="https://github.com/billpku/Agent_Flow_with_LangGraph_in_Action">an intelligent agent that plays “Rock Paper Scissors”</a> against two human players, using strategy to try to win!</p><p><a href="https://github.com/billpku/Agent_Flow_with_LangGraph_in_Action">GitHub - billpku/Agent_Flow_with_LangGraph_in_Action</a></p><h3>Game Process</h3><p>Our “Rock Paper Scissors” agent will follow this flow:</p><ol><li>Receive player inputs</li><li>Check for game termination signal</li><li>Generate agent’s move based on:</li></ol><ul><li>Previous game choices</li><li>Historical results</li><li>Pattern recognition of player behavior</li></ul><p>4. Determine the round’s winner</p><p>5. Continue gameplay until players send “end”</p><h3>State Structure</h3><p>Here’s our state definition that tracks all necessary data throughout the game:</p><pre># Define state management<br>class GameState(TypedDict):<br>    session_id: str  # UUID for each game session<br>    history: List[Dict]  # [{round: n, choices: {}, winner: str, timestamp: str}]<br>    current_round: Dict  # {player1: choice, player2: choice, agent: None}<br>    scores: Dict  # {player1: wins, player2: wins, agent: wins}<br>    is_active: bool  # True until END received</pre><p>This state structure maintains the game’s progress, tracks player choices, and records the game’s history for strategic decision-making.</p><p>Graph Structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*Eu3wqNrZHvJ_yncmVJRvcQ.png" /></figure><p>The agent flow is composed of interconnected nodes, where each node represents a function in our game logic. To maintain consistency and ease of use, each node function takes a state as input and returns an updated state.</p><p>Let’s examine one of our nodes: process_human_choices. This node handles player input validation and checks for game termination.</p><pre>def _player_1_choice_real(state: GameState) -&gt; Union[GameState, str]:<br>    &quot;&quot;&quot;Get player 1&#39;s choice from terminal input&quot;&quot;&quot;<br>    while True:<br>        print(&quot;\nChoose your move Player 1:&quot;)<br>        for key, move in CHOICES_MAP.items():<br>            print(f&quot;{key}: {move}&quot;)<br>        choice = input(&quot;Enter choice number (or END): &quot;).strip()<br><br>        if choice.lower() == &quot;end&quot;:<br>            state[&quot;current_round&quot;][&quot;player1&quot;] = &quot;END&quot;<br>            return state<br><br>        if choice in CHOICES_MAP:<br>            state[&quot;current_round&quot;][&quot;player1&quot;] = CHOICES_MAP[choice]<br>            return state<br>        print(&quot;Invalid choice! Please select a valid number or END&quot;)<br><br><br>def _player_2_choice_real(state: GameState) -&gt; Union[GameState, str]:<br>    &quot;&quot;&quot;Get player 2&#39;s choice from terminal input&quot;&quot;&quot;<br>    while True:<br>        print(&quot;\nChoose your move Player 2:&quot;)<br>        for key, move in CHOICES_MAP.items():<br>            print(f&quot;{key}: {move}&quot;)<br>        choice = input(&quot;Enter choice number (or END): &quot;).strip()<br><br>        if choice.lower() == &quot;end&quot;:<br>            state[&quot;current_round&quot;][&quot;player2&quot;] = &quot;END&quot;<br>            return state<br><br>        if choice in CHOICES_MAP:<br>            state[&quot;current_round&quot;][&quot;player2&quot;] = CHOICES_MAP[choice]<br>            return state<br>        print(&quot;Invalid choice! Please select a valid number or END&quot;)<br><br><br>def process_human_choices(state: GameState) -&gt; Union[GameState, str]:<br>    &quot;&quot;&quot;Process and validate human player choices&quot;&quot;&quot;<br>    # Get real player choices instead of mock choices<br>    state = _player_1_choice_real(state)<br>    state = _player_2_choice_real(state)<br><br>    # Check for END condition (if any player chooses END)<br>    if &quot;END&quot; in [state[&quot;current_round&quot;][&quot;player1&quot;], state[&quot;current_round&quot;][&quot;player2&quot;]]:<br>        state[&quot;is_active&quot;] = False<br>        return state<br><br>    # Validate moves<br>    for player in [&quot;player1&quot;, &quot;player2&quot;]:<br>        choice = state[&quot;current_round&quot;][player]<br>        if choice not in VALID_MOVES:<br>            raise ValueError(f&quot;Invalid move {choice} from {player}&quot;)<br><br>    return state</pre><p>This node demonstrates how we:</p><ul><li>Collect choices from both players</li><li>Check for game termination signals</li><li>Validate move legality</li><li>Update and return the game state</li></ul><p>Each node in our graph follows a similar pattern, taking the current state, performing its specific function, and returning the updated state to the next node in the flow.</p><h3>Build Graph</h3><p>After creating our node functions, we can construct the complete game flow by connecting nodes with edges. Here’s how we build our game graph:</p><pre># Function that work for routing the next step in condtion edge<br>def decision_if_end(state: GameState) -&gt; str:<br>    &quot;&quot;&quot;Decision if END is received&quot;&quot;&quot;<br>    if state[&quot;is_active&quot;]:<br>        return &quot;agent_decision&quot;<br>    else:<br>        return &quot;END&quot;<br><br><br>def create_workflow(memory: SqliteSaver):<br>    &quot;&quot;&quot;Create and return the workflow graph&quot;&quot;&quot;<br>    # Build graph<br>    workflow = StateGraph(GameState)<br><br>    # Add nodes<br>    workflow.add_node(&quot;process_human_choices&quot;, process_human_choices)<br>    workflow.add_node(&quot;agent_decision&quot;, agent_decision)<br>    workflow.add_node(&quot;analyze_result&quot;, analyze_result)<br><br>    # Add edges with data transformations<br>    workflow.add_edge(&quot;agent_decision&quot;, &quot;analyze_result&quot;)<br>    workflow.add_edge(&quot;analyze_result&quot;, &quot;process_human_choices&quot;)<br><br>    # Add conditional edge for END<br>    workflow.add_conditional_edges(<br>        &quot;process_human_choices&quot;,<br>        decision_if_end,<br>        {&quot;END&quot;: END, &quot;agent_decision&quot;: &quot;agent_decision&quot;},<br>    )<br><br>    # Set entry point<br>    workflow.set_entry_point(&quot;process_human_choices&quot;)<br><br>    return workflow.compile(store=memory)</pre><p>This graph structure creates a continuous game loop that:</p><ol><li>Processes player choices</li><li>Makes strategic agent decisions</li><li>Analyzes game results</li><li>Either continues the game or ends based on player input</li></ol><p>The conditional edge ensures our game can gracefully exit when players choose to end the session.</p><h3>Result</h3><p>Here are the results from playing with the agent. As you can see, it performed not bad!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*NVFowCCdbHGX-VuMze_lPA.png" /></figure><h3>Summary</h3><p>By leveraging LangGraph, we can easily create an agent that not only follows the predefined process but also has the flexibility to make decisions based on context.</p><p>Hope you enjoy it and feel free to leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01b7531b5ee9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tune LLM in Action: Mixtral-8x7B]]></title>
            <link>https://medium.com/@yingbiao/fine-tune-llm-in-action-mixtral-8x7b-bb9caba22cb4?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb9caba22cb4</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 21:02:06 GMT</pubDate>
            <atom:updated>2024-03-04T21:56:26.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>Fine-tuning LLMs, such as Mixtral-8x7B, is key to excelling in NLP tasks by tailoring them with custom datasets for specific fields like finance or health.</p><p>This article will cover:</p><ul><li>Essential fine-tuning concepts and techniques.</li><li>How to fine-tune Mixtral-8x7B with <a href="https://ludwig.ai/latest/">Ludwig</a> for domains like health.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dignczU9mwUhoHTjStJ4cQ.png" /></figure><h3>Mixtral-8x7B</h3><p><a href="https://mistral.ai/news/mixtral-of-experts/">Mixtral-8x7B</a> is a cutting-edge open-source language model that excels in generating text. It outperforms or matches other leading models like Llama 2 70B and GPT-3.5 in most benchmarks.</p><p>Mixtral-8x7B’s key features include:</p><ul><li><strong>Sparse Mixture of Experts (SMoE)</strong>: Incorporates multiple “expert” layers, allowing for sophisticated pattern learning with relatively low computational costs.</li><li><strong>Efficient Inference</strong>: Despite its large parameter count, Mixtral-8x7B achieves faster inference, comparable to smaller models, due to its selective parameter activation</li><li><strong>Long Context Lengths</strong>: Capable of handling up to <strong>32k</strong> tokens, making it suitable for tasks requiring extensive context</li><li><strong>Multilingual Capabilities</strong>: Demonstrates strong performance in multiple languages, including English, French, Italian, German, and Spanish</li></ul><h3>Why Fine-Tuning Matter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPTKVfsf9zUBJbNV9nZ3TQ.png" /></figure><p>LLMs are trained on diverse and extensive data. However, without fine-tuning, they may lack the domain-specific knowledge required for certain tasks.</p><p>Fine-tuning adjusts the model’s parameters to learn from task-specific data, allowing it to produce more accurate and relevant outputs for specialized applications.</p><p>Since the parameters of LLMs are extensive, various techniques are used to improve efficiency. The two most popular techniques are:</p><ul><li><strong>Quantization</strong></li><li><strong>LoRA</strong></li></ul><h3>Quantization: Boosting Efficiency</h3><p>Quantization is a technique that reduces the precision of the model’s parameters, thereby decreasing memory consumption and computational demand without significantly sacrificing performance.</p><p>For instance, when fine-tuning Mixtral-8x7B, we can reduce the model’s size by changing its 32-bit floating-point numbers (the standard way of storing model parameters) to 8-bit integers. This process can make the model <strong>4X smaller</strong>, saving memory and improving computational efficiency.</p><h3>LoRA: Enhancing Adaptability</h3><p><a href="https://arxiv.org/abs/2106.09685">Low-Rank Adaptation (LoRA) </a>is a novel approach to efficiently fine-tune pre-trained models for specific tasks without the need to extensively retrain the entire model. LoRA achieves this by introducing small, trainable adjustments to certain parts of the model.</p><p>This method allows the model to quickly adapt to new tasks while preserving the vast knowledge it has already acquired, making it a cost-effective and resource-efficient way to enhance the model’s performance on targeted applications.</p><p><strong>For instance</strong>, imagine you have a well-trained <strong>soccer player</strong> who’s great at playing in any position on the field. Now, you want this player to become especially good at scoring goals. Instead of starting their training from scratch, you give them specific exercises that improve their goal-scoring skills.</p><p>This is what LoRA does for fine-tuning LLMs!</p><h3>Code Explanation</h3><p>I will show case how to fine-tuning Mixtral-8x7B with health realted knowledge. <strong>The source code is here:</strong></p><p><a href="https://github.com/billpku/Fine-Tune-LLM-in-Action-Mixtral-8x7B">GitHub - billpku/Fine-Tune-LLM-in-Action-Mixtral-8x7B</a></p><h3>Step1: Loading the Dataset</h3><p>We begin by preparing our dataset, <a href="https://www.kaggle.com/datasets/jpmiller/layoutlm">MedQuAD</a>, setting the stage for healthcare-specific learning.</p><pre>data_set = &quot;data/medquad.csv&quot;</pre><h3>Step2: Fine-Tuning with Ludwig</h3><p>We will fine-tune the Mixtral-8x7B<strong> </strong>with <a href="https://ludwig.ai/latest/">Ludwig</a>.</p><p>Ludwig is an open-source framework that simplifies the fine-tuning of LLMs. The library’s benefits include:</p><ul><li><strong>Declarative YAML Configurations</strong>: Define model architecture and training processes in an easy-to-understand YAML format, making machine learning accessible without extensive coding.</li><li><strong>Efficient Fine-Tuning</strong>: Incorporates techniques like Low-Rank Adaptation (LoRA) and Quantization to fine-tune models effectively on standard hardware.</li><li><strong>Versatile Applications</strong>: Suitable for a range of NLP tasks, from text generation to predictive modeling, with support for generative and predictive fine-tuning.</li></ul><p>The <a href="https://github.com/billpku/Fine-Tune-LLM-in-Action-Mixtral-8x7B/blob/main/yaml_config/Mixtral-8x7B-Instruct-v0.1-health.yaml"><strong>.yaml</strong></a> configuration file, which plays a pivotal role in fine-tuning the Mixtral-8x7B model. Here&#39;s a breakdown of some key components for this task:</p><h3>model_type and base_model</h3><pre>model_type: llm<br>base_model: mistralai/Mixtral-8x7B-Instruct-v0.1</pre><p>Specifies the type of model to be fine-tuned and the base pre-trained model from Hugging Face Hub. <strong>Mixtral-8x7B-Instruct-v0.1</strong> is chosen for its proficiency in instruction-based tasks.</p><h3>quantization</h3><pre>quantization:<br>  bits: 4</pre><p>Reduces the model’s size and speeds up inference by quantizing the model weights to 4 bits, making the model more efficient without significant loss in performance.</p><h3>adapter</h3><pre>adapter:<br>  type: lora</pre><p>Incorporates the Low-Rank Adaptation (LoRA) technique, a method that fine-tunes large language models with minimal additional parameters. <br>LoRA adjusts the self-attention mechanism, enhancing the model’s adaptability to healthcare nuances without overhauling its pre-trained knowledge.</p><h3>prompt</h3><pre>prompt:<br>  template: &gt;-<br>    ### Instruction: {instruction}<br>    ### Response:</pre><p>Defines a prompt template to guide the model during training and inference. This structured approach helps the model understand the context of healthcare queries better, leading to more accurate and relevant responses.</p><p>By configuring Mixtral-8x7B with this YAML file, we can fine-tune the model specifically for healthcare querie.</p><pre>from ludwig.api import LudwigModel<br>from ludwig.hyperopt.run import hyperopt<br>import logging<br><br># The config file is a YAML file that specifies the model architecture and the parameters for training<br>config_path = &#39;Mixtral-8x7B-Instruct-v0.1-health.yaml&#39;<br>model = LudwigModel(config=config_path, logging_level=logging.INFO)<br>results = model.train(dataset=data_set)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4sa26lEdZm0qrbSf3zCSg.png" /></figure><h3>Summary</h3><p>Fine-tuning LLMs like Mixtral-8x7B with techniques such as quantization and LoRA enhances their efficiency and adaptability for advanced NLP tasks.</p><p>Hope you enjoy it and feel free to leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb9caba22cb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chatbot with LLM and RAG in Action]]></title>
            <link>https://medium.com/@yingbiao/chatbot-with-llm-and-rag-in-action-575382df4323?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/575382df4323</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 19:11:40 GMT</pubDate>
            <atom:updated>2024-03-04T21:49:58.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Hello friends, in this article I will guild you through creating a cutting-edge chatbot for recommender with the power of LLM and with advanced retrieval technology to handle complex questions with ease.</p><p>By the end, you’ll learn how to:</p><ul><li>Build vector space for RAG</li><li>Build Chatbot power with LLM using LangChain</li><li>Make chatbot’s decison smarter with Agent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTolrWxeJplZnIWlVcbvxQ.png" /></figure><h3>Large Language Models (LLMs)</h3><p>LLMs, such as <a href="https://openai.com/research/gpt-4">GPT-4</a>, <a href="https://llama.meta.com/">Llama 2</a>, <a href="https://mistral.ai/news/mixtral-of-experts/">Mixtral <strong>8x7B</strong></a><strong>,</strong> have revolutionized the way machines understand and interact with human language. Think of LLMs as the chatbot’s <strong>brain</strong>, capable of deep understanding and generating human-like responses.</p><h3>Retrieval-Augmented Generation (RAG)</h3><p>RAG acts as a <strong>bridge</strong>, combining the creative response generation of models with the precision of retrieval-based methods, ensuring chatbots can source and integrate external information for more accurate responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zIYIh8BwufEnQngii8lfA.png" /></figure><h3>Traditional Chatbot Process vs. Chatbot + LLM</h3><p>Traditional chatbots often rely on scripted responses, limiting their flexibility. LLM integration expands their capabilities, enabling a dynamic and contextual conversation.</p><p>Imagine traditional chatbots as <strong>librarians</strong> limited to their own knowledge, answering only from what they’ve <strong>learned</strong>.</p><p>In contrast, LLM-enhanced chatbots are like librarians with access to <strong>every</strong> <strong>book</strong> in the whole library, providing wider-ranging and more detailed assistance.</p><h3>Chatbot vs. Chatbot + RAG</h3><p>Chatbots without RAG are limited to responding based on their pre-existing knowledge, which can lead to incorrect or “<a href="https://en.wikipedia.org/wiki/Hallucination_(artificial_intelligence)"><strong>hallucinated</strong></a>” answers when faced with unfamiliar questions. This means they might guess the answer, often resulting in unreliable responses.</p><p>On the other hand, chatbots enhanced with RAG can access and use external information to answer questions. This capability allows them to provide more accurate and reliable responses, even for questions outside their initial training data. <br>By integrating RAG, chatbots become more versatile and dependable for users seeking information.</p><p>Imagine Chatbot + RAG are like librarians not only read all the book in the library, but in the middle of your conversation, can <strong>instantly</strong> fetch and read any relative info in <strong>everywhere</strong> to answer your questions.</p><p>That’s the <strong>power</strong> of RAG!</p><h3>Step-by-Step Code Explanation</h3><p>Next, I will show you the proecss in buiding a book and movie recommender chatbot using Python, LangChain, embedding-based retrieval strategies, and OpenAI’s GPT-3.5.<br><strong>The source code is here:</strong></p><p><a href="https://github.com/billpku/Chatbot_LLM_RAG_in_Action">GitHub - billpku/Chatbot_LLM_RAG_in_Action</a></p><h3>Preparation of the Corpus:</h3><p>The foundation of any RAG system is a robust and comprehensive corpus.</p><p>For this chatbot, movie and book data were meticulously formatted into JSON, ensuring each entry had a unique ID, title, summary and etc. This standardized format facilitates efficient data retrieval and processing.</p><p>My data were based on the the CMU’s corpus:</p><ul><li><a href="https://www.kaggle.com/datasets/ymaricar/cmu-book-summary-dataset">BookSummary</a></li><li><a href="https://www.cs.cmu.edu/~ark/personas/">MovieSummary</a></li></ul><h3>Building the Vector Store for Retrieval</h3><p>To enhance a chatbot’s ability to search semantically similar content, we create embeddings for each item in the corpus. These embeddings are generated using sentence embedding models, such as the one from Hugging Face, and are indexed using FAISS for fast retrieval.</p><p><strong>Generating Embeddings</strong></p><p>First, we convert the content into embeddings using a sentence embedding model. This allows the chatbot to perform semantic similarity searches. Here’s how to generate embeddings using the Hugging Face model:</p><pre>from langchain.embeddings import HuggingFaceEmbeddings<br><br>embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)</pre><p><strong>Storing and Retrieving Embeddings</strong></p><p>Next, we need a service like FAISS to store these embeddings and retrieve the most similar ones based on user input. FAISS simplifies the storage and retrieval process for both book and movie recommendations. Here’s how to create, save, and load a FAISS store:</p><pre>from langchain.vectorstores import FAISS<br><br># Create FAISS store from document<br>vector_store = FAISS.from_documents(document, self.embeddings)<br># Save the space<br>vector_store.save_local(save_path)<br># Load the space, with embeddings<br>vector_store = FAISS.load_local(save_path, embeddings)</pre><h3>Chatbot Logic and User Interaction:</h3><p>At its core, the chatbot is designed to interpret user queries, retrieve pertinent information, and generate responses that incorporate this information. <br>This involves converting queries into embeddings, searching the corpus, and then using GPT-3.5 to craft a final response that integrates both the retrieved data and the model’s generative output.</p><p><strong>Using GPT-3.5 for Dynamic Responses</strong></p><p>We employ GPT-3.5 to power our chatbot, enabling it to anticipate user needs and craft answers using our curated content.</p><pre>import os<br>from langchain.chat_models import ChatOpenAI<br><br>openai_api_key = os.getenv(&quot;OPENAI_API_KEY&quot;, &quot;YOUR_API_KEY&quot;)<br>chat = ChatOpenAI(<br>    openai_api_key=openai_api_key,<br>    model=&#39;gpt-3.5-turbo&#39;,<br>    temperature=0.0, # Set 0.0 for consistent reply, easy to debug in dev<br>)</pre><p><strong>Intent Classification with GPT-3.5</strong></p><p>To understand whether a user is inquiring about books, movies, or other topics, we utilize GPT-3.5’s advanced zero-shot learning capabilities for classification.</p><pre>class TopicClassifier:<br>    def __init__(self, llm):<br>        self.llm = llm<br>        self.topics = [&quot;movies&quot;, &quot;books&quot;, &quot;others&quot;]<br><br>    def classify(self, query):<br>        prompt = f&quot;Classify the following question into one of these topics: &#39;{&#39;,&#39;.join(self.topics)}&#39;: &#39;{query}&#39;&quot;<br>        response = self.llm.predict(text=prompt, max_tokens=10)<br>        topic = response.strip().lower()<br>        return topic</pre><p><strong>Tailoring the Chatbot’s Response with RAG</strong></p><p>After we know the user intention, we will trigger different process:</p><ul><li>Movies, LLM reply the user based on it knowldege and relvente info from our movie corpus</li><li>Books, LLM reply the user based on it knowldege and relvente info from our book corpus</li><li>Others, LLM reply the user based on it knowldege</li></ul><p>With the langChain agent, we can easy to decide this process</p><pre>from langchain.memory import ConversationBufferMemory<br>from langchain.agents import ConversationalChatAgent, AgentExecutor<br><br>class ChatAgent:<br>    def __init__(self, llm, tool_manager):<br>        self.llm = llm<br>        self.tool_manager = tool_manager<br>        self.memory = ConversationBufferMemory(memory_key=&quot;chat_history&quot;,input_key=&quot;input&quot;, return_messages=True)<br>        self.agent = ConversationalChatAgent.from_llm_and_tools(llm=self.llm, tools=list(self.tool_manager.tools.values()), system_message=&quot;You are a smart assistant whose main goal is to recommend amazing books and movies to users. Provide helpful, short and concise recommendations with a touch of fun!&quot;)<br>        self.chat_agent = AgentExecutor.from_agent_and_tools(agent=self.agent, tools=list(self.tool_manager.tools.values()), verbose=True, memory=self.memory)<br>    def get_response(self, query, topic_classifier):<br>        topic = topic_classifier.classify(query)<br>        tool_name = None if topic == &quot;other&quot; else topic.capitalize() + &quot;Tool&quot;<br>        try:<br>            response = self.chat_agent.run(input=query, tool_name=tool_name) if tool_name else self.llm.generate(prompt=query)<br>        except ValueError as e:<br>            response = str(e)<br>        return {&quot;answer&quot;: response}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhAm-EGeQ9I9CwueB6apuQ.png" /></figure><p>Depending on what you ask, it either fetches the most relevant movie or book details from its database or crafts a direct response on its own. This flexibility ensures you get precise and engaging answers every time.</p><h3>Summary</h3><p>By combining the understanding capabilities of LLMs with the vast knowledge access provided by RAG, we’ve created a chatbot that’s not just a tool but a companion ready to explore the world of books and movies with you.</p><p>Hope you enjoy it and feel free to leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=575382df4323" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPT-3.5 in Action: Call GPT API]]></title>
            <link>https://medium.com/@yingbiao/gpt-3-5-in-action-call-gpt-api-33157169794f?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/33157169794f</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 15:12:55 GMT</pubDate>
            <atom:updated>2024-03-04T21:48:27.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>GPT-3.5 is the backend model of the chatGPT service. It is an advanced language model that has the ability to generate human-like text, answer questions, and perform a variety of NLP tasks with impressive accuracy.</p><p>In this post, we will share how to call it:</p><ul><li>Using the OpenAI library</li><li><strong>(Recommended)</strong>HTTP POST requests</li></ul><p>The code for the post can all be found here:</p><p><a href="https://github.com/billpku/GPT3.5-in-Action">GitHub - billpku/GPT3.5-in-Action</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSMZsVagjiMbu4XV_0Ct0g.png" /></figure><h3>Call GPT-3.5 with OpenAI library</h3><p>Here, I will show you how to use OpenAI library(version: 0.27.4) in python to call the GPT-3.5 API.</p><p>Before we start, I will assert that you alreadly have a a avabile OpenAI key, which start with “sk-”.</p><p>There are 3 steps to use the call GPT-3.5 service with OpenAI library:</p><ul><li>Set up api key, model, temperature</li><li>Set up message with roles</li><li>Get response</li></ul><p><strong>1.Set up api key, model, temperature</strong></p><p>Api key, as we talked before, it is contained in the OpenAI account, when you have a avaiable OpenAI account(for new openai user, you have free 18$ in three month time).</p><p>The molde is “gpt-3.5-turbo”, which is GPT-3.5 we will call</p><p>Tempeture is an optional parameter, it is in range of 0 to 1, the bigger the value the more creative the bot will be. <br>If you want the bot to answer conservative, set it lower, like: 0.4, if you want the bot try answer the question in more detail(may be wrong), set it highly like:0.9. You can test it based on your preference.</p><p>Here is the code block:</p><pre>import openai<br><br># Set up YOUR OpenAI API key<br>openai.api_key = &quot;sk-XXXXXXXXXXXXXXXX&quot;<br># Set MODEL to &quot;gpt-3.5-turbo&quot;<br>model = &quot;gpt-3.5-turbo&quot;<br># Set temperature to 0.9, it can be from 0~1, 0 is the most conservative, 1 is the most creative<br>temperature = 0.9</pre><p><strong>2.Set up message with roles</strong></p><p>Since GPT-3.5 is a backend of chatGPT, the famouse usage with GPT-3.5, is use it like a chat bot. We can define 3 kinds of role when we send message to call the api, the roles are introduced as below:</p><ul><li><strong>system</strong>, the instruction we give to the robot first, tell he/she what to do and how to do</li><li><strong>user, </strong>the content we send to the robot, like the question we will ask</li><li><strong>(Optional)assistant</strong>, the robot’s response</li></ul><p>Now, I will take a translation task as an example to show you how to use the API. The task is to translate the following sentence from English to Japanese.</p><p>Imagine that you want the bot to help us translate the English to Japanese, we must firstly tell the bot:</p><ul><li>who she is</li><li>what she can do</li><li>And how does she do</li></ul><p>With this way, the bot will act like what we want her to be. This content, will define with the role “system”, which is used for giving instruction to bot first.</p><p>Here is the code:</p><pre># A message list to contain the messages from the user and the bot<br>message_list = []<br><br># Firstly, we need to set up a instruction for the bot to follow<br>system_message = {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a translator master, given a English sentence, you can change it to Japanese which is easy to understand and in well format.&quot;}<br><br>message_list.append(system_message)</pre><p>Then, we can tell the bot, what our question is, the content defined with the role “user”, showing that this is the question come from we human.</p><p>Here is the code:</p><pre># Secondly, we need to set up a message from the user, which is your request<br>user_message = {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;The baby is so cute!&quot;}<br><br>message_list.append(user_message)</pre><p><strong>3.Get response</strong></p><p>After we prepare the api key, model we use, what the bot should act like and our question, we can send out the content to GPT-3.5, then get the content using the OpenAI library.</p><p>Here is the code:</p><pre># Send the message to the bot<br>response_message = openai.ChatCompletion.create(model=model, messages=message_list, temperature=temperature)<br><br># Get the response from the bot<br>response = response_message.choices[0].message.content<br><br>print(response)</pre><p>Guess what, the response is:</p><pre>赤ちゃんはとても可愛いですね！<br>(Akachan wa totemo kawaii desu ne!)</pre><p>Awesome!</p><h3>Call GPT-3.5 with Http Request</h3><p>With the above cotent, we can call GPT-3.5 in python with OpenAI offical library.</p><p>Since not all languages have official openAI library support like(C#, C++, Java etc…).</p><p>If we konw how to call the API in Http request, we can call the API with any language or platform we want.</p><p>There are 3 steps to use the call GPT-3.5 service with Http requst:</p><ul><li>Set up api <strong>cofiguration</strong></li><li>Set up message with roles</li><li>Call GPT-3.5 with Http request</li></ul><p><strong>1.Set up api cofiguration</strong></p><p>As before, I will assert that you alreadly hava a avabile OpenAI key, which start with “sk-”,</p><p>in this process, we will set up api_key, model, url(https://medium.com/OpenAI%20GPT-3.5%20official%20endpoint) and Http Headers.</p><p>Here is the code:</p><pre># Set up YOUR OpenAI API key<br>api_key = &quot;sk-XXXXXXXXXXXXXXXX&quot;<br># With gpt-3.5-turbo model<br>model = &quot;gpt-3.5-turbo&quot;<br># OpenAI official API endpoint<br>url = &quot;https://api.openai.com/v1/chat/completions&quot;<br># Headers<br>headers = {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>}</pre><p><strong>2.Set up message with roles</strong></p><p>The process is the same as above content in the “Call GPT-3.5 with OpenAI library” process, we still take a translation task as an example to show you how to use the API. The task is to translate the following sentence from English to Japanese.</p><p>Here is the code showing how to set the message with roles:</p><pre># A message list to contain the messages from the user and the bot<br>message_list = []<br><br># Firstly, we need to set up a instruction for the bot to follow<br>system_message = {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a translator master, given a English sentence, you can change it to Japanese which is easy to understand and in well format.&quot;}<br><br>message_list.append(system_message)<br><br># Secondly, we need to set up a message from the user, which is your request<br>user_message = {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;The baby is so cute!&quot;}<br><br>message_list.append(user_message)</pre><p><strong>3.Call GPT-3.5 with Http request</strong></p><p>Different from using the official openai library, we can assemble our content into a http requst containing our api_key, model, tempreture, message_list.</p><p>Here is the send request funtion:</p><pre># Function to send the message to the bot<br>import requests<br>import json<br><br>def send_request(messages, model, url, temperature, headers, api_key):<br>    headers[&#39;Authorization&#39;] = f&quot;Bearer {api_key}&quot;<br>    <br>    data = {<br>        &quot;model&quot;: model,<br>        &quot;temperature&quot;: temperature,<br>        &quot;messages&quot;: messages<br>    }<br>    <br>    response = requests.post(url, headers=headers, json=data)<br>    response_json = response.json()<br>    <br>    if response.status_code == 200:<br>        content = [choice[&#39;message&#39;][&#39;content&#39;] for choice in response_json[&#39;choices&#39;]]<br>        return content[0]<br>    else:<br>        raise Exception(f&quot;Request failed with status code {response.status_code}: {response_json}&quot;)</pre><p>See what we can get from the request</p><pre># Send http request to the bot<br>response = send_request(message_list, model, url, headers, api_key)<br><br># Print the response from the bot<br>print(response)</pre><p>The response result is:</p><pre>赤ちゃんがとても可愛いですね！(Akachan ga totemo kawaii desu ne!)</pre><h3>Summary</h3><p>We explain how to call the GPT-3.5 API using the OpenAI library or HTTP POST requests, with a step-by-step guide to setting up the API key, model, and temperature, defining the message with roles, and getting the response.</p><p>Hope you enjoy and feel free to leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33157169794f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Generation with GPT-2 in Action]]></title>
            <link>https://medium.com/@yingbiao/text-generation-with-gpt-2-in-action-174e0335e1f6?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/174e0335e1f6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Sat, 24 Aug 2019 04:09:51 GMT</pubDate>
            <atom:updated>2020-01-07T07:44:33.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello friends, this is the third post of my serial “NLP in Action”, in this serial posts, I will share how to do NLP tasks with some SOTA technique with “code-first” idea — — which is inspired by <a href="https://www.fast.ai/about/">fast.ai</a>.</p><p>And I am also looking forwards for your feedbacks and suggestion.<br>My serial “NLP in Action” contains:</p><ul><li><a href="https://medium.com/@yingbiao/ner-with-bert-in-action-936ff275bc73">NER with BERT in Action</a></li><li><a href="https://medium.com/@yingbiao/text-classification-with-xlnet-in-action-869029246f7e">Text Classification with XLNet in Action</a></li><li><a href="https://medium.com/@yingbiao/text-generation-with-gpt-2-in-action-174e0335e1f6">Text Generation with GPT-2 in Action</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41LeDbKWnK_STBO51ImRSw.png" /></figure><h3>About Text Generation</h3><p>Text Generation is a usual NLP task, the purpose of text generation is to generate text from the given context, and make the newly generate text appearing indistinguishable to human-written text .</p><p>You can treat text generation as a task for the computer to write texts like human.With text generation, we can let the computer write stories, poems, news articles, and more for us.The better the model is , the more human like the generation will be.</p><p>Here come a funny test, can you tell the sentences below, which one is written by human, which one is written by human for the beginning and generate the left by computer?</p><blockquote><strong><em>Setence A:</em></strong><br>Apple was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in April 1976. Its stock began trading on the New York Stock Exchange on June 1, 1978. It was the first computer company to be listed on the NAS.</blockquote><blockquote><strong><em>Sentence B:</em></strong><br>Apple was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in April 1976 to develop and sell Wozniak’s Apple I personal computer, though Wayne sold his share back within 12 days. It was incorporated as Apple Computer, Inc.</blockquote><h3>About LM</h3><p>Language Model(LM) is the keystone for NLP, language model is a probability distribution over sequences of words, given the context, it will tell you the possibility of the next token.</p><p>In order to generate text, it is good to use language model, since language model will tell you the next most possible token base on your context. We can treat text generation process as a recurrent next token predict process.</p><p>Here is an example:</p><blockquote><strong><em>E.g.</em></strong><br>when you only say “Merry Christmas and happy”, with language model, it may predict the next token base on your context to be ‘new’ ,and then the context will be “Merry Christmas and happy new”, again, considering the text ,the language model may predict the next most reasonable token to be ‘year’.</blockquote><p>In this example, we you give “Merry Christmas and happy”, the language model will generate “new year” for you. So that, the full text will be “Merry Christmas and happy new year”.</p><p>Does it sound like a magic?</p><h3>About GPT-2</h3><p>GPT-2 is a language model comes from OpenAI’s paper <a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">“Language Models are Unsupervised Multitask Learners”</a>. GPT was a variation of the famous Transformer architecture proposed by the Google Brain team in their paper <a href="https://arxiv.org/abs/1706.03762">“Attention is all You Need”</a> .</p><p>With deep transformer layers, GPT-2 can detect long term dependencies between textual data. The model was trained unsupervised, by predicting the next word in 40GB of Internet text. So that, this model had a good sense of telling you what the next token based on the context.</p><p>The full GPT-2 model contain 1.5 billion parameters, it had achieved SOTA performance on many language modeling benchmarks especially text generation.</p><p>For the concerns about misusing GPT-2 model, OpenAI didn’t release the full version of GPT-2, the GPT-2 model we use in this post is a large model version which was released on Aug 20, 2019 by OpenAI with 774 million parameters.</p><blockquote>In this post, I will show how to use GPT-2 model to do text generation</blockquote><h3>In Action</h3><p>As a saying goes “No water, no swimming, no sailing, no boating.”, it would be better to get your hand on codes, if we want to get a clearer understanding of doing text generation.</p><p>Here, I will use the excellent library <a href="https://github.com/huggingface/pytorch-transformers">transformers</a> which deploy by <a href="https://github.com/huggingface">huggingface</a> , this library contains some state-of-the-art pre-trained models for Natural Language Processing (NLP) like GPT-2, XLNet, BERT … etc.</p><p>The process of doing text generation with GPT-2 contains 4 steps:<br>1. Load model and tokenizer<br>2. Set generation process parameters<br>3. Make context into embedding<br>4. Generate new text with model based on context</p><p>All the code will show with jupyter notebook here.</p><p><a href="https://github.com/billpku/NLP_In_Action">billpku/NLP_In_Action</a></p><p>And I will give a brief introduction of each step.</p><p><strong><em>1.Load model and tokenizer</em></strong></p><p>It is highly recommended to pre-download models and vocabulary files into local folder before using the model and tokenizer, so that we can enjoy a smooth using experience.</p><p>The files including:<br>1. <a href="https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-pytorch_model.bin">pytorch_model.bin</a><br>2. <a href="https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-config.json">config.json</a><br>3. <a href="https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-vocab.json">vocab.json</a><br>4. <a href="https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-large-merges.txt">merges.txt</a></p><p>Click each link above, download the files and rename them as presented above, then put them in the same folder like “gpt2-large”.<br>We can load the model and tokenizer with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3562f98cfb1ba57e16347a0a231e23dc/href">https://medium.com/media/3562f98cfb1ba57e16347a0a231e23dc/href</a></iframe><p><strong><em>2.Set generation process parameters</em></strong></p><p>For text generation, we need to tell the model how long the texts will generate, how to evaluate the next token is acceptable and decide how predictable text or surprising the text will be.<br>The parameters including:</p><ul><li><strong>Seed</strong>, int num for getting a random num</li><li><strong>Temperature</strong>, int num to treat as a magic num to make the generating process unpredictable</li><li><strong>Max_len</strong>, int num to define how long the text the model will generate</li><li><strong>Top_k</strong>, int num help the model only pick top K possible candidate token base on the context for each run of next token prediction</li><li><strong>Top_p</strong>, float num to filter the next predict token, only when the next token’s possibility higher than this num, can be taken into consideration for the predicting process</li></ul><p>You can change the parameters as you want, to make this generation process as a box of chocolates like life ^-^</p><p><strong><em>3.Make context into embedding</em></strong></p><p>We can set the context what we want, then tokenize and transform it into embedding. Then wait for the magic to happen in next step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/345bdba9070f3da659046a969f2d1f65/href">https://medium.com/media/345bdba9070f3da659046a969f2d1f65/href</a></iframe><p><strong><em>4.Generate new text with model based on context</em></strong></p><p>The precess of generating text including:</p><ol><li><strong>Sampling</strong>, in order the pick up the most reasonable next token from the context, the language model will calculate each word’s conditional probability based on the context. The higher the probability the word is, the more possible it will be picked as the next token</li><li><strong>Filtering</strong>, since there are tons of words can be candidate for the next token choice, we need to set up some filter to only consider the possible ones</li><li><strong>Beam search</strong>, as we know, when a sentence is fluency, not only because each word connects good, but also all the words in the sentence can together become a whole. So it will be the same for the text generation process, the model will consider words for a long term, the model will try to pick up words that not only have a good sense with token before it, but also connect good with all the words in the sentence</li><li><strong>Recurrent decision</strong>, after picking some reasonable token for the next position as candidate, the model will repeat the process described above, keep changing and picking tokens for each position. And finally generate a sentence that fit the requirement of length.</li></ol><p>It is such a great joy to play with text generation, I keep changing the context and generation process parameters described above, then get some result that I hardly can tell it was written by computer.</p><blockquote><strong><em>E.g:</em></strong><br><strong><em>Context: </em></strong><br>Apple was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in April 1976.<br><strong><em>Generate text:</em></strong><br>Its stock began trading on the New York Stock Exchange on June 1, 1978. It was the first computer company to be listed on the NAS<br><strong><em>Combined result:</em></strong><br>Apple was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in April 1976. Its stock began trading on the New York Stock Exchange on June 1, 1978. It was the first computer company to be listed on the NAS</blockquote><h3>Summary</h3><p>Text generation is a task in NLP to generate texts based on the context, with language model, we can let the computer to generate text for us. Deep transformer model like GPT-2 had a good sense of predicting the most reasonable word based on the context, which can help us to make SOTA text generation result.</p><h3>Reference</h3><p>In order to write this post , I had learned and got inspired from these articles, thank you^-^</p><p><a href="https://www.topbots.com/generalized-language-models-bert-openai-gpt2/">GENERALIZED LANGUAGE MODELS: BERT &amp; OPENAI GPT-2</a><br><a href="https://towardsdatascience.com/one-language-model-to-rule-them-all-26f802c90660">One Language Model to Rule Them All</a><br><a href="https://medium.com/phrasee/neural-text-generation-generating-text-using-conditional-language-models-a37b69c7cd4b">Neural text generation: How to generate text using conditional language models</a><br><a href="https://medium.com/huggingface/how-to-build-a-state-of-the-art-conversational-ai-with-transfer-learning-2d818ac26313">How to build a State-of-the-Art Conversational AI with Transfer Learning</a></p><h3>Disclaimer</h3><p><strong>Text generation is a task for NLP, I write this post for educational purposes only. Please don’t misuse this model and technology.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174e0335e1f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Classification with XLNet in Action]]></title>
            <link>https://medium.com/@yingbiao/text-classification-with-xlnet-in-action-869029246f7e?source=rss-f9f914e94fe0------2</link>
            <guid isPermaLink="false">https://medium.com/p/869029246f7e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Yingbiao(Bill) Huang]]></dc:creator>
            <pubDate>Mon, 05 Aug 2019 16:03:47 GMT</pubDate>
            <atom:updated>2020-01-07T07:43:31.735Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello friends, this is the second post of my serial “NLP in Action”, in this serial posts, I will share how to do NLP tasks with some SOTA technique with “code-first” idea — — which is inspired by <a href="https://www.fast.ai/about/">fast.ai</a>.</p><p>And I am also looking forwards for your feedbacks and suggestion.<br>My serial “NLP in Action” contains:</p><ul><li><a href="https://medium.com/@yingbiao/ner-with-bert-in-action-936ff275bc73">NER with BERT in Action</a></li><li><a href="https://medium.com/@yingbiao/text-classification-with-xlnet-in-action-869029246f7e">Text Classification with XLNet in Action</a></li><li><a href="https://medium.com/@yingbiao/text-generation-with-gpt-2-in-action-174e0335e1f6">Text Generation with GPT-2 in Action</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmRRON0R0xnq3xTnY1O8_g.png" /></figure><h3>About Text Classification</h3><p>Text Classification is a usual NLP task, the purpose of text classification is straight forward, is to classify the texts (documents , sentences ,queries or article titles…) , then set a label or labels to the texts.</p><p>So that, we can get a deeper understand of the texts, it is good for us to manage the texts as resource. Text classification is widely used, like news recommendation system, after you know the preference of the user, if you had labeled the news before, then you can push a reasonable news to the user, which is a win win situation — — the user enjoy your recommendation, and your website will be enjoyed ^-^</p><p>Here is an example:</p><blockquote><strong>E.g.</strong></blockquote><blockquote><strong>News title:</strong> “NBA schedule release 2019–20: Here are four things we already know about this season’s slate of games”<br><strong>Classification: </strong><em>Sports</em></blockquote><blockquote><strong>News title:</strong>”Deep Learning, AI Improve Accuracy of Breast Cancer Detection”<br><strong>Classification: </strong><em>Technology</em></blockquote><h3>About XLNet</h3><p>XLNet is a language model comes from this paper <a href="https://arxiv.org/abs/1906.08237"><strong>XLNet: Generalized Autoregressive Pretraining for Language Understanding</strong></a>.</p><p>XLNet is a <a href="https://arxiv.org/abs/1810.04805"><strong>BERT</strong></a> like pre-trained model. We can treat XLNet as an enhanced version of BERT, it outperformed BERT on some NLP tasks including Text Classification , Question Answering and others.</p><p>XLNet use <a href="https://arxiv.org/abs/1901.02860"><strong>Transformer XL</strong> </a>as a feature extracting architecture, which is better than BERT’s Transformer, since Transformer XL added recurrence to the Transformer. Which can make the XLNet has a deeper understand of the language context.</p><p>Using XLNet for a specific task is very straightforward, we can download XLNet model pre-trained first, then use fine-tuning method to update the pre-trained model to fit downstream task needed, XLNet is a specific transform learning method for NLP.</p><blockquote>In this post, I will show how to use XLNet method to do text classification</blockquote><h3>In Action</h3><p>As a saying goes “No water, no swimming, no sailing, no boating.”, it would better to get your hand on code, so that we can get a more clear understanding of doing text classification.</p><p>Here, I will use the excellent library <a href="https://github.com/huggingface/pytorch-transformers"><strong>transformers</strong></a> which deploy by <a href="https://github.com/huggingface"><strong>huggingface</strong></a>, this library contains some state-of-the-art pre-trained models for Natural Language Processing (NLP) like XLNet, GPT, BERT … etc.</p><p>The process of doing text classification with XLNet contains 4 steps:<br><strong>1. Load data<br>2. Set data into training embeddings<br>3. Train model<br>4. Evaluate model performance</strong></p><p>All the code will show with jupyter notebook here.</p><p><a href="https://github.com/billpku/NLP_In_Action">billpku/NLP_In_Action</a></p><p>And I will give brief introduction of each step.</p><p><strong><em>1.Load data<br></em></strong>In order to do text classification, we need dataset which texts were labeled.<br>First, we need to load the dataset with pandas:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acffd1a90cf73c84cd55a2bcde17bf4c/href">https://medium.com/media/acffd1a90cf73c84cd55a2bcde17bf4c/href</a></iframe><p>Then we have a look at the data and analyze the tags distribution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/567df1add517c4700b994257a54f6ae9/href">https://medium.com/media/567df1add517c4700b994257a54f6ae9/href</a></iframe><p><strong><em>2.Set data into training embeddings<br></em></strong>After we get the data, we need to set the text into 3 kinds of embeddings:<br>- Token embedding<br>- Mask word embedding<br>- Segmentation embedding</p><p>The process of making embeddings for XLNet is different from BERT, first we will tokenize the texts with <a href="https://github.com/google/sentencepiece"><strong>sentencepiece</strong></a>, then, we will add “&lt;sep&gt;’”,”&lt;cls&gt;”and pad mask to the embeddings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c68a14c47acedbb72d89b78d6cc2f7f/href">https://medium.com/media/0c68a14c47acedbb72d89b78d6cc2f7f/href</a></iframe><p><strong><em>3.Train model<br></em></strong>When using transform learning like XLNet, the process of training a new model with downstream data called “fine-tuning”, all we need to do it to choose one of the XLNet pre-trained model and use our own data to update the model’s parameter to fix our downstream NLP task.<br>For English language, XLNet have 2 kinds of model, base cased model and large cased model. <br>The large version model is a bigger model than base model, which has better performance, but need more computing power and times. <br>In this example we will choose XLNet base cased model for fine-tuning new model, if you are interested, you can try the large model instead, and it may get a better results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf24ca263baa4d8e17d1a9229412925a/href">https://medium.com/media/bf24ca263baa4d8e17d1a9229412925a/href</a></iframe><p><strong><em>4.Evaluate model performance<br></em></strong>After training a new model for text classification, we want to know how well the model will be. So that ,we can evaluate the model with new data.<br>The evaluate data can set in the process when we set training data batch<br>before, it recommended to use 30% of data to act as testing data for performance validation.<br>After evaluated by testing data, the result may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_w5aFV_U4P2bgi9Q52M0Q.png" /><figcaption>Validation Accuracy</figcaption></figure><h3>Summary</h3><p>Text classification is a task in NLP to label texts, with the labels, we can know much better about the meaning of the text. In order to do text classification, we can use XLNet — a nowadays SOTA pre-trained model to easily fine-tune a model for text classification downstream task.</p><h3>Reference</h3><p>In order to write down this post , I have learned and got inspired from these articles, thank you^-^</p><ol><li><a href="https://towardsdatascience.com/xlnet-a-clever-language-modeling-solution-ab41e87798b0">XLNet — a clever language modeling solution</a></li><li><a href="https://mlexplained.com/2019/06/30/paper-dissected-xlnet-generalized-autoregressive-pretraining-for-language-understanding-explained/">Paper Dissected: “XLNet: Generalized Autoregressive Pretraining for Language Understanding” Explained</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=869029246f7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>