<?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 Anthony Sun on Medium]]></title>
        <description><![CDATA[Stories by Anthony Sun on Medium]]></description>
        <link>https://medium.com/@auslei?source=rss-94e509a3e93c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Anthony Sun on Medium</title>
            <link>https://medium.com/@auslei?source=rss-94e509a3e93c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:06:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@auslei/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[OpenAI’s new agent builder — How it works (5 min intro)]]></title>
            <link>https://medium.com/@auslei/openais-new-agent-builder-how-it-works-5-min-intro-c48a6765bd38?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48a6765bd38</guid>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 01:57:02 GMT</pubDate>
            <atom:updated>2025-10-20T02:11:22.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenAI’s new agent builder — How it works (5 min intro)</h3><p>OpenAI recently launched its “block coding” style <a href="https://openai.com/index/introducing-agentkit/">AgentKit</a>, <a href="https://platform.openai.com/docs/guides/chatkit">ChatKit</a>. With AgentKit comes with a GUI based “<a href="https://platform.openai.com/agent-builder">Agent Builder</a>” allowing developers to build workflows visually. Finally, there is a <a href="https://platform.openai.com/docs/guides/chatkit-widgets">WidgetKit</a>, which creates formats the responses into a presentable web formats.</p><p>So, is it N8N, Create, Lovable, etc.? I don’t think so, it looks similar but it is basically a wrapper around OpenAI’s AgentSDK. The workflow design is less flexible with a lot less tools and connections. The multi-agent flows is not as comprehensive as LangChain. However, I think in time, most of the issues will be addressed. However, one specific one makes me hesitant — ecosystem locking. Using AgentKit will lock you inside OpenAI ecosystem, and significant development meaning significant investment needed when switching.</p><p>For now, let’s see what we can do. There are some really useful things in the framework as well, hopefully it will be made opensource. Let’s assume that we want to build a research assistant that will get a research topic from an user and browse online and finding authoritative sources, then summarise the result. You know, the typical stuff. Workflow like the below:</p><ol><li>Simple Classifier + Extraction: Validate if the user is intended for research, only proceed if research is requested.</li><li>Condition: if research then proceed</li><li>Simple Agent + Web Search Tool: Generate right queries to find information related to the topics</li><li>Editor Agent: Summarise and make it presentable.</li></ol><p>To start, let’s got to <a href="https://platform.openai.com/agent-builder/">https://platform.openai.com/agent-builder/</a>. (you will need to setup your organisation, project and openai account I believe).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-SPxdmK0Vjml7UecOs9Tw.png" /><figcaption>Agent Builder Landing Page</figcaption></figure><h3>Agents</h3><p>To create a new agent, click on “Create”, and you will be greeted with a blank canvas, with two nodes. Start and My Agent. Let’s make changes to My Agent to a classifier. Clicking on it will bring up the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Le0088GeUseJ_5T6_MKJhw.png" /><figcaption>Agent Menu</figcaption></figure><p>It’s actually very self-explanatory, only highlighting a few points here which I find to be useful:</p><ul><li><strong>Name</strong>: I have renamed it to <strong>topic_extractor</strong>, as you can see I didn’t leave any spaces in the name, and it will make sense later.</li><li><strong>Instructions</strong>: I think it is system prompt, so I treated as one. Provided instructions below</li></ul><pre>You are an AI agent whose primary purpose is to help users research topics they mention.<br>If the user’s request is not related to research, politely inform them that you can only assist with research tasks.<br>If a valid research topic is identified, hand off the request to your assistant AI agent to gather relevant materials.</pre><ul><li><strong>User</strong>: It’s user prompt, originally it only has instructions, but you can click on the + key to add an user prompt. To reference the variables, you can use expressions in curly brackets. e.g. {{workflow.input_as_text}} You can reference workflow variables, inputs and specific nodes.</li><li><strong>Output Format: </strong>Let’s say if we want a structured format in json, we can either specify a json template, manually add fields, or just generate one directly here. I find it to be quite useful.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpBO8321FlxbcFrlUdWGEA.png" /><figcaption>Structured Output Generation</figcaption></figure><ul><li><strong>Models</strong>: For simple classifiers, I used o4-mini which is more than enough. You can also adjust model reasoning effort (ReAct maybe?) which we can set to low.</li></ul><h3><strong>Workflow</strong></h3><p>I don’t want to bore you with every single node and If/else is very simple, I will save my own tokens. ;) so I built the following flows to just test our a few things:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stLcunVrm7yJhKgLIvVj2A.png" /><figcaption>Full Workflow</figcaption></figure><p>A few things:</p><ul><li><strong>Guardrails</strong>: The guardrails node is basically a custom agent that detects predefined scenarios such as PII leaks, explicit contents, hallucinations, etc. It can be refined further.</li><li><strong>If/Else/Else If</strong>: These are your typical flow controls</li><li><strong>Reference to variables</strong>: use workflow object to reference workflow variables, input to reference previous node, step.[node_name] to reference other nodes.</li><li><strong>Tools: </strong>There are a few tools already provided: browser, file search (vector database search), code interpreter. It also integrates with MCPs so your tool options are pretty much unlimited.</li><li><strong>Transforms</strong>: I didn’t test it, but it perform data transforms, probably simple ones, but should be similar to other visual programming toolsets.</li><li><strong>Set State: </strong>There are basically global variables.</li><li><strong>Widgets: </strong>You can apply additional formatting with widgets, and you can use ones created in OpenAI’s gallery or prompt Widget Builder tool to generate one and download it. So it can be fed into the agent.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H56k3LV6lyd69nfZQCxSvQ.png" /></figure><ul><li><strong>Evaluate: </strong>Once published you can evaluate how your agents are performing, I am find it is very good. You can drill down to each area and set criteria to graders (bots). This may also mean all requests are logged. hmm.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8WDW-yeXukqr8BMIcPMQw.png" /><figcaption>Evaluate</figcaption></figure><h3>Deployment</h3><p>Once you are happy with everything. then you can <strong>publish</strong> your great workflow. When publish, you will get a workflow_id, and you will just need to spin up your own server and supply your OpenAI API KEY and this workflow id, and it will start working.</p><p>OpenAI also provided an example app for both npm TypeScript and python:</p><p><a href="https://github.com/openai/openai-chatkit-advanced-samples">https://github.com/openai/openai-chatkit-advanced-samples</a></p><p>Of course, all python/typescript code required are already generated. Yes, it is this simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ml94637bOXOY2WAHYC5Qsg.png" /><figcaption>Auto Generated Code</figcaption></figure><p>Please let me know what your thoughts, should we trust OpenAI or should we opt for a more Open Source system. :)</p><p><strong>Full Automatically Generated Code:</strong></p><pre>from agents import FileSearchTool, WebSearchTool, Agent, ModelSettings, RunContextWrapper, TResponseInputItem, Runner, RunConfig, trace<br>from openai import AsyncOpenAI<br>from types import SimpleNamespace<br>from guardrails.runtime import load_config_bundle, instantiate_guardrails, run_guardrails<br>from pydantic import BaseModel<br>from openai.types.shared.reasoning import Reasoning<br><br># Tool definitions<br>file_search = FileSearchTool(<br>  vector_store_ids=[<br>    &quot;vs_68ec8b7b83c48191861accbec2c9fa47&quot;<br>  ]<br>)<br>web_search_preview = WebSearchTool(<br>  search_context_size=&quot;medium&quot;,<br>  user_location={<br>    &quot;type&quot;: &quot;approximate&quot;<br>  }<br>)<br># Shared client for guardrails and file search<br>client = AsyncOpenAI()<br>ctx = SimpleNamespace(guardrail_llm=client)<br># Guardrails definitions<br>guardrails_config = {<br>  &quot;guardrails&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Moderation&quot;,<br>      &quot;config&quot;: {<br>        &quot;categories&quot;: [<br>          &quot;sexual&quot;,<br>          &quot;sexual/minors&quot;,<br>          &quot;hate&quot;,<br>          &quot;hate/threatening&quot;,<br>          &quot;harassment&quot;,<br>          &quot;harassment/threatening&quot;,<br>          &quot;self-harm&quot;,<br>          &quot;self-harm/intent&quot;,<br>          &quot;self-harm/instructions&quot;,<br>          &quot;violence&quot;,<br>          &quot;violence/graphic&quot;,<br>          &quot;illicit&quot;,<br>          &quot;illicit/violent&quot;<br>        ]<br>      }<br>    },<br>    {<br>      &quot;name&quot;: &quot;Jailbreak&quot;,<br>      &quot;config&quot;: {<br>        &quot;model&quot;: &quot;gpt-4.1-mini&quot;,<br>        &quot;confidence_threshold&quot;: 0.7<br>      }<br>    },<br>    {<br>      &quot;name&quot;: &quot;Contains PII&quot;,<br>      &quot;config&quot;: {<br>        &quot;block&quot;: True,<br>        &quot;entities&quot;: [<br>          &quot;CREDIT_CARD&quot;,<br>          &quot;US_BANK_NUMBER&quot;,<br>          &quot;US_PASSPORT&quot;,<br>          &quot;US_SSN&quot;<br>        ]<br>      }<br>    }<br>  ]<br>}<br># Guardrails utils<br><br>def guardrails_has_tripwire(results):<br>    return any(getattr(r, &quot;tripwire_triggered&quot;, False) is True for r in (results or []))<br><br>def get_guardrail_checked_text(results, fallback_text):<br>    for r in (results or []):<br>        info = getattr(r, &quot;info&quot;, None) or {}<br>        if isinstance(info, dict) and (&quot;checked_text&quot; in info):<br>            return info.get(&quot;checked_text&quot;) or fallback_text<br>    return fallback_text<br><br>def build_guardrail_fail_output(results):<br>    failures = []<br>    for r in (results or []):<br>        if getattr(r, &quot;tripwire_triggered&quot;, False):<br>            info = getattr(r, &quot;info&quot;, None) or {}<br>            failure = {<br>                &quot;guardrail_name&quot;: info.get(&quot;guardrail_name&quot;),<br>            }<br>            for key in (&quot;flagged&quot;, &quot;confidence&quot;, &quot;threshold&quot;, &quot;hallucination_type&quot;, &quot;hallucinated_statements&quot;, &quot;verified_statements&quot;):<br>                if key in (info or {}):<br>                    failure[key] = info.get(key)<br>            failures.append(failure)<br>    return {&quot;failed&quot;: len(failures) &gt; 0, &quot;failures&quot;: failures}<br>class TopicExtractorSchema(BaseModel):<br>  action: str<br>  topics: list[str]<br>  reason: str<br><br><br>class DataGathererSchema__KeyPointsItem(BaseModel):<br>  point: str<br>  source: str<br>  published: str<br><br><br>class DataGathererSchema(BaseModel):<br>  topic: str<br>  summary: str<br>  key_points: list[DataGathererSchema__KeyPointsItem]<br><br><br>class EditorSchema(BaseModel):<br>  pass<br><br><br>topic_extractor = Agent(<br>  name=&quot;topic_extractor&quot;,<br>  instructions=&quot;&quot;&quot;You are an AI agent whose primary purpose is to help users research topics they mention.<br>If the user’s request is not related to research, politely inform them that you can only assist with research tasks.<br>If a valid research topic is identified, hand off the request to your assistant AI agent to gather relevant materials.&quot;&quot;&quot;,<br>  model=&quot;o4-mini&quot;,<br>  tools=[<br>    file_search<br>  ],<br>  output_type=TopicExtractorSchema,<br>  model_settings=ModelSettings(<br>    store=True,<br>    reasoning=Reasoning(<br>      effort=&quot;low&quot;,<br>      summary=&quot;auto&quot;<br>    )<br>  )<br>)<br><br><br>data_gatherer = Agent(<br>  name=&quot;data_gatherer&quot;,<br>  instructions=&quot;&quot;&quot;You are an AI agent responsible for gathering accurate and trustworthy information from the internet on a given topics.<br><br>Your task:<br><br>1. Collect information only from credible and verifiable sources such as:<br>   - Government websites (.gov)<br>   - Educational and academic institutions (.edu, Google Scholar, academic journals)<br>   - Recognised news organisations or reputable media outlets<br>   - Industry reports, whitepapers, or official publications<br>   - Peer-reviewed studies or expert-authored articles<br><br>2. Avoid using:<br>   - Personal blogs, forums, or unverified social media posts<br>   - AI-generated content or sources without citation<br>   - Information without clear origin or publication date<br><br>3. For each key point you gather, include:<br>   - Source name or website<br>   - Publication date (if available)<br>   - A short summary of the information<br><br>4. Ensure all data is relevant to the topic, unbiased, and up-to-date (preferably within the last 2–3 years unless historical context is necessary).<br><br>5. Present your findings in a structured format, such as:&quot;&quot;&quot;,<br>  model=&quot;gpt-5-nano&quot;,<br>  tools=[<br>    web_search_preview<br>  ],<br>  output_type=DataGathererSchema,<br>  model_settings=ModelSettings(<br>    store=True,<br>    reasoning=Reasoning(<br>      effort=&quot;low&quot;,<br>      summary=&quot;auto&quot;<br>    )<br>  )<br>)<br><br><br>editor = Agent(<br>  name=&quot;editor&quot;,<br>  instructions=&quot;&quot;&quot;You are an Editor AI agent. Your task is to take the research data gathered by previous agent(s) and transform it into a clear, coherent, and well-structured report.<br><br><br><br>### Your Responsibilities:<br><br>1. **Understand the topic** from the provided research data.<br>2. **Read and organise** the collected information into a structured format.<br>3. **Write a human-readable report** that:<br>   - Flows logically from introduction to conclusion<br>   - Summarises key findings clearly<br>   - Maintains factual accuracy based on the provided sources<br>   - Uses neutral, professional language<br>   - Avoids repetition, speculation, or unsupported claims<br>4. **Cite or reference sources** where appropriate (e.g. “According to the World Health Organization (2023)...”)<br>5. **Do not fabricate information.** Only use the materials provided by the research agent.<br><br>### **Output Format:**<br><br>Provide the final report in this structure:<br><br><br>Title of Report<br><br><br><br>1. Introduction<br><br><br>Brief overview of the topic<br>Purpose and scope of the report<br><br><br><br>2. Key Findings<br><br><br>Summarise information logically grouped into themes or subtopics<br>Use short paragraphs or bullet points for clarity<br><br><br><br>3. Analysis / Discussion<br><br><br>Explain relationships, implications, or trends from the information<br>Compare perspectives if multiple sources differ<br><br><br><br>4. Conclusion<br><br><br>Final summary of insights<br>No new information should be introduced here<br><br><br><br>5. References<br><br><br>List the main sources used (name + organisation + date if available)<br>&quot;&quot;&quot;,<br>  model=&quot;gpt-5&quot;,<br>  output_type=EditorSchema,<br>  model_settings=ModelSettings(<br>    store=True,<br>    reasoning=Reasoning(<br>      effort=&quot;low&quot;,<br>      summary=&quot;auto&quot;<br>    )<br>  )<br>)<br><br><br>class GuidanceContext:<br>  def __init__(self, input_guardrails: str):<br>    self.input_guardrails = input_guardrails<br>def guidance_instructions(run_context: RunContextWrapper[GuidanceContext], _agent: Agent[GuidanceContext]):<br>  input_guardrails = run_context.context.input_guardrails<br>  return f&quot;&quot;&quot;Explain to user why you cannot proceed based on below guardrail issues:<br>{input_guardrails}&quot;&quot;&quot;<br>guidance = Agent(<br>  name=&quot;Guidance&quot;,<br>  instructions=guidance_instructions,<br>  model=&quot;gpt-5-mini&quot;,<br>  model_settings=ModelSettings(<br>    store=True,<br>    reasoning=Reasoning(<br>      effort=&quot;low&quot;,<br>      summary=&quot;auto&quot;<br>    )<br>  )<br>)<br><br><br>class WorkflowInput(BaseModel):<br>  input_as_text: str<br><br><br># Main code entrypoint<br>async def run_workflow(workflow_input: WorkflowInput):<br>  with trace(&quot;Web Research&quot;):<br>    state = {<br><br>    }<br>    workflow = workflow_input.model_dump()<br>    conversation_history: list[TResponseInputItem] = [<br>      {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: [<br>          {<br>            &quot;type&quot;: &quot;input_text&quot;,<br>            &quot;text&quot;: workflow[&quot;input_as_text&quot;]<br>          }<br>        ]<br>      }<br>    ]<br>    guardrails_inputtext = workflow[&quot;input_as_text&quot;]<br>    guardrails_result = await run_guardrails(ctx, guardrails_inputtext, &quot;text/plain&quot;, instantiate_guardrails(load_config_bundle(guardrails_config)), suppress_tripwire=True)<br>    guardrails_hastripwire = guardrails_has_tripwire(guardrails_result)<br>    guardrails_anonymizedtext = get_guardrail_checked_text(guardrails_result, guardrails_inputtext)<br>    guardrails_output = (guardrails_hastripwire and build_guardrail_fail_output(guardrails_result or [])) or (guardrails_anonymizedtext or guardrails_inputtext)<br>    if guardrails_hastripwire:<br>      guidance_result_temp = await Runner.run(<br>        guidance,<br>        input=[<br>          *conversation_history<br>        ],<br>        run_config=RunConfig(trace_metadata={<br>          &quot;__trace_source__&quot;: &quot;agent-builder&quot;,<br>          &quot;workflow_id&quot;: &quot;wf_68e65283baa0819093376a9603cf77960833a9a0080c2c77&quot;<br>        }),<br>        context=GuidanceContext(input_guardrails=guardrails_output[&quot;guardrails&quot;])<br>      )<br><br>      conversation_history.extend([item.to_input_item() for item in guidance_result_temp.new_items])<br><br>      guidance_result = {<br>        &quot;output_text&quot;: guidance_result_temp.final_output_as(str)<br>      }<br>    else:<br>      topic_extractor_result_temp = await Runner.run(<br>        topic_extractor,<br>        input=[<br>          *conversation_history,<br>          {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: [<br>              {<br>                &quot;type&quot;: &quot;input_text&quot;,<br>                &quot;text&quot;: f&quot;Original question: {workflow[&quot;input_as_text&quot;]}&quot;<br>              }<br>            ]<br>          }<br>        ],<br>        run_config=RunConfig(trace_metadata={<br>          &quot;__trace_source__&quot;: &quot;agent-builder&quot;,<br>          &quot;workflow_id&quot;: &quot;wf_68e65283baa0819093376a9603cf77960833a9a0080c2c77&quot;<br>        })<br>      )<br><br>      conversation_history.extend([item.to_input_item() for item in topic_extractor_result_temp.new_items])<br><br>      topic_extractor_result = {<br>        &quot;output_text&quot;: topic_extractor_result_temp.final_output.json(),<br>        &quot;output_parsed&quot;: topic_extractor_result_temp.final_output.model_dump()<br>      }<br>      if topic_extractor_result[&quot;output_parsed&quot;][&quot;action&quot;] == &quot;research&quot;:<br>        data_gatherer_result_temp = await Runner.run(<br>          data_gatherer,<br>          input=[<br>            *conversation_history,<br>            {<br>              &quot;role&quot;: &quot;user&quot;,<br>              &quot;content&quot;: [<br>                {<br>                  &quot;type&quot;: &quot;input_text&quot;,<br>                  &quot;text&quot;: &quot;&quot;&quot;Please research on the following topics:<br>                {{steps.topic_extractor.output.topics}}&quot;&quot;&quot;<br>                }<br>              ]<br>            }<br>          ],<br>          run_config=RunConfig(trace_metadata={<br>            &quot;__trace_source__&quot;: &quot;agent-builder&quot;,<br>            &quot;workflow_id&quot;: &quot;wf_68e65283baa0819093376a9603cf77960833a9a0080c2c77&quot;<br>          })<br>        )<br><br>        conversation_history.extend([item.to_input_item() for item in data_gatherer_result_temp.new_items])<br><br>        data_gatherer_result = {<br>          &quot;output_text&quot;: data_gatherer_result_temp.final_output.json(),<br>          &quot;output_parsed&quot;: data_gatherer_result_temp.final_output.model_dump()<br>        }<br>        editor_result_temp = await Runner.run(<br>          editor,<br>          input=[<br>            *conversation_history<br>          ],<br>          run_config=RunConfig(trace_metadata={<br>            &quot;__trace_source__&quot;: &quot;agent-builder&quot;,<br>            &quot;workflow_id&quot;: &quot;wf_68e65283baa0819093376a9603cf77960833a9a0080c2c77&quot;<br>          })<br>        )<br><br>        conversation_history.extend([item.to_input_item() for item in editor_result_temp.new_items])<br><br>        editor_result = {<br>          &quot;output_text&quot;: editor_result_temp.final_output.json(),<br>          &quot;output_parsed&quot;: editor_result_temp.final_output.model_dump()<br>        }<br>      else:<br>        return topic_extractor_result</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48a6765bd38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenVoice — Text to speech]]></title>
            <link>https://medium.com/@auslei/openvoice-text-to-speech-87547175348d?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/87547175348d</guid>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 15:14:43 GMT</pubDate>
            <atom:updated>2025-07-15T15:14:43.336Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenVoice — Text to speech</h3><p>Let you computer talk with any voice</p><p><a href="https://github.com/myshell-ai/OpenVoice">OpenVoice</a> is a model provided by MIT and MyShell. The package requires a reference sound clip, to achieve a (almost) zero-shot voice clone, without requiring fine-tuning on the speaker. The model is efficient and fast, and works even if neither reference nor target language appears in its multilingual training set.</p><p>Without going into details on the <a href="https://arxiv.org/abs/2312.01479">paper</a>. The following is a summary of workflow to enable text to speech mimicking a speaker.</p><p>The process goes as follows:</p><ul><li>User provide text and corresponding language. Each language may have different dialects, for example English (EN) will have Australian, British, and even Indian accents.</li><li>Based on the language and dialect, we will find the corresponding base TTS “speaker”, and thus synthesis text to speech.</li><li>Then we use se_extractor, which is a model with pre-trained weight to encode reference voice into vector (embedding) that captures the reference voices timbre (tone colour)</li><li>Then we apply the embedding into the base voice and convert the speech into the desired voice.</li></ul><p>While the original git hub provided some sample code, but the lack of documentation made it a bit confusing. Hope the following step helps, each code block corresponds to the above described steps:</p><h4><strong>Setup Environment</strong></h4><p>Refere to the original documentation for more details. In this illustration, we will use v2 checkpoints. (assuming v2 is better than v1)</p><p>Firstly create a new conda environment and install OpenVoice package from GitHub.</p><pre># Create a new Conda environment named &quot;openvoice&quot; with Python 3.9<br>conda create -n openvoice python=3.9<br><br># Activate the new environment<br>conda activate openvoice<br><br># Clone the OpenVoice repository using SSH<br>git clone git@github.com:myshell-ai/OpenVoice.git<br><br># Change directory into the OpenVoice folder<br>cd OpenVoice<br><br># Install the OpenVoice package in editable mode (useful for development)<br>pip install -e .</pre><p>Then create a new directory for your own code (provided code for both linux/macOS):</p><pre>mkdir ~/myvoice<br>cd ~/myvoice<br><br># Create the destination folder if it doesn&#39;t exist<br>mkdir -p checkpoints_v2<br><br># Download the ZIP file using curl<br><br># MacOS<br>curl -L -o checkpoints_v2.zip &quot;https://myshell-public-repo-host.s3.amazonaws.com/openvoice/checkpoints_v2_0417.zip&quot;<br><br># Linux<br>wget https://myshell-public-repo-host.s3.amazonaws.com/openvoice/checkpoints_v2_0417.zip -O checkpoints_v2.zip<br><br># Unzip the contents into the checkpoints_v2 directory<br>unzip checkpoints_v2.zip -d checkpoints_v2<br><br># (Optional) Remove the ZIP file after extraction<br>rm checkpoints_v2.zip </pre><p>Then download and install MeloTTS package.</p><pre># Install the MeloTTS package directly from the GitHub repository<br># MeloTTS is a multilingual and controllable TTS (text-to-speech) system<br># used as the base-speaker TTS model in OpenVoice. It supports style control<br># like emotion, rhythm, and language.<br>pip install git+https://github.com/myshell-ai/MeloTTS.git<br><br># Download the UniDic Japanese dictionary for morphological analysis<br># This is required for Japanese text tokenisation and linguistic processing.<br># It’s used by MeCab (a Japanese tokenizer) behind the scenes.<br>python -m unidic download</pre><h4>Code</h4><p>The following are sample codes roughly follows the process laid out previously.</p><p>Firstly, getting the right device to use based on system:</p><pre>import torch<br>def get_device() -&gt; str:<br>    &quot;&quot;&quot;Auto-detect torch device: MPS (Apple M1), CUDA, or CPU.&quot;&quot;&quot;<br>    if hasattr(torch.backends, &#39;mps&#39;) and torch.backends.mps.is_available():<br>        return &#39;mps&#39;<br>    if torch.cuda.is_available():<br>        return &#39;cuda:0&#39;<br><br>    return &#39;cpu&#39;<br><br>device = get_device()<br>print(device)</pre><p>Then, convert the text into speech:</p><pre>text = &quot;I love to play table tennis with my brother.&quot;<br><br>model = TTS(language=&quot;EN&quot;, device=device) # create the TTS model<br><br># dialect <br>speaker_key = &#39;EN-BR&#39;<br>speaker_id = model.hps.data.spk2id[speaker_key]<br><br># file key is somewhat similar to the speaker key, <br># it identifies the location of the weight (for a particular<br># dialect. The below is simple string manipulation.<br>file_key = speaker_key.lower().replace(&#39;_&#39;, &#39;-&#39;)<br><br># loading the base speaker weight<br>source_se = torch.load(f&quot;./checkpoints_v2/base_speakers/ses/{file_key}.pth&quot;, map_location=device) <br><br># save the synthesised text into a temp file. <br>model.tts_to_file(text, speaker_id, &quot;./tmp.wav&quot;, speed=1)</pre><p>Then we will get reference speaker embedding:</p><pre>from openvoice.api import ToneColorConverter<br><br>converter = ToneColorConverter(<br>        config_path=&quot;./checkpoints_v2/converter/config.json&quot;,<br>        device=device,<br>    )<br>converter.load_ckpt(&quot;./checkpoints_v2/converter/checkpoint.pth&quot;)<br><br>from openvoice import se_extractor<br>target_se, _ = se_extractor.get_se(str(&quot;./reference_voice.wav&quot;), converter, vad=True)</pre><p>Lastly, we combine temp file generated via TTS with Tone Colour:</p><pre>with torch.no_grad():<br>    converter.convert(<br>        audio_src_path=&quot;./tmp.wav&quot;,<br>        src_se=source_se,<br>        tgt_se=target_se,<br>        output_path=&quot;./new.wav&quot;,<br>        message=&quot;@MyShell&quot;, #a voice identier<br>    )</pre><p>Note:</p><p>If reference file is of mp3 type, we may need to download ffmpg:</p><pre># MacOS<br>brew install ffmpeg <br><br># Linux<br>sudo apt update<br>sudo apt install ffmpeg</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87547175348d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Fine-tuning with Unsloth locally]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@auslei/llm-fine-tuning-with-unsloth-locally-fb9d5ef688c9?source=rss-94e509a3e93c------2"><img src="https://cdn-images-1.medium.com/max/1536/0*dxd1mKD9KItCk7EE" width="1536"></a></p><p class="medium-feed-snippet">How to extended LLM knowledge</p><p class="medium-feed-link"><a href="https://medium.com/@auslei/llm-fine-tuning-with-unsloth-locally-fb9d5ef688c9?source=rss-94e509a3e93c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@auslei/llm-fine-tuning-with-unsloth-locally-fb9d5ef688c9?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb9d5ef688c9</guid>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 11:11:28 GMT</pubDate>
            <atom:updated>2025-07-02T11:15:21.868Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Setup Windows WSL2 (or Linux) for Machine Learning (LLM)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">I always forget how to setup, every time when I set up a new system for machine learning. It will take a while googling and cussing before&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@auslei/setup-windows-wsl2-for-machine-learning-llm-5d25cb7118f9?source=rss-94e509a3e93c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@auslei/setup-windows-wsl2-for-machine-learning-llm-5d25cb7118f9?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d25cb7118f9</guid>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 09:34:09 GMT</pubDate>
            <atom:updated>2025-07-02T00:53:14.797Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Word Embedding from Scratch]]></title>
            <link>https://medium.com/@auslei/word-embedding-from-scratch-5735cfe5ad7b?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5735cfe5ad7b</guid>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 04:37:33 GMT</pubDate>
            <atom:updated>2025-02-26T02:39:22.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary</h3><p>In <strong>natural language processing (NLP)</strong>, it is essential to represent words or sub-words (also called <strong>tokens</strong>) numerically so that mathematical operations can be performed efficiently. This numerical representation enables computers to process, analyse, and generate human language.</p><p>Before the introduction of <strong>word embeddings</strong>, traditional methods such as <strong>one-hot encoding</strong> and <strong>TF-IDF (Term Frequency-Inverse Document Frequency)</strong> were commonly used to represent words in a machine-readable format.</p><ul><li>One-hot encoding: Each word in the vocabulary is represented as a unique vector where only one element is 1, and all others are 0.</li></ul><pre>apple  = [1, 0, 0]<br>banana = [0, 1, 0]<br>cherry = [0, 0, 1]</pre><ul><li><strong>TF-IDF (Term Frequency-Inverse Document Frequency)</strong>: Measures the importance of a word in a document relative to a corpus. It assigns a weight to each word based on how frequently it appears.</li></ul><p><strong>Word embeddings</strong> overcome these limitations by representing words as <strong>dense, continuous-valued vectors</strong> in a multi-dimensional space. Instead of arbitrary one-hot vectors, embeddings are <strong>learned</strong> from large text corpora, capturing meaningful relationships between words.</p><p><strong>Semantic Meaning</strong>: Words with similar meanings (e.g., “king” and “queen”) are <strong>close together</strong> in vector space, while unrelated words (e.g., “king” and “apple”) are far apart.</p><p>This means that if you take the vector for “king”, subtract the vector for “man”, and add the vector for “woman”, you end up near the vector for “queen”. This shows that embeddings capture <strong>gender relationships</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE-u0FGD03GA4qMfUeCoNA.png" /></figure><p><strong>Key Advantages of Word Embeddings</strong></p><ul><li><strong>Captures Context &amp; Meaning</strong>: Unlike one-hot encoding, embeddings reflect word similarity and relationships.</li><li><strong>Efficient Representation</strong>: Dense vectors (e.g., 300-dimensional) reduce computational cost compared to sparse one-hot vectors.</li><li><strong>Generalises Better</strong>: Pretrained embeddings (e.g., Word2Vec, GloVe, FastText) can be used across multiple NLP tasks.</li></ul><p>In summary, <strong>word embeddings revolutionised NLP</strong> by providing a way to represent words <strong>mathematically while preserving meaning</strong>, leading to better <strong>machine translation, sentiment analysis, question-answering, and more.</strong> 🚀</p><h3>Training Word Embedding</h3><h4>Methods</h4><p>Word embeddings are learned from large text corpora using unsupervised learning methods. Two of the most popular approaches for training word embeddings:</p><ul><li><strong>Skip-gram</strong>, the goal is to predict the <strong>context words</strong> given a <strong>target word</strong>. For example, in the sentence “The king rules the country,” given the word “king” as the target, the Skip-gram model tries to predict the words “the”, “rules”, “the”, and “country” as the context. This method works well with large datasets and is effective at capturing relationships between words, especially for infrequent words. The Skip-gram model learns to represent the target word in such a way that it predicts surrounding words accurately, helping the model build meaningful word embeddings.</li><li><strong>Continuous Bag of Words (CBOW)</strong> works the other way around. It predicts the <strong>target word</strong> from its <strong>context words</strong>. In the same example, given the context words [“the”, “rules”, “the”, “country”], the CBOW model tries to predict the target word “king”. CBOW is faster to train compared to Skip-gram, especially with smaller datasets, as it takes the context words as input and averages their embeddings to predict the target. Both models ultimately aim to learn word representations where semantically similar words are positioned closely in the vector space.</li></ul><p>We will go through the CBOW method for now, and later I may add skip-gram into the same article.</p><h4>Step 1 — Preparation</h4><ol><li>The libraries we will need are: nltk, tensorflow, sklearn and matplotlib (for visualisation)</li><li><strong>Get Data: </strong>We need to firstly download some text for training our model. We will use <a href="https://www.google.com/search?client=safari&amp;rls=en&amp;q=Project+Gutenberg+Book&amp;ie=UTF-8&amp;oe=UTF-8"><strong>Project Gutenberg Book</strong></a>.</li><li><strong>Preprocessing</strong>: We will want to cleans the books a bit, removing unnecessary special characters, and stop-words. (they usually do not contribute too much)</li></ol><pre># =============================================<br># Download Required NLTK Datasets<br># =============================================<br>nltk.download(&quot;gutenberg&quot;)<br>nltk.download(&quot;punkt&quot;)<br>nltk.download(&quot;stopwords&quot;)<br>nltk.download(&quot;punkt_tab&quot;)<br><br># =============================================<br># Load &amp; Preprocess Text Data <br># =============================================<br>def load_gutenberg_text():<br>    &quot;&quot;&quot;Loads all books from the NLTK Gutenberg dataset and concatenates them into a single text corpus.&quot;&quot;&quot;<br>    corpus = &quot;&quot;<br>    for file_id in gutenberg.fileids():<br>        corpus += gutenberg.raw(file_id) + &quot;\n\n&quot;  # Add spacing between books<br>    return corpus<br><br>def preprocess_text(corpus):<br>    &quot;&quot;&quot;Tokenizes text, removes punctuation and stopwords, and converts to lowercase.&quot;&quot;&quot;<br>    stop_words = set(stopwords.words(&quot;english&quot;))<br>    important_words = {&quot;i&quot;, &quot;he&quot;, &quot;she&quot;, &quot;we&quot;, &quot;they&quot;, &quot;you&quot;}  # Keep personal pronouns<br>    filtered_stopwords = stop_words - important_words  # Remove other stopwords<br><br>    tokens = word_tokenize(corpus)  # Tokenize text<br>    tokens = [word.lower() for word in tokens if word.isalnum() and word not in filtered_stopwords]  # Clean tokens<br>    return tokens<br><br># Load and preprocess text<br>corpus = load_gutenberg_text()<br>tokens = preprocess_text(corpus)<br><br># Print the 10 most common words<br>word_counts = Counter(tokens)<br>print(&quot;Most common words:&quot;, word_counts.most_common(10))</pre><p>The code is quite self-explanatory: we download necessary packages from NLTK; then we iterate through each book in the collection and built up the corpus load_gutenberg_text() ; then we pre-process. Note that we’ve kept some pronouns as they will be useful for conveying information.</p><p>Finally we counted top 10 most common words, the following is the output:</p><pre>Most common words: [(&#39;i&#39;, 30209), (&#39;he&#39;, 25839), (&#39;and&#39;, 16570), <br>(&#39;you&#39;, 16305), (&#39;they&#39;, 13088), (&#39;shall&#39;, 11679), (&#39;said&#39;, 9427), <br>(&#39;she&#39;, 9060), (&#39;unto&#39;, 9010), (&#39;lord&#39;, 8585)]</pre><h4>Step 2 — Generate Training Data</h4><p>We will firstly build up our vocabulary, basically create a unique numeric id for each of the token. We also add &lt;PAD&gt; and &lt;OOV&gt;. PAD is used to PAD our training data to ensure uniform input length. OOV (out of vocabulary) is used to handle token not in vocabulary.</p><p>Take following string as example The King rules the country. The vocab will be like below:</p><pre>+---------+-------+<br>|  Word   | Index |<br>+---------+-------+<br>| &lt;PAD&gt;   |     0 |<br>| &lt;OOV&gt;   |     1 |<br>| the     |     2 |<br>| king    |     3 |<br>| rules   |     4 |<br>| country |     5 |<br>+---------+-------+</pre><pre>def build_vocab(tokens, max_vocab_size=5000, min_freq=5):<br>    &quot;&quot;&quot;Creates word-to-index and index-to-word mappings with OOV handling.&quot;&quot;&quot;<br>    word_counts = Counter(tokens)<br>    <br>    # Filter words by minimum frequency<br>    filtered_words = {word: count for word, count in word_counts.items() if count &gt;= min_freq}<br>    <br>    # Sort words by frequency and keep only the most common<br>    most_common_words = sorted(filtered_words, key=filtered_words.get, reverse=True)[:max_vocab_size]<br>    <br>    # Special tokens<br>    word_to_ix = {&#39;&lt;PAD&gt;&#39;: 0, &#39;&lt;OOV&gt;&#39;: 1}<br>    <br>    # Assign indices to words<br>    word_to_ix.update({word: i + 2 for i, word in enumerate(most_common_words)})<br>    ix_to_word = {i: word for word, i in word_to_ix.items()}<br><br>    # ✅ Use defaultdict to handle OOV words<br>    word_to_ix = defaultdict(lambda: 1, word_to_ix)  # Default to index 1 (OOV)<br><br>    return word_to_ix, ix_to_word<br><br># Example usage<br>max_vocab_size = 5000  # Ensure vocabulary size is defined<br>word_to_ix, ix_to_word = build_vocab(tokens, max_vocab_size = max_vocab_size, min_freq=5)<br>vocab_size = len(word_to_ix)<br>print(f&quot;Vocabulary Size: {vocab_size}&quot;)</pre><p>Use the same logic, we will build the vocabulary. Each will be assigned an ID. We will add PAD and OOV in the front.</p><h4>Step 3- Generate Training Data</h4><p>The training data for CBOW, as described earlier will be context words and target word. Where context word are words surrounding the target word. For training, each word in our token set will be target words. Using previous example (“The king rules the country”) with a context window of 2, the context and target training pair will be as follows:</p><pre>Words:<br>+-------------+-------------------------------+<br>| Target Word | Context Words                 |<br>+-------------+-------------------------------+<br>| the         | king, rules, &lt;PAD&gt;, &lt;PAD&gt;     |<br>| king        | the, rules, the, &lt;PAD&gt;        |<br>| rules       | the, king, the, country       |<br>| the         | rules, country, &lt;PAD&gt;, &lt;PAD&gt;  |<br>| country     | the, rules, &lt;PAD&gt;, &lt;PAD&gt;      |<br>+-------------+-------------------------------+<br><br>Actual output:<br>+-------------+----------------------+<br>| Target Index | Context Indices     |<br>+-------------+----------------------+<br>| 2           | 3, 4, 0, 0           |<br>| 3           | 2, 4, 2, 0           |<br>| 4           | 2, 3, 2, 5           |<br>| 2           | 4, 5, 0, 0           |<br>| 5           | 2, 4, 0, 0           |<br>+-------------+----------------------+</pre><p>Note, the context size is 2*context_window .</p><p>The following is python code to generate data. In this case, we used a generator to efficiently use memory. Assuming we have a vocab of 5000, the context window size of 5 and a batch of 128. The memory usesage can be quite high. context_mem = batch_size*window_size*2*vocab_size and target_mem = batch_size * vocab_size . Also noting we did one-hot encoding on the target, but not context. This is also to save memory. The one-hot encoding for context will be done on the fly to save memory.</p><pre>def cbow_data_generator(tokens, word_to_ix, window_size=5):<br>    &quot;&quot;&quot;Generates (context, target) pairs for CBOW training (yields raw indices).&quot;&quot;&quot;<br>    for idx in range(len(tokens)):<br>        <br>        context = [<br>            word_to_ix.get(tokens[i], word_to_ix[&quot;&lt;OOV&gt;&quot;])<br>            for i in range(max(0, idx - window_size), min(len(tokens), idx + window_size + 1))<br>            if i != idx<br>        ]  # Context words as word indices<br><br>        target = word_to_ix.get(tokens[idx], word_to_ix[&quot;&lt;OOV&gt;&quot;])  # Target word as index<br><br>        # Ensure fixed-size context (pad if necessary)<br>        while len(context) &lt; 2 * window_size:<br>            context.append(word_to_ix[&quot;&lt;PAD&gt;&quot;])<br>        <br>        vocab_size = len(word_to_ix)  # Ensure vocabulary size is defined<br>        target_one_hot = tf.one_hot(tf.cast(target, tf.int32), depth=vocab_size) <br><br>        yield np.array(context, dtype=np.int32), target_one_hot.numpy()  # Yield context and target<br><br># Define parameters<br>window_size = 5<br>embedding_dim = 10<br><br># Keep dataset as word indices, apply one-hot encoding inside the model<br>dataset = tf.data.Dataset.from_generator(<br>    lambda: cbow_data_generator(tokens, word_to_ix, window_size),<br>    output_signature=(<br>        tf.TensorSpec(shape=(2 * window_size,), dtype=tf.int32),  # Context words (indices)<br>        tf.TensorSpec(shape=(vocab_size), dtype=tf.int32)  # Target (index)<br>    )<br>)</pre><h4>Step 4 — Building Model</h4><p>The model will consist 5 layers, we will go through each layer:</p><ol><li><strong>Input Layer</strong>: It’s self explanatory, our input will be context words, which will be a shape of batch_size, 2*context_window.</li><li><strong>Lambda Layer: </strong>The input are list ID’s, we will need to perform one-hot encoding. It is most efficient if we do it during training as part of the model, as the memory will be released as soon as calculation is done. Following one hot, we will have a shape of batch_size, 2*context_window, vocab_size</li><li><strong>Dense Layer: </strong>Here we will a dense layer, acting as an embedding lookup to train word embedding, which are the weights. The shape of the weights (embedding) will be vocab_size, embedding_dim , and output will be batch_size, 2*context_window, embedding_dim . As can be seen, the wright will have an word vector for each vocab.</li><li><strong>Mean Pooling Layer: </strong>The assumption is the average context word (overall meaning) will be similar to target word. So this is a pure mathematical operation to get the averge of the previous step. mean_pooling = (embedding 1 + embedding 2 ... embedding_n) / 2*context_window</li><li><strong>Output Dense with Softmax: </strong>Lastly, we will predict the target word with a softmax classifier. Note target is one-hot encoded, and output will be probabily distribution of the vocabulary.</li></ol><p>Putting it all together:</p><pre>import tensorflow as tf<br>from tensorflow.keras.layers import Input, Dense, Lambda<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.optimizers import Adam<br><br>def build_cbow_model(vocab_size, embedding_dim, window_size):<br>    &quot;&quot;&quot;Builds a CBOW model where one-hot encoding is done inside the model for both input and output.&quot;&quot;&quot;<br><br>    input_layer = Input(shape=(2 * window_size,))  # Input: word indices (NOT one-hot)<br><br>    # Convert word indices to one-hot dynamically (for input)<br>    one_hot_input = Lambda(lambda x: tf.one_hot(tf.cast(x, tf.int32), depth=vocab_size))(input_layer)<br><br>    # Dense layer simulating embedding lookup (trainable weight matrix)<br>    dense_embedding = Dense(embedding_dim, use_bias=False)(one_hot_input)  # (batch, context_size, embedding_dim)<br><br>    # Mean Pooling (Averaging context word vectors)<br>    mean_embedding = Lambda(lambda x: tf.reduce_mean(x, axis=1))(dense_embedding)<br><br>    # Output Layer (Softmax for predicting target word)<br>    output_layer = Dense(vocab_size, activation=&quot;softmax&quot;)(mean_embedding)<br><br>    # Compile Model (Now Uses Standard `categorical_crossentropy`)<br>    model = Model(inputs=input_layer, outputs=output_layer)<br>    model.compile(loss=&quot;categorical_crossentropy&quot;, optimizer=Adam(learning_rate=0.01), metrics=[&quot;accuracy&quot;])<br><br>    return model<br><br># ✅ No need to precompute one-hot encoding!<br># Use word indices directly<br>model = build_cbow_model(vocab_size, embedding_dim, window_size)<br>model.summary()</pre><h4>Step 5 — Model Training</h4><p>We are not going to elaborate on how training works, it’s pretty much the same for all other trainings. The code is as below, I have added a couple of callbacks:</p><pre># =============================================<br># Train CBOW Model<br># =============================================<br>from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint<br><br># Build CBOW model<br>model = build_cbow_model(vocab_size, embedding_dim, window_size)<br><br># Checkpoint to save best model<br>checkpoint = ModelCheckpoint(<br>    filepath=&quot;cbow_best_model.h5&quot;,<br>    monitor=&quot;loss&quot;,  # Monitor training loss<br>    save_best_only=True,<br>    mode=&quot;min&quot;,<br>    verbose=1<br>)<br><br># Early stopping to prevent overfitting<br>early_stopping = EarlyStopping(<br>    monitor=&quot;loss&quot;,      # Monitor training loss (no val_loss in unsupervised training)<br>    patience=5,          # Stop if loss doesn&#39;t improve for 5 epochs<br>    min_delta=1e-4,      # Ignore very small changes<br>    mode=&quot;min&quot;,<br>    verbose=1<br>)<br><br># Training dataset (replace with actual tf.data.Dataset)<br>batch_size = 128<br>epochs = 50  # More epochs needed for embeddings<br>dataset = dataset.batch(batch_size).prefetch(tf.data.AUTOTUNE)<br><br># Train model<br>model.fit(<br>    dataset,<br>    epochs=epochs,<br>    verbose=1,<br>    callbacks=[checkpoint, early_stopping]<br>)</pre><h3>Visualising Result</h3><p>As can be seen, when visualise a sample of words, similar words or related words are clustered close to each other. Though there are exceptions. For example, cat and dog is further apart but cat is close to the house. May be due to the text we have portrait cats always play around the house. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*nhWTJ1kGqs1wZ-OprNiswQ.png" /><figcaption>Some words visualised using t-SNE dimension reduction technique</figcaption></figure><p>Of course, we only used a very small vocabulary (5000) and dimension (10) for the training. To better optimise we may want to increase these parameters, then we will need to optimise our memory usage more efficiently. Tensorflow provides an embedding layer which does exactly this, see below adjusted function and I will leave the rest of discovery to you.</p><pre>def build_cbow_model_embedding_layer(vocab_size, embedding_dim, window_size):<br>    &quot;&quot;&quot;Builds a CBOW model using an Embedding layer instead of one-hot encoding.&quot;&quot;&quot;<br>    <br>    # 🔹 Input: word indices (no need for one-hot encoding)<br>    input_layer = Input(shape=(2 * window_size,), dtype=tf.int32)  # (batch_size, context_size)<br><br>    # 🔹 Embedding layer replaces one-hot + dense embedding lookup<br>    embedding_layer = Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=2 * window_size)<br>    embedded_context = embedding_layer(input_layer)  # (batch_size, context_size, embedding_dim)<br><br>    # 🔹 Mean Pooling (Averaging context word vectors)<br>    mean_embedding = Lambda(lambda x: tf.reduce_mean(x, axis=1))(embedded_context)  # (batch_size, embedding_dim)<br><br>    # 🔹 Output Layer (Softmax for predicting target word)<br>    output_layer = Dense(vocab_size, activation=&quot;softmax&quot;)(mean_embedding)  # (batch_size, vocab_size)<br><br>    # ✅ Define Model<br>    model = Model(inputs=input_layer, outputs=output_layer)<br>    model.compile(loss=&quot;categorical_crossentropy&quot;, optimizer=Adam(learning_rate=0.01), metrics=[&quot;accuracy&quot;])<br><br>    return model</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5735cfe5ad7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summarise Web Pages Instantly: Writing a Chrome Extension Powered by Ollama LLM]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@auslei/summarise-web-pages-instantly-writing-a-chrome-extension-powered-by-ollama-llm-e4c305a2f636?source=rss-94e509a3e93c------2"><img src="https://cdn-images-1.medium.com/max/800/1*YusvTYsGehv2yeX051H4Cw.png" width="800"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.com/@auslei/summarise-web-pages-instantly-writing-a-chrome-extension-powered-by-ollama-llm-e4c305a2f636?source=rss-94e509a3e93c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@auslei/summarise-web-pages-instantly-writing-a-chrome-extension-powered-by-ollama-llm-e4c305a2f636?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c305a2f636</guid>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 02:07:15 GMT</pubDate>
            <atom:updated>2024-11-29T02:07:15.511Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Are Algorithms Reprogramming Your Mind? The Hidden Risks of Recommender Systems]]></title>
            <link>https://medium.com/@auslei/are-algorithms-reprogramming-your-mind-the-hidden-risks-of-recommender-systems-2894e05fa1d4?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2894e05fa1d4</guid>
            <category><![CDATA[digital-life]]></category>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[mental-health]]></category>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 00:24:04 GMT</pubDate>
            <atom:updated>2024-11-25T01:25:01.226Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The Allure of Personalised Content</strong></h3><p>Have you ever noticed how your social media feed seems to know exactly what you like? It feels like magic — one video leads to another, each more interesting or engaging than the last. But behind this convenience lies a powerful algorithmic system designed to keep your attention. And while it’s learning about you, it might also be training you in ways you haven’t realised.</p><h3><strong>How Machines Learn — A Brief Overview</strong></h3><p>Machine learning (ML) is the backbone of recommender systems. At its core, ML works by identifying patterns in data and using them to predict what you might want next.</p><p>For instance, let’s say you watch a video about cooking. The algorithm:</p><p>1. Records your action (watching the video).</p><p>2. Looks at data from millions of other users who watched similar videos.</p><p>3. Predicts that you might enjoy related content, like more cooking tutorials or even food critique shows.</p><p>The more data the system gathers, the better it gets at predicting what you’ll like. It’s an iterative process: the algorithm’s “recommendations” are based on what it’s been trained to see as patterns of interest.</p><h3><strong>The Problem with Biased Training</strong></h3><p>Here’s the catch: just as biased data can lead to flawed ML predictions, a biased flow of information can shape your perceptions.</p><p>Imagine an ML model trained only on one type of data — say, cat pictures. It wouldn’t understand dog pictures very well, and over time, it would start reinforcing its preference for cats. Similarly, when recommender systems continuously feed you articles or videos that align with your views, they create an echo chamber. This phenomenon:</p><p>• Amplifies confirmation bias (our tendency to favor information that supports our existing beliefs).</p><p>• Makes opposing views seem less relevant, or even threatening.</p><p>• Reinforces stereotypes, misconceptions, or extreme ideologies.</p><p>Studies like those by <em>Zeynep Tufekci</em> (<em>TED Talk: “We’re Building a Dystopia Just to Make People Click on Ads”</em>) and research in <em>Nature Communications</em> have shown how algorithms can inadvertently contribute to political polarization and radicalization by favoring content that provokes emotional engagement.</p><h3><strong>Are You Being Trained?</strong></h3><p>Here’s where it gets personal. While algorithms train themselves to predict your preferences, they might also be training <strong>you</strong>. Each piece of content you consume reinforces a mental pathway, much like practice strengthens a skill. Over time:</p><p>• Seeing similar content repeatedly can deepen your convictions.</p><p>• Exaggerated or extreme perspectives may start to feel like the norm.</p><p>• Exposure to one-sided narratives could reduce your ability to empathize with other viewpoints.</p><p>Neuroscience backs this up: the human brain is remarkably plastic. Just as repetition shapes habits, the constant bombardment of similar content can rewire your thought patterns. In effect, a recommender system can guide how you think — without you even noticing.</p><h3><strong>Breaking Free — Why You Should Turn Off Recommendations</strong></h3><p>So, what can you do? The simplest step is to turn off recommender systems when possible. Here’s why:</p><p>1. <strong>Regain Autonomy</strong>: Without algorithms steering your choices, you’re free to explore diverse perspectives and discover content organically.</p><p>2. <strong>Avoid Extremes</strong>: A balanced information diet can prevent your views from becoming overly polarized.</p><p>3. <strong>Stay Mindful</strong>: Actively choosing what to watch, read, or listen to keeps you in control of your mental and emotional well-being.</p><p>While turning off recommendations might seem inconvenient, it’s a small price to pay for protecting your cognitive freedom.</p><h3><strong>A Mind of Your Own</strong></h3><p>Recommender systems are powerful tools, but like any tool, they must be used carefully. By understanding how they work — and how they might be working on you — you can take steps to reclaim your mental space. Next time you’re scrolling through your feed, remember: the algorithm might be training your brain, but you have the power to change the narrative.</p><h3><strong>Practical Steps to Turn Off Recommender Systems</strong></h3><p>If you’re convinced of the need to break free from algorithm-driven recommendations, here are some practical steps to help you regain control:</p><h4><strong>Step 1: Disable Auto-Play Features</strong></h4><p>Auto-play keeps you hooked by serving content without giving you a chance to pause and reflect.</p><p><strong>How to Disable:</strong></p><ul><li><strong>YouTube</strong>: Toggle off the “Auto-play” switch at the top of the sidebar while watching a video.</li><li><strong>Netflix</strong>: Go to “Account Settings” → “Playback Settings” → Uncheck “Autoplay next episode.”</li><li><strong>Social Media</strong>: Many platforms, like Instagram and TikTok, use infinite scrolling instead. Limiting time on these apps can help.</li></ul><h4>Step 2: <strong>Clear Your Watch/Reading History</strong></h4><p>Algorithms rely on your viewing history to refine their recommendations. Deleting this data resets the system.</p><p><strong>How to Clear:</strong></p><ul><li><strong>YouTube</strong>: Go to “History” → “Manage All History” → Delete activity by date or type. (you can also turn off history all together)</li><li><strong>Netflix</strong>: Under “Viewing Activity,” you can remove specific titles to prevent them from influencing recommendations.</li><li><strong>Web Browsers</strong>: Clear your cookies and browsing data periodically.</li></ul><h4>Step 3: <strong>Use “Do Not Track” Features</strong></h4><p>Many platforms collect data from your online behavior across different sites to refine recommendations.</p><p><strong>How to Enable:</strong></p><ul><li><strong>Browsers</strong>: Activate “Do Not Track” in Chrome, Firefox, or Safari settings.</li><li><strong>Privacy Extensions</strong>: Tools like DuckDuckGo or Brave browser block trackers and reduce data collection.</li></ul><h4>Step 4: <strong>Opt for Manual Search Instead of Feeds</strong></h4><p>Feeds are designed to show you what algorithms think you’ll like. Searching manually ensures you’re choosing content intentionally.</p><p><strong>How to Do It:</strong></p><ul><li>Use the search bar on platforms like YouTube, Netflix, or Spotify to find specific topics or creators.</li><li>Bookmark content sources you trust and visit them directly.</li></ul><h4>Step 5: <strong>Adjust Content Preferences</strong></h4><p>Some platforms prioritise user choice over algorithmic control.</p><p><strong>How to Adjust:</strong></p><ul><li><strong>YouTube</strong>: Click “Not Interested” on videos or “Don’t Recommend Channel.”</li><li><strong>Facebook</strong>: Use the “See Less” or “Hide Post” options for unwanted topics or accounts.</li><li><strong>Spotify</strong>: Create and listen to your own playlists instead of using auto-generated mixes.</li></ul><h4>Step 6: <strong>Explore Alternative Platforms</strong></h4><p>Some platforms prioritize user choice over algorithmic control.</p><p><strong>What to Try:</strong></p><ul><li>Opt for open-source platforms like <strong>Mastodon</strong>, which lack aggressive algorithms</li><li>For video content, consider platforms like <strong>Nebula</strong> or <strong>Vimeo</strong>, which don’t focus on constant recommendations.</li></ul><h4>Step 7: <strong>Turn Off Personalised Ads</strong></h4><p>Ads are often the driving force behind data collection and recommendations.</p><p><strong>How to Disable:</strong></p><p>• <strong>Google</strong>: Go to “Ad Settings” and toggle off “Personalized Ads.”</p><ul><li><strong>Facebook</strong>: Navigate to “Ad Preferences” and limit interest-based ad targeting.</li></ul><h4>Step 8: <strong>Limit App Permissions</strong></h4><p>Many apps collect unnecessary data that feed into their recommendation systems.</p><p><strong>How to Manage:</strong></p><ul><li>On your phone, review permissions under “Settings” → “Apps” and deny access to data like location or activity tracking.</li></ul><p>Taking control of your content consumption might feel overwhelming at first, but even small steps — like disabling auto-play or switching to manual search — can make a big difference. By making these changes, you’ll reduce the influence of algorithms on your mind and enjoy a more balanced, intentional digital experience.</p><h3>References</h3><ul><li>Zeynep Tufekci, <em>TED Talk: “We’re Building a Dystopia Just to Make People Click on Ads”</em></li><li>Lazer, D., et al. (2018). <em>The science of fake news.</em> Science, 359(6380), 1094–1096.</li><li>Bakshy, E., Messing, S., &amp; Adamic, L. A. (2015). <em>Exposure to ideologically diverse news and opinion on Facebook.</em> Science, 348(6239), 1130–1132.</li><li>Pariser, E. (2011). <em>The Filter Bubble: What the Internet Is Hiding from You.</em> Penguin Press.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2894e05fa1d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Chatbots with Ollama Vision Models: Adding Image Reasoning Capabilities]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@auslei/enhancing-chatbots-with-ollama-vision-models-adding-image-reasoning-capabilities-9e75f33ecda5?source=rss-94e509a3e93c------2"><img src="https://cdn-images-1.medium.com/max/800/1*rQ9NIDNtamVLLlHKio39Ng.png" width="800"></a></p><p class="medium-feed-link"><a href="https://medium.com/@auslei/enhancing-chatbots-with-ollama-vision-models-adding-image-reasoning-capabilities-9e75f33ecda5?source=rss-94e509a3e93c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@auslei/enhancing-chatbots-with-ollama-vision-models-adding-image-reasoning-capabilities-9e75f33ecda5?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e75f33ecda5</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 23:11:32 GMT</pubDate>
            <atom:updated>2024-11-25T01:22:16.510Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Progressive Summarisation (using LLM with limited context window)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@auslei/progressive-summarisation-using-llm-with-limited-context-window-e160f5041316?source=rss-94e509a3e93c------2"><img src="https://cdn-images-1.medium.com/max/800/1*SS9hhGqScqSC7MxCYM2MCg.png" width="800"></a></p><p class="medium-feed-link"><a href="https://medium.com/@auslei/progressive-summarisation-using-llm-with-limited-context-window-e160f5041316?source=rss-94e509a3e93c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@auslei/progressive-summarisation-using-llm-with-limited-context-window-e160f5041316?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e160f5041316</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 00:40:00 GMT</pubDate>
            <atom:updated>2024-11-25T01:24:16.263Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to chat with your PDF with Local LLM]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@auslei/how-to-chat-with-your-pdf-with-local-llm-5dfb1d419f37?source=rss-94e509a3e93c------2"><img src="https://cdn-images-1.medium.com/max/800/1*a163uK9FU3KRIHPLMCWjdw.png" width="800"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.com/@auslei/how-to-chat-with-your-pdf-with-local-llm-5dfb1d419f37?source=rss-94e509a3e93c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@auslei/how-to-chat-with-your-pdf-with-local-llm-5dfb1d419f37?source=rss-94e509a3e93c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dfb1d419f37</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Anthony Sun]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 06:03:32 GMT</pubDate>
            <atom:updated>2024-11-25T01:25:50.580Z</atom:updated>
        </item>
    </channel>
</rss>