<?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 sjchin on Medium]]></title>
        <description><![CDATA[Stories by sjchin on Medium]]></description>
        <link>https://medium.com/@chinsj?source=rss-28e03c706898------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HxMdvOfo9HFIm0NrHQdz9A.jpeg</url>
            <title>Stories by sjchin on Medium</title>
            <link>https://medium.com/@chinsj?source=rss-28e03c706898------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:39:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chinsj/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[美国退休金安排的策略]]></title>
            <link>https://chinsj.medium.com/%E7%BE%8E%E5%9B%BD%E9%80%80%E4%BC%91%E9%87%91%E5%AE%89%E6%8E%92%E7%9A%84%E7%AD%96%E7%95%A5-7d42ad3f985e?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d42ad3f985e</guid>
            <category><![CDATA[401k]]></category>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 02:33:26 GMT</pubDate>
            <atom:updated>2026-07-31T01:10:42.720Z</atom:updated>
            <content:encoded><![CDATA[<h3>懒人包策略</h3><h4>前提：</h4><ol><li>你对美国的股市有长期信心。</li><li>你预期会在美国待很久到接近退休， 或者你可以接受钱可以长期留在退休账户直到退休 （60岁）</li><li>你满意公司 401K plan 里的投资选项 （这里面通常会有一个 ETF track S&amp;P 500)</li></ol><h4>大策略</h4><p>优先顺序</p><ol><li>401(k) pretax 直到公司 match 的上限。 如果你公司match 50% up to 6% of salary, 就先存到6% salary.</li><li>如果本身健康， 一年的医疗支出（包括年检，prescription drug 等）少于 $500 -&gt; 买HDHP plan ，然后存满 HSA 上限。 HSA 同时兼具pretax 和 earnings growth tax-free 功能， 医疗支出不要 claim HSA, 从自己的钱包出， 让HSA 的钱自然增长。HSA 唯一缺点是 如果不是医疗支出， 得等65岁才能无理由取出。</li><li>在 401K pretax 上限内 （2026年是 $24,500）， 如果你预期 1） 退休时候的 收入会比现在低很多， 和 2） 你直到60岁(最早可以免罚金取出401K pretax的年龄) 前都不需要动用这笔钱， 那么就无脑 放 pretax 401K. 反之， 则放 Roth IRA， 其次是 Roth 401(k)。</li><li>如果你把 401(k) pretax 上限放满了， 有剩余的钱， 可以接受五十九岁前不动， 直接无脑 放 401(k) after-tax，然后做 Roth in-plan conversion (俗称 Mega backdoor) 转进 Roth 401(k). <strong>你的本金在五十九岁前可以随时取出， 不过收益会有 penalty，有些公司的 401K plan 在网页上直接有这个选项 (ROTH IN PLAN CONVERSION, Convert After-tax to Roth)。 有些没有。 没有的可以打电话去问 401(k) plan 的 Administrator 可不可以做 Roth in-plan conversion 或者 mega backdoor.</strong></li><li>个人投资账户里， 少过一年的收益按 ordinary income tax 算， 超过一年的收益按 long-term capital gain tax 算。 Long-term capital gain tax 的 tax rate 取决于你的 taxable income，每年少于的话税率为 0（单身 $48,350, 结婚 $96700), 你可以 每年做 capital gain tax harvest （即同时卖出股票来 lock in gain, 然后买入来提升你的 cost basis) up to 这个数额。 假设美股每年的报酬是 7-10%, 那么单身的你只要个人账户总资产少于 70万美金且没有其他收入基本不用缴税。 但科技行业的工作者只要肯存，五到十年内个人账户总资产会超过70万美金这个数， 同时还不可能没有其他收入， 这时候就需要你提前把钱存进 Mega Backdoor.</li><li>也就是说如果你的收入高， 有绿卡， 打算至少工作十年以上，存最少一两百万， 你肯定得考虑做 mega backdoor.</li></ol><p>两种 Roth 的区别</p><p>Roth IRA</p><ul><li>本金可以随时取出.</li><li>存入数额有限制， 且年收入不能超过特定数额</li></ul><p>Roth 401K</p><ul><li>本金可以随时取出， 但因为 Prorate rule, 取出本金时也要取出 收益 (Earning), 而取出收益在 59岁前有 penalty.</li></ul><h4>参考</h4><p><a href="https://www.1point3acres.com/bbs/thread-597491-1-1.html">[科普向]图解401K和IRA-可能是最容易理解退休金计划的科普贴|一亩三分地投资版</a></p><p><a href="https://www.gocurrycracker.com/never-pay-taxes-again/">https://www.gocurrycracker.com/never-pay-taxes-again/</a></p><h3>Pretax 401K vs Roth</h3><p><strong>问题描述：</strong> IRS 每年允许 个人 投入 pretax 401K 和 Roth 401K 的 总数是有限制的， 对五十岁以下的人群来说， 这个限制大概是 $23500. 那么选择 pretax 或者 Roth, 就要了解 这两个账户的主要特点和区别 及其 税务影响。 总的来说</p><p>Pretax 401(k) 投入的钱 不需缴税， 但取出时的收益按 Ordinary income 缴税， 并且有强制取出 Required Minimum Distribution 的限制。</p><p>Roth 401K 投入时当下 的钱需要缴税， 但取出时的收益 不用缴税。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xNcbqqnQP65Fv8Hc.png" /><figcaption>401K 解释图. 来源： 一亩三分地 诸神黄昏泪<a href="https://www.1point3acres.com/bbs/thread-597491-1-1.html">帖子</a></figcaption></figure><p>那么， 同一个 池子 ($23.5K) 下， 如何决定应该投入 pretax 401K 或者 Roth 401K 呢？答案是没有 必赢的选项。 投入 pretax 或者 Roth 何者收益更大， 取决于 很多因素， 比如个人的收入和存款能力， 当前和退休时候的预期税率 (包括州税的影响), 预期退休的年龄， 公司是否提供 In-plan conversion， 预期退休的开销等。</p><p>我们可以尝试简化问题， 考虑以下四种情况。</p><ol><li>个人 的 剩余收入 (收入减掉必要开支) 只够 存满 pretax 23.5K 的上限 （第一上限）。</li><li>个人 的 剩余收入 能够 存满 Roth 401K 的 第一上限， 但存不满 401K 每年<a href="https://www.fidelity.com/learning-center/smart-money/401k-contribution-limits">存入限制</a> ($69K for 2025) 的上限 (第二上限）。</li><li>个人 的 剩余收入 能够 存满 全 Roth 的 第二上限。</li><li>个人 的 剩余收入 能够 存满 全 Roth 的 第二上限， 且有相当多余的钱进行投资。</li></ol><p><strong>先划结论：</strong></p><p><strong>在个人的 marginal tax bracket 高的情况下， 存满 pretax 上限省下来的税， 在绝大多数情况下， 累积的投资收益在退休时， 都会优于其他选项。</strong></p><p>再假设一个 讨论对象。</p><p>小明，</p><ul><li>刚开始工作 (26岁) ， 每年收入 $100K, 生活在有州税的地方。</li><li>每年只能存满 pretax 23.5K 的上限， 公司另外match 1 to 1 up to 5% of total salary ($5K) 。</li><li>去除通胀影响的真实投资收益率 为 6% (<a href="https://www.investopedia.com/ask/answers/042415/what-average-annual-return-sp-500.asp">参考</a> S&amp;P 500 的 Inflation adjusted CAGR = 6.37%)</li><li>先不考虑通胀影响 。 在通胀的情况下， Pretax / Roth 的投入上限会增加, Nominal 投资收益会增加， 但相应的 Income tax bracket 也会增加。</li><li>不考虑 50岁后 的 Catch up contribution.</li><li>假设 60岁开始退休， 每年从 pre-tax 401K 固定取钱 到 100岁， 取钱的数额保证大于未来数十年任一时刻的 Required Minimum Distribution (如果不优化的话， 会发生 RMD 的必须取款 push up marginal income tax rate, 导致必须多缴税）。</li><li>退休时没有其他收入。</li></ul><h4>情况一 : 只够存满 全部 pre-tax 的第一上限</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiwiDAzfC3luQDkA4aZEeA.png" /><figcaption>全投入 pretax vs 部分投入 Roth</figcaption></figure><p>先解释下上面的图表。</p><p>Current marginal tax rate 是小明当下最高的 tax bracket. 因为 pretax 减少的是 小明的 total taxable income, 所以实际节省的税费取决于他的 last tax bracket.</p><p>Effective tax rate 是假设 在小明退休时 ，从 Pretax 401K plan 固定取款时的实际税率。</p><p>Column D 是小明 60岁后开始取款的数额， 保证每年取款数额大于 Required Minimum Distribution (Column E), 就能保证小明无需多缴税。 在这个例子里约 $195K. 这决定了 effective tax rate.</p><p>因为最优的策略必然是 先 max out 公司的 401K match, 所以在选项二里， 小明还是会有一点 pretax 401K (Column I）。</p><p>当小明退休时， 最优的选择肯定是尽量不动 tax free growth 的 roth, 所以优先从 pretax 取出。</p><p>因为 pretax plan withdraw 要缴税， 所以小明要从 Roth plan 取出的数额只需等于实际到手的数额即可 （大约约 $144.5K）</p><p>选项一 和 选项二 的差别体现在 column I 的数字， 数字 是正的 表示选项一比选项二号。</p><p>结论：</p><p>最优选择是优先存 Pretax.</p><p>Pretax 的优势源于 这个假设： 绝大多数情况下， 现在省下的税率 (Marginal income tax rate) 大概率大于 以后要还的税率 (effective income tax rate). 同时如果你现在在 有州税的 地方工作 (比如加州), 退休后如果搬到没有州税的地方 (比如 华盛顿 西雅图）， 那省下的税率会更明显。</p><p>但在以下情况 这个假设并不保险</p><ul><li>小明退休时还有其他收入 (比如 Social Security, side income, rental)。</li><li>小明决定延期退休， 或者pre-tax 401K 的实际回报率 大于 6%， 导致当他开始取款时的 固定取款额增加， 进而推高 effective income tax rate.</li><li>小明在没有州税的地方工作， 退休时搬到有州税的地方。</li><li>当小明退休时， 政府大幅度增加税率，进而推高 effective income tax rate.</li></ul><h4>情况二 : 能存满 全部 Roth 的 第一上限</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAjkquzEIL0IykI9NxSBOQ.png" /><figcaption>用 Pretax 节税 和 不用 Pretax 节税</figcaption></figure><p>最重要的假设， 小明投满第一上限后， 能投 Mega Backdoor Roth。 如果不能 用 mega backdoor, 就变成情况三。</p><p>这时候， 如果 在 Max out 公司 match 后 放满 Roth 到第一上限， Column G 表示 同时根据 Marginal tax rate 要缴交的税 (约 $8429). 全投 Pretax 401K 的好处是 这八千多刀小明不用交给政府， 他可以用 mega backdoor 的方式 转投 Roth IRA.</p><p>情况二的结论会更明显。</p><p>最优选择是优先存 Pretax.</p><p>Pretax 的优势是 省下的 税费可以直接 投入 Roth.</p><h4>情况三 : 刚好存满全部 Roth 的 第二上限</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BL398e56qExGTAZXK2hrA.png" /></figure><p>当小明能在 Max out 公司 401K match 后， 用 mega backdoor 存满Roth 的 第二上限时， 这时候 Pretax 省下的税 只能放 个人的投资账号。 按目前长期资本税 为 百分之二十计算， 假设小明一次取出所有个人投资， 实际需要缴交的资本税 列在 Column I.</p><p>虽然这大幅减低 Pretax 和 Roth 的 区别， 但考虑到 小明目前 Marginal tax rate 和 退休时候 long term capital tax rate 的差异， 这个区别还是很可观的。</p><h4>情况四， 存满 第二上限之余还有多余的钱投资</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0hfr698OQyYi2Ge9NDGCw.png" /></figure><p>需要解释的重点，</p><p>当小明能存满 第二上限之余还有多余的钱投资的时候， 他的总收入大概率接近超过 $200K, 很有可能已经触发了 32% 的 tax bracket.</p><p>当小明退休时， 如果他存满 pretax 401K, 那么他必须从pretax 哪里取钱。 但如果他存在 Roth, 那么他可以选择从 自己的个人账号取钱， 让Roth 的资产继续 grow tax free.</p><p>当他从个人账号取钱时， 选项一 会有对应的个人资产。 Column J — K 模拟的是在选项一下， 如果他没有从个人资产取钱的收益。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nG4r8H8Yaxd-SL-_I_truw.png" /></figure><p><strong>结论是选项一 (全 pretax ) 永远有优势。</strong></p><p>这可能有点违反直觉， 但注意一个 数字， H41 是 全pretax 策略下， 省下的税 利滚利到小明退休时候的数字， 这个数额大概是 一百四十万， 同时 选项二 Roth 账户的数字才两百万， 既在刚退休的起跑点时， pretax 已经有 额外70% 的资产。</p><p>注意情况三和情况四 Age 100 最后一列的数字</p><p>情况三， 个人账户的总额是 $9.6million, 选项一和选项二的差别是 + $2.2million</p><p>情况四， 个人账户的总额是 $14.8million，比情况三增加了 $5.2million. 选项一和选项二的差别是 + $6.6million， 比情况三只增加了 $4.4million. 少了的 $0.8 million 可以理解为 选项二的策略优势。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d42ad3f985e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to use AI on your Local Desktop: Generate Translated Subtitle]]></title>
            <link>https://chinsj.medium.com/guide-to-use-ai-on-your-local-desktop-generate-translated-subtitle-10b95389b51c?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/10b95389b51c</guid>
            <category><![CDATA[translategemma]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[faster-whisper]]></category>
            <category><![CDATA[speech-transcription]]></category>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Mon, 25 May 2026 19:37:57 GMT</pubDate>
            <atom:updated>2026-05-25T19:37:57.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preface</h3><p>Are you a Japanese Anime lover who loves to watch the latest series without having to wait for the translated version of the episode to be released?</p><p>Or are you a non-native English speaker who struggles to score high on TOEFL® but still wants to watch a good English video clip with no subtitles?</p><p>And do you want to do all these without worrying about paying the bills for the tokens used with Google Gemini, ChatGPT, ClaudeCode, etc.?</p><p>In this guide, I will show you how you can build tools that generate and translate subtitles on your local computer.</p><h3>Breaking Down the Steps Involved</h3><p>Generating a translated subtitle involves the following steps:</p><ul><li><strong>Extract the audio file</strong>: If you&#39;re working with a video file (like .mp4), you will need to extract the audio file (.mp3).</li><li><strong>Transcribe the audio file</strong>: You will need to use an <strong>Automatic Speech Recognition (ASR) </strong>model to transcribe the speech from the audio file into text.</li><li><strong>Translate the text</strong>: You will then use a translation model to translate the text from the source language (like Japanese) to a target language (like English)</li><li><strong>Transcribe speech to text and translate the text in chunks</strong>: No one wants to read a long paragraph of subtitles without knowing which word is related to the current utterance of the speech. You will need to break down the transcription and translation into chunks so you can output the subtitle one short sentence at a time.</li><li><strong>Create the subtitle file</strong>: Just record the text down to the SRT format.</li></ul><p>Note: the same ASR model used in step 2 can be extended to build an interesting chat application that can listen to you via a mic (<a href="https://dartisan.medium.com/how-i-built-a-local-ai-chatbot-that-can-talk-listen-and-read-my-files-675f120098fe">example</a>).</p><h3>What You Need and Tech Stacks Recommended</h3><p>You will need a desktop that can play computer games with decent graphics settings:</p><ul><li>CPU is not the bottleneck, any CPU at minimal, like an old CPU (Intel Core I5–8400 @2.80 GHZ) will do</li><li>Memory: at least 32 GB DDR4 RAM, higher is better.</li><li>Graphic Card: NVIDIA GeForce RTX 4070 Super desktop graphic card or higher; the key is the memory available on your graphics card. You should have at least 12GB GDDR6X to run the model</li><li>Storage: Solid State Drive (SSD) is a must.</li></ul><p>All these components (except the CPU) are getting expensive in the AI Boom Era, so if you managed to get those before 2025, good for you.</p><p>Now for the software part:</p><ul><li>Main IDE: <a href="https://code.visualstudio.com/"><strong>Visual Studio Code</strong></a> or similar</li><li>Main Programming Language: <strong>Python</strong> (No brainer for AI Agent Application)</li><li>You need the <a href="https://developer.nvidia.com/cuda/toolkit">CUDA toolkit</a> for NVIDIA GPU. Version 12.x is required to run the ASR model. If you have upgraded to version 13.x before, then you need a workaround like below</li></ul><pre># Install cublas and cudnn library<br>pip install nvidia-cublas-cu12 nvidia-cudnn-cu12<br><br># Then add the bin path to your python file<br># Find the path to the library binaries inside your virtual environment<br>import os<br>cublas_bin = os.path.join(<br>    sys.prefix, r&quot;Lib\\site-packages\\nvidia\\cublas\\bin&quot;)<br>cudnn_bin = os.path.join(sys.prefix, r&quot;Lib\\site-packages\\nvidia\\cudnn\\bin&quot;)<br><br>os.environ[&quot;PATH&quot;] += os.pathsep + cublas_bin + os.pathsep + cudnn_bin</pre><ul><li>Package Management Tool &amp; Virtual Environment Set Up: <strong>Poetry</strong> is recommended; see this <a href="https://chinsj.medium.com/develop-and-deploy-cli-tool-on-python-with-poetry-and-click-ab62f4341c45">guide</a>.</li><li><strong>ASR Model</strong>: <strong>faster-whisper</strong>. See the user guide and example <a href="https://github.com/SYSTRAN/faster-whisper/blob/master/README.md">here</a>. You don’t need to download the model from HuggingFace; once you specify the model to use in your transcribe method, it will automatically download for the first time and cache it in your local. You do need to be able to read and understand the method signature <a href="https://github.com/SYSTRAN/faster-whisper/blob/master/faster_whisper/transcribe.py#L747-L791">here</a>.</li><li>Software that can run your translation model to serve API requests locally: <a href="https://docs.ollama.com/quickstart"><strong>Ollama</strong></a>. You will need this to translate the subtitles chunk by chunk, by programmatically sending (and serving) the translation api requests for each chunk.</li><li><strong>Translation Model</strong>: <a href="https://huggingface.co/google/translategemma-4b-it"><strong>TranslateGemma</strong></a><strong>. </strong>You need a fast, lightweight model that can run on your local desktop. While qwen3.6 or gemma4 can also do the job, they tend to overthink and consume an unbearable amount of time to translate a short sentence. Models that are specialized for translation, like TranslateGemma or Hunyuan-MT, are significantly more efficient. You can download the model from Ollama.</li><li>Other Python Libraries: <strong>moviepy (VideoFileClip class)</strong> to extract an audio file from the video file. <strong>pydub (AudioSegment class)</strong> to split the audio file into a list of chunks for easier processing. <strong>srt</strong> to write the subtitle file.</li></ul><h3>Example Codes</h3><p><a href="https://github.com/chorlick/pysub/blob/main/main.py">Pysub</a> is one of the projects that does a similar thing as mentioned in this article. You can take a look at the main code for reference. If you are interested in building your own program, I will list some sample pieces of code below.</p><h4><strong>Extract the audio file</strong></h4><pre>from moviepy import VideoFileClip<br><br>def extract_audio(video_path:str, audio_path=&quot;temp_audio.mp3&quot;)-&gt;str:<br>    &quot;&quot;&quot; Extract audio from video file and write it into the audio_path<br><br>    Args:<br>        video_path (str): Path to the video file<br>        audio_path (str, optional): Path to target audio file. <br>          Defaults to &quot;temp_audio.mp3&quot;.<br><br>    Returns:<br>        str: Path to target audio file<br>    &quot;&quot;&quot;<br>    clip = VideoFileClip(video_path)<br>    clip.audio.write_audiofile(audio_path)<br>    return audio_path</pre><h4><strong>Transcribe the audio file</strong></h4><pre>import os<br>import sys<br>from faster_whisper import WhisperModel<br><br># Find the path to the library binaries inside your virtual environment<br># and replace the path text, add it to os path<br>cublas_bin = os.path.join(<br>    sys.prefix, r&quot;Lib\\site-packages\\nvidia\\cublas\\bin&quot;)<br>cudnn_bin = os.path.join(sys.prefix, r&quot;Lib\\site-packages\\nvidia\\cudnn\\bin&quot;)<br>os.environ[&quot;PATH&quot;] += os.pathsep + cublas_bin + os.pathsep + cudnn_bin<br><br>WHISPER_MODEL = &quot;large-v3-turbo&quot;<br><br># We use a class so we don&#39;t have to reinitialize the model for every<br># transcribe request<br>class Transcriber:<br>    T_LANGUAGE = &quot;en&quot;<br><br>    def __init__(self):<br>        self.model = WhisperModel(<br>            WHISPER_MODEL, device=&quot;cuda&quot;, compute_type=&quot;int8&quot;)<br><br>    def transcribe(self, audio_path:str) -&gt; tuple:<br>        # higher beam_size result in more accurate output but took longer<br>        # 5 is a sweetspot to balance accuracy and speed<br>        # no_speech_threshold and condition_on_previous_text is to<br>        # ignore non speech sound<br>        segments, info = self.model.transcribe(<br>            audio_path,<br>            language=self.T_LANGUAGE,<br>            no_speech_threshold=0.6,<br>            condition_on_previous_text=False,<br>            beam_size=5<br>        )<br>        return segments, info</pre><p><strong>Translate the text</strong></p><p>With Ollama running in your background, send the translation request to the Ollama local API.</p><pre>import requests<br><br>def translate_with_ollama(text:str, model:str=&quot;translategemma:4b&quot;)-&gt;str:<br>    &quot;&quot;&quot; Translate text with ollama model<br><br>    Args:<br>        text (str): text to be translated<br>        model (str, optional): Model to use. <br>          Defaults to &quot;translategemma:4b&quot;.<br><br>    Returns:<br>        str: the translated text<br>    &quot;&quot;&quot; <br>    prompt = f&quot;&quot;&quot;<br>You are a professional English (en) to Chinese (zh-Hans) translator. Your goal <br>is to accurately convey the meaning and nuances of the original English text <br>while adhering to Chinese grammar, vocabulary, and cultural sensitivities.<br>Produce only the Chinese translation, without any additional explanations or <br>commentary. Please translate the following English text into Chinese:<br>{text}<br>&quot;&quot;&quot;<br>    response = requests.post(<br>        # This is where ollama serve the api<br>        &quot;http://localhost:11434/api/generate&quot;,<br>        json={<br>            &quot;model&quot;: model,<br>            &quot;prompt&quot;: prompt,<br>            &quot;stream&quot;: False,<br>            # this argument may be required to stop the model from<br>            # over thinking<br>            &quot;chat_template_kwargs&quot;: {&quot;enable_thinking&quot;: False}<br>        }<br>    )<br>    response.raise_for_status()<br>    return response.json()[&quot;response&quot;].strip().strip(&#39;&quot;&#39;)</pre><h4>Process in Chunks and Create the Subtitle File</h4><pre>import os<br>import srt<br>from moviepy import VideoFileClip<br>from pydub import AudioSegment<br>from tqdm import tqdm<br>from datetime import timedelta<br><br>def process_audio(audio_path: str, srt_path: str) -&gt; None:<br>    &quot;&quot;&quot; Process the audio file and write the subtitle file<br><br>    Args:<br>        audio_path (str): Path to the audio file<br>        srt_path (str): Destination Path of the subtitle file<br>    &quot;&quot;&quot;<br><br>    # Define chunk duration and overlap period<br>    chunk_duration_sec = 60<br>    chunk_overlap_sec = 5<br>    chunk_len_ms = chunk_duration_sec * 1000<br>    overlap_ms = chunk_overlap_sec * 1000<br><br>    # Split the audio into chunks for processing<br>    audio = AudioSegment.from_file(audio_path)<br>    chunks = [audio[i:i + chunk_len_ms]<br>              for i in range(0, len(audio), chunk_len_ms - overlap_ms)]<br><br>    # Initialize variables<br>    srt_index = 1<br>    offset = 0.0<br><br>    # last_english is to skip duplicate text in the transribe process<br>    # due to overlap<br>    last_english = None<br><br>    transcriber = Transcriber()<br><br>    # Start producing for each chunks, tqdm is a progress bar tool to help<br>    # you visualize the progress of the transcribe and translation<br>    with open(srt_path, &quot;w&quot;, encoding=&quot;utf-8&quot;) as srt_file, tqdm(<br>        total=len(chunks),<br>        desc=f&quot;Chunks&quot;,<br>        position=1,<br>        leave=False<br>    ) as chunk_bar:<br><br>        for i, chunk in enumerate(chunks):<br>            # Create temporary chunk file<br>            chunk_file = f&quot;chunk_{i}.mp3&quot;<br>            chunk.export(chunk_file, format=&quot;mp3&quot;)<br><br>            # Transcribe the chunk<br>            try:<br>                segments, info = transcriber.transcribe(chunk_file)<br>            except Exception as e:<br>                # log or print if required<br>                chunk_bar.update(1)<br>                continue<br><br>            # For each transcribe segment<br>            for segment in segments:<br>                # get the content and skip if overlap<br>                content = segment.text.strip()<br>                if content == last_english:<br>                    continue<br>                last_english = content<br><br>                # translate the content<br>                translated_content = translate_with_ollama(content)<br><br>                # Use start and end time to build the subtitle position.<br>                start = timedelta(seconds=offset + segment.start)<br>                end = timedelta(seconds=offset + segment.end)<br><br>                # This is optional, you can save only the translated_content<br>                combined_content = translated_content + &quot;\n&quot; + content<br><br>                subtitle = srt.Subtitle(<br>                    index=srt_index, start=start, end=end, <br>                     content=combined_content)<br>                srt_file.write(srt.compose([subtitle]))<br>                srt_index += 1<br><br>            # Update offset and progress bar<br>            offset += (chunk_len_ms - overlap_ms) / 1000.0<br>            chunk_bar.update(1)<br><br>            # Remove the temporary chunk file<br>            try:<br>                os.remove(chunk_file)<br>            except Exception:<br>                # log or print if required<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10b95389b51c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How much Prior Knowledge do you Actually Need to Start Using the AI Coding IDE (like Google…]]></title>
            <link>https://chinsj.medium.com/how-much-prior-knowledge-do-you-actually-need-to-start-using-the-ai-coding-ide-google-antigravity-252aeb9f743d?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/252aeb9f743d</guid>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Sun, 17 May 2026 01:45:35 GMT</pubDate>
            <atom:updated>2026-05-17T01:46:57.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>How much Prior Knowledge do you Actually Need to Start Using the AI Coding IDE (like Google Antigravity) for Software Development?</h3><p>I will say it&#39;s a lot for people who don’t have a programming background, if you want to truly understand what you are doing, and why we do this instead of that.</p><p>The reference tutorial is available in Google codelabs for free: <a href="https://codelabs.developers.google.com/getting-started-google-antigravity?hl=en#0">https://codelabs.developers.google.com/getting-started-google-antigravity?hl=en#0</a></p><p>Assume you went through sections 1 to 5 and landed on section 6 — Editor.</p><h3><strong>1. The Command Line Terminal</strong></h3><p><strong>What is it?</strong> A text-based interface used to interact with any software program.</p><p>Regular people are familiar with interacting with the software using a Graphical User Interface (GUI), where there is always a button that you can click for a specific action. This applies even with the BIOS start-up screen, where the desktop builder often works with it when setting up their desktop for the first time or to fix Operating System and hardware problems.</p><p>However, not all software programs come with a built-in GUI interface. The only way, and often the most efficient way, to interact with a software program is through the command line interface (CLI). The CLI interface also enables cross-program interaction, where you can pass the output of program A as input to program B, or call program C automatically using a script when using program B.</p><p>The command line terminal then allows you to do the following</p><ul><li>Enter the command in the text</li><li>Read the text output</li></ul><p>The terminal itself is usually an Operating System session, acting as the intermediary (translator) between your commands and the machine language, interpreting the commands you input and translating machine output to you.</p><h4><strong>Understand the Command Line Interface Environment</strong></h4><p>The majority of software developers work within a Bash / zsh shell environment within a Unix-like operating system (Linux, macOS). Bash itself will normally take a few hours to learn, where one of the must learn is how to use the ~/.bashrc (or ~/.zshrc file) for environment variable setup.</p><p>For the majority of beginners, the most common pain point is that they have a Windows machine (as it&#39;s usually cheaper to buy a Windows laptop/desktop than an Apple machine of the same hardware specs). Windows has its own command prompt interface and PowerShell interface for a CLI environment. These have a different command syntax compared to the Bash / zsh shell (actually, Bash and zsh shells have a different set of command syntax as well).</p><p>So if you are following a tutorial for learning, and somehow the commands didn’t work, most of the time you should check if the environment you are using is the same as the environment used in the tutorial.</p><h3><strong>2. The Programming Language</strong></h3><p>Antigravity uses Python as the default programming language. The question you might want to ask is, what are the alternative programming languages? Why choose Python?</p><p>There are several popular alternative programming languages, and each suits a different set of use cases.</p><p>JavaScript (and TypeScript) are most popular in building front-end web applications due to the React framework.</p><p>Java is popular for building enterprise-level, high-concurrency applications. The Spring and Spring Boot frameworks also provide boilerplate code that helps make building a new application easier.</p><p>C++ is predominantly used in high-frequency trading systems.</p><p>Python is popular within the data science community due to its pandas and numpy libraries. It is also dominant in machine learning (AI) scenarios with the PyTorch framework.</p><p>There are also some notable newcomers like Rust and Go, which aim to do better than the mentioned programming languages in a particular area.</p><p>Above all, there is one important distinction that all programmers must know: the difference between a <strong>static-typed language</strong> and a <strong>dynamically typed</strong> language. In summary, a static-typed language like Java will check the compatibility of the variables being processed during compilation time, before you even run the program. One example of static checking is below.</p><pre>public class MyClass {<br>    // A method that returns an integer<br>    public static int addNumbers(int a, int b) {<br>        return a + b;<br>    }<br><br>    // Let say we define another funtion use the addNumbers call<br>    public static List&lt;string&gt; processPairs(List&lt;string&gt; listA, List&lt;string&gt; listB){<br>        List&lt;string&gt; results = new ArrayList&lt;String&gt;();<br>        for (int i = 0; i &lt; listA.length; i++) {<br>            // This will throw error during compilation type, <br>            // as you cant pass string as int to the input<br>            // and use the int output to add to the list of string<br>            results.add(addNumbers(listA.get(i), listB.get(i));<br>        } <br>    }<br>}</pre><p>The benefit of type checking is huge — it significantly reduces the number of run-time errors that are difficult to debug. That&#39;s why TypeScript (essentially JavaScript with type checking capability) became popular.</p><p>While popular for its flexibility, Python is a <strong>dynamically typed</strong> language. Using Python without type hints and type checking practice is essentially inviting tons of run-time errors when the program gets complex. Thus, it is essential to implement type checking with Python using Mypy or a similar library.</p><h3>3. The Rules &amp; Workflows</h3><p>First, you should notice the distinction between the file directory to store the global rule and the workspace rule.</p><p>Global rules are stored in `~/.gemini/GEMINI.md.` location. ~/ denotes this is your home directory. Because it is in your home directory, when you are working within a new folder, you can refer to the rules again (hence it is Global). The `.gemini` tells you this is a specific folder for the Gemini application. The . tells you the folder should be hidden and not touched by other non-Gemini applications.</p><p>Every programming language has its own <strong>style guide </strong>and comment style. <a href="https://peps.python.org/pep-0008/">PEP 8</a> is the official style guide for Python.</p><p>Before the AI Coding era, it used to be very important to write good docstrings for functions and classes. Two popular <strong>docstring</strong> styles for Python are <a href="https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#google-vs-numpy">Google and Numpy</a>. The docstring is supposed to provide context beyond the code on what the function actually does.</p><pre># Example Google DocString style<br>def func(arg1:int, arg2:str)-&gt; bool:<br>    &quot;&quot;&quot;Summary line.<br><br>    Extended description of function.<br><br>    Args:<br>        arg1 (int): Description of arg1<br>        arg2 (str): Description of arg2<br><br>    Returns:<br>        bool: Description of return value<br><br>    &quot;&quot;&quot;<br>    return True</pre><p><strong>Testing</strong> if your function can handle all intended scenarios is the most important part of programming. Each programming language has its own popular testing framework for automatic testing.</p><p>For Python, the popular testing framework is <strong>pytest</strong>. The testing <strong>coverage</strong> report will reveal the percentage of the lines and branches that are covered by the test cases. Ideally, we should aim for 100% coverage to check for all edge cases.</p><h3>4. The Algorithms</h3><p>The antigravity tutorial showcases the algorithm for Binary Search and Bubble Sort. The available contents in the Data Structure and Algorithm space are a lot more, and often take a programmer months and even years to learn and master.</p><p>In the AI Coding era, two important concepts you need to ask the agent are what the <strong>time complexity</strong> is and what the <strong>space complexity</strong> is.</p><p><strong>Time complexity </strong>determines how fast the program will run; an algorithm with O(n) time complexity will run faster than an algorithm with O(n²) time complexity.</p><p><strong>Space complexity</strong> determines how much memory the program will require; an algorithm with O(n) space complexity will require much more memory in handling large data compared with an algorithm with O(1) space complexity.</p><p>If you feel that your program is running too slowly, you should ask the agent to improve the time complexity. Sometimes you can achieve better time complexity by trading off space complexity.</p><h3>5. What’s Missing: Continuous Integration / Continuous Deployment (CI/CD) Workflow</h3><p>The Antigravity tutorial shows how you can develop a simple application that runs locally; subsequent <a href="https://codelabs.developers.google.com/build-and-deploy-gcp-with-antigravity#7">tutorials</a> also show you how you can deploy your application to the cloud. But software development within the big technology companies will go far beyond that as the complexity increases, dependencies increase, and more developers are involved in building the software program.</p><p>To collaborate with others, Source Control Management (SCM), like <strong>Git</strong>, allows you to do two things</p><ul><li>Collaborate with others on the same software package.</li><li>Revert individual commit without affecting other parts of the software package.</li></ul><p>As your software program is getting more complex, you will start using more external libraries (known as dependencies) in your program. Each of these libraries may be released in different versions, and software of different versions may not behave the same.</p><p>A <strong>package manager like Poetry </strong>with version control is important for managing your dependency packages, especially when others develop them, as someone may introduce breaking changes that result in incompatibility issues among them. The package manager also helps you automate the build, format, lint (style check, type checking), and test process. And ensure that other developers are using the same configurations, so they can build and run the software package as you do.</p><p>If you are building a website or api services, you will need to host your application with one of the cloud service providers. A popular choice is to wrap your server within a <strong>Docker</strong> container and use <strong>Kubernetes</strong> or a similar <strong>container orchestration service</strong> (like <strong>AWS ECS with Fargate</strong>) to scale it when required.</p><p>As you need to use more and more of the infrastructure, you will need to set up deployment actions to autoconfigure the infrastructure resources required as well, either through <strong>Terraform </strong>or the <strong>AWS CDK</strong> service.</p><p>As your deployment gets more complex, you will need a service that automatically runs the deployment actions whenever there are new code changes. These actions include automatically building and testing the code, provisioning the cloud resources required, creating Docker containers for your application, and replacing the current running services with newer versions gradually. This is where full <strong>CI/CD</strong> services like <strong>Jenkins/Github Actions / AWS CodePipeline / Azure DevOps</strong> came into the picture.</p><p>The CI/CD services also work with Cloud Services to handle production disruption, such as automatically scaling out when required, and reverting/rolling back when new code introduces new issues.</p><h3>In Summary</h3><p>While AI Coding Agents help lower the qualifications/skills/experience required to develop a software product, it does not reduce the prior knowledge required to build production-ready software. On the contrary, it made having this prior knowledge more important as the coding agent became more powerful. Vibe coding without prior knowledge is like giving a teenager control of a modern commercial plane; eventually, it is a recipe for a crash.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252aeb9f743d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Quick Note 1 — IAM Role, Permission, and Trusted Entity]]></title>
            <link>https://chinsj.medium.com/aws-quick-note-1-iam-role-permission-and-trusted-entity-30d74b49c76e?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d74b49c76e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[iam-policy]]></category>
            <category><![CDATA[iam-roles]]></category>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 20:10:09 GMT</pubDate>
            <atom:updated>2026-01-03T20:10:09.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Quick Note 1 — IAM Role, Permission, and Trusted Entity</h3><p>There is a lengthy official <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html">guide</a>. This note is just a summary of the most fundamental concepts IMO to help get started with.</p><p>An AWS Root Account / Administrator Role has access to all the AWS resources within the service quota limit. Thus, you dont want your application to have root / administrator-level access, as if someone can gain access to your application, they can do anything they want with your money/data.</p><p>The immediate solution is to create an IAM role for your application, and grant the Permission to access specific resources with specific actions only with that role. Following the principle of least privilege access, an application with the role having read permission on a specific S3 bucket (say bucket A) will not be able to write to S3 bucket A or read another S3 bucket.</p><p>All IAM roles within the same AWS account have access to resources within the account as long as the permission permits. However, quite often we will build our application in different AWS accounts. Cross-account access is by default forbidden.</p><p>This is where the trusted entity came into the picture. The way it works is as follows:</p><ul><li>Say account A hosts an API Gateway serving API requests. The developer will create an IAM role (Role A) in account A that can execute the API. And within the role, <strong>add account B as the trusted entity</strong>.</li><li>Account B will create a role (Role B) for the application. This role will have a permission policy similar to below, where it can perform the <strong>sts: AssumeRole action limited to the role resource Role A </strong>from account A.</li></ul><pre>{<br>&quot;Version&quot;: &quot;2012–10–17&quot;,<br>&quot;Statement&quot;: <br>  [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:iam::AccountA:role/Role A&quot;<br>    }<br>  ]<br>}</pre><p>In summary, for cross-account access where application App B from account B needs to access the application App A from account A, we need to</p><ol><li>Create an IAM Role (Role A) with permissions to access App A.</li><li>Add Account B (or more specifically, App B) as a trusted entity to assume Role A.</li><li>Create an IAM Role (Role B) with permissions to perform the sts: AssumeRole action with the role resource Role A.</li><li>Attached Role B to application B.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d74b49c76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I think about Agentic AI — 2025 EoY edition]]></title>
            <link>https://chinsj.medium.com/what-i-think-about-agentic-ai-2025-eoy-edition-f91dac3f4641?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91dac3f4641</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 23:55:57 GMT</pubDate>
            <atom:updated>2025-12-28T23:55:57.476Z</atom:updated>
            <content:encoded><![CDATA[<h3>What I think about Agentic AI — 2025 EoY edition</h3><p>Note by Agentic AI: I mean <strong>Large Language Model</strong> or <strong>Multimodal generative AI </strong>or<strong> AI Agents, </strong>or<strong> Agentic AI or Coding Agents; </strong>there are subtle differences between the terms, but for these rambling pieces, they mean the same.</p><h3>AI can destroy the world only if someone gives it a tool to do so</h3><p>This part is for the people who have never built an agentic AI application. The latest State Of The Art (SOTA) LLM / Multimodal Generative AI like Gemini, Deepseek, GPT, Claude Opus/Sonnet, QWEN, etc, only does one thing: given an input media (texts, image, audio, video), then output the response media (texts, image, audio, video).</p><p>Beyond the media, the AI Agent’s interaction with the rest of the world, whether it&#39;s software (like a computer program, the internet, or a database) or hardware, can only be done via a function tool within a programming language. In other words, AI can destroy the world only if the developer does the following</p><pre># create a tool that can do harm<br>@tool<br>def release_harm(input):<br>    # Code that link to physical world like a missle system. <br><br># Pass the tool to agent<br>agent = Agent(tools=[release_harm])</pre><h3>The Best Safeguard to Ensure AI Safety is on Front Runner’s Moral Compass</h3><p>This is a controversial topic. I will lay down my opinion instead of an argument supported by facts (the latter would require a much deeper dive).</p><p>It would be nearly impossible to regulate on the end-user / developer side. There could be more than a few hundred thousand software developers working to build an Agentic AI application now, with some of them may intentionally / unintentionally give the AI access to tools that have great potential to cause harm. There are hundreds of millions of users now interacting with the AI daily, some of them are already asking questions to acquire knowledge on how to harm others or themselves.</p><p>The fewer the targets to be monitored and regulated, make easier it is for the regulator to enforce AI Safety. At the same time, due to the proliferation of the open source models (DeepSeek, Llama, QWEN), regulating at the application or platform level (like regulating ChatGPT) is not enough, as capable developers can just download the open source models and run them on their own hardware. If we want a high level of AI Safety, we need to <strong>build in the safety mechanism within the model</strong> itself. Ie, the model shouldn’t output the response if it detects that the information it gave could cause harm. But this will lead to the following two issues.</p><p>How can the model differentiate between whether the user is asking for information to avoid harm or asking for information to cause harm? There is a joke that if you directly ask the AI how to manufacture a drug, it will say no, but if you ask the AI how <strong>not to </strong>manufacture drugs that can cause hallucination, it will lay out the steps to avoid (which can be reversed to manufacture a drug)</p><p>Incorporating restrictions and built-in safety mechanisms may reduce the model&#39;s capability or slow down the development process. At today’s vibe, where every LLM company is racing to beat others on the benchmarks, they are more likely to accept the consequences of the side effects (which is hard to quantify the magnitude and the percentage of responsibilities they should bear) rather than losing out on the race to AGI.</p><h3>Builders (SDEs) are now (Technical) Product Managers, and Agents are now SDEs in the Vibe Coding era</h3><p>This is the analogy that I resonated with the first time I saw it.</p><p>In the past, a software development project started when</p><ul><li>The (Technical) Product Manager came out with a set of initial feature requirements.</li><li>The builders then proceed to design, develop, and test out the application.</li><li>The Product Manager examines the implemented features during the User Acceptance Test (UAT).</li><li>The Product Manager highlights the list of issues discovered or adds some new requirements based on the initial user experience.</li><li>The builders proceed to re-architect / fix the bugs / add new features to the application, and the cycle continues.</li></ul><p>Essentially, the same thing we are doing with the Vibe Coding / AI Coding</p><ul><li>The Builders (SDEs) came out with the set of initial requirements or technical specifications.</li><li>The Agents proceed to vibe code.</li><li>The builders examined the implemented code and test cases and tested out the features.</li><li>The builders provide feedback to the agent to improve.</li></ul><p>We probably need more Technical Product Managers with SDE experience in the future rather than more SDEs.</p><h3>AI Creates Slops, and It can be Compounded or Reduced</h3><p>If you create your Agent System in a straight-line workflow, the slops created by the AI can be compounded. For example, if your workflow consists of three agents: A -&gt; B. And each agent has an average probability of 80% to do the task given correctly. The chances of you getting the correct results out of your system are 0.8 ^ 2 = 64%.</p><p>However, if your workflow contains a feedback loop, like A -&gt; B, then -&gt; A if an error is detected, then theoretically, we can improve the accuracy rate to 94% ( provided Agent B has an accuracy of 80%, ie if Agent A produced the correct results, Agent B still has 20% chance of returning it, and if Agent A produced the slop, Agent B still has 20% chance to let it pass, the maths are a bit complicated but we will end up with the inaccuracy rate as the sum of infinite geometric series of 4% * (0.32)^n for n from 0 to infinity which is closer to 6%).</p><h3>There is a limit on the Software Development Efficiency gain with Coding Agents</h3><h4>What percentage of time does a Full-Time SDE actually spend on Coding?</h4><p>Let&#39;s do a simple calculation. A Software Development Engineer (SDE) usually spends</p><ul><li>10% of time for leaves (Public Holidays, PTOs, Sick Leaves)</li><li>10–20% of the time for administration (Daily stand-ups, Weekly meetings, Sprint Planning, Org Level Meetings, Learnings and Design Review, alignment meetings) . The higher the level, the more time the SDE would spend on this.</li><li>10–20% of the time for on-call.</li><li>10–20% of learning/refreshing the knowledge required for the software development.</li><li>10–20% of time doing Code Review for other peers’ Pull Request (PR).</li><li>That&#39;s like 10–50% (or an average 30%) of time left for coding.</li></ul><p>For the time left on coding, Coding Agents can speed up / reduce the time required by 30–40%? Coding Agents are good at writing unit tests and implementing simple functions, but for more complex features/code modifications, we still need time to deliberate on the implementation architecture from a holistic point of view.</p><h4>Even if Coding Efficiency can increase 5x, the Bottleneck is still the Review Part</h4><p>It&#39;s simple math, one SDE can create a PR with 200 lines of changes, and it would take two of the peers to spend 30 minutes — 1 hour each to review the PR.</p><p>Now, let&#39;s assume with the Coding Agent’s help, an SDE can create 5 PRs instead of 1 PR now. The time required to review the PR is now multiplied by 5x. If the ratio of time spent on coding vs time spent on review was 3:1 previously, even if we reverse the ratio now to 1:3, the review process can only accommodate a productivity improvement of 3x instead of 5x.</p><h4>The only way to speed up is to reduce the Human in the Loop, aka Vibe Coding</h4><p>This will work when the product you want to build is of a Proof of Concept (PoC) type, or the consequence of an error is low.</p><p>But if you are refactoring a system where many services are depending on it (like AWS or Windows), or a system handling important information (Government Services or Financial Data), can you / dare you completely trust the agent and leave humans out of the loop?</p><p>Another uncontrolled variable with Vibe Coding is the cost. There is a story where a team builds an agent system with multiple agents, where a pair of the agents end up communicating with each other back and forth in a deadlock and endless loop, and end up costing the team $47K of token costs per week.</p><p>And for SDE, another reason to avoid relying too much on the agent is the intelligent degradation that comes with over-reliance on the tool. You rely on the agent to do most of the coding, where you end up losing your ability to code and the ability to code against the common pitfalls and bugs.</p><h4>There are three kinds of lies: lies, damned lies, and statistics</h4><p>Here is an interesting <a href="https://www.youtube.com/watch?v=SZStlIhyTCY">video</a> from McKinsey &amp; Company that suggests Coding Agent can speed up the development work by 2–5x.</p><p>Leaders who are inspired by the talk and determined to drive productivity gain within their organization should be cautious about <strong>what kind of metrics they will measure to benchmark for productivity gain</strong> and the behavior the metrics will encourage.</p><p>If you are measuring productivity gain based on the number of PRs -&gt; the developers can just split changes previously done in one PR into two PRs and celebrate the gain.</p><p>If you are measuring productivity gain based on the number of lines of Code, the following two approaches of writing the function do the same thing. The first approach needs 13 lines of code while the second approach needs only two lines of code. Will you say approach 1 is better than approach 2?</p><pre># Approach 1<br>def add_by_10(num:int)-&gt; int:<br>    new_num = num<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    new_num += 1<br>    return new_num<br><br># Approach 2<br>def add_by_10(num:int)-&gt; int:<br>    return new_num + 10</pre><p>If you are measuring productivity gain based on the number of features released, now given a theoretical example below:</p><p>First group of features:</p><ul><li>Support weather query for US cities with a population of more than 50.</li></ul><p>Second group of features:</p><ul><li>Support weather query for cities in Washington state.</li><li>Support weather query for cities in California.</li><li>Support weather query for cities in Texas.</li><li>Support weather query for cities in Michigan.</li><li>Support weather query for cities in Massachusetts.</li></ul><p>Would you say the second group of features delivers more compared to the first group of features?</p><h3>There is still an endless possibility to use AI to speed up the automation work</h3><p>AI is good at tasks with simpler contexts. Gemini 3 can solve Leetcode questions within a few minutes that many SDEs are struggling with.</p><p>As the task gets more complex, the accuracy drops. This is where we need the SDEs to develop the Agentic AI system that reduces the slop by introducing a multi-agent system, improving the tools, etc. (An Interesting reader can see this <a href="https://medium.com/@chinsj/quick-guide-on-building-ai-agents-with-strands-agent-framework-0c8619a4c017">guide</a>)</p><p>But even so, the emergence of generative AI has already helped us tackle one of the most challenging problems in software development -&gt; I call it the problem of the rigidity of input requirements that meet a variety of real-life conditions. Let me try to explain</p><p>Let&#39;s say we want to develop a simple app that gathers the favorite colors through conversation with the user and outputs a designer cloth based on the chosen color. We may start with the following code</p><pre>def create_cloth(color:str) -&gt; Cloth:<br>    if color == &quot;Blue&quot;:<br>        return BlueCloth()<br>    elif color == &quot;Green&quot;:<br>        return GreenCloth()</pre><p>Here is a list of issues that the code eventually needs to handle</p><ul><li>We need to extract the color from the message input by the user. If the user says, My favorite color is Blue then we need to capture the “Blue” keyword.</li><li>What is instead of saying Blue, the user says blue or sky blue?</li><li>We can use a dropdown selection to capture exactly which color the user wants. Can we expand the code to cover more options, like Red or Yellow, or eventually 256 combinations of color?</li><li>If you think letting the user choose the RGB values, you have to assume the user knows what the RGB value is for their favorite color, or create a tool that lets the user choose based on a palette.</li><li>Now, imagine the create_cloth function is actually part of the data processing pipeline. Aside from fixing the API agreement between the callers and the function being called, we might also need to fix the input choice with an enum.</li><li>And in the future, if there are new requirements/edge cases, we need to modify the function to handle them.</li></ul><p>With the emergence of generative AI, we dont need to write the create_cloth function anymore, we just need to pass the prompt to the agent for it to help generate an image of clothing with the specified color. And it can adjust based on user feedback.</p><p>Based on some of my previous working experiences, I can list a few scenarios where AI can speed up the work. Note that things may have changed over the past few years.</p><h4>All Documentation work can be automated and done fast</h4><p>Whether it is</p><ul><li>comparing the <a href="https://www.asme.org/codes-standards/bpvc-standards">ASME Boiler and Pressure Vessel Code (BPVC)</a> with China’s GB code,</li><li>Contract Review,</li><li>Form filling,</li><li>Permit to Work (PTW) review,</li><li>Creating and reviewing a process isolation plan</li><li>Risk Review,</li><li>drafting project documentation,</li><li>querying existing documentation and standards for information</li></ul><p>All that paperwork that we find tedious can be handled by AI.</p><h4>AI can create Tools to help Engineers Handle Data</h4><p>A Boiler inspection engineer for a coal-fired power plant spends quite a lot of time on</p><ul><li>Developing the inspection plan, communicating the inspection plan with the inspectors, and requesting them to record in a specific format.</li><li>Comparing the inspection records of different periods, calculate the rate of thinning and determine the next course of action (which section of tubes needs to be replaced, etc).</li></ul><p>Most of the actions can be done in Excel, but Excel is not good at handling variety and alignment between results of different formats.</p><p>We might eventually need a Data Engineer who</p><ul><li>Design a data schema to store the data</li><li>Write the program to sanitize/reorganize the input data</li><li>Write the data pipeline and handling logic to determine what to inspect</li><li>Write the program to output the inspection requirements in a form</li><li>Write the data pipeline and prediction logic to determine the next course of action.</li></ul><p>Having a Data Engineer with the inspection team is a luxury. A smaller Independent Power Producer (IPP) might not have the budget to hire one. But all of the Data Engineer’s tasks can be handled by an AI coding agent.</p><h4>Eventually Specialized Agent (with Fine-tuning Model) can perform better than an Expert Engineer whose main job is to act based on the data.</h4><p>To be honest, I’m not entirely sure about this, but my gut feeling is that this is a high-value field that could be tackled by the AI agent.</p><p>My previous job as a Production Support Engineer was to optimize the overall production of an oil-producing platform within system constraints while adhering to the reservoir management guidelines. The optimization process can be summarized in the following steps</p><ol><li>Understand each of the system constraints and reservoir management guidelines. For example, the total gas that can be handled by the top top-side gas processing facility could be 300 MMscf per day. We can have 10–20 oil-producing wells, with each having a target gas-to-oil ratio that we want to keep within.</li><li>Having some tools that help with the calculations, it could be simulation tools or just a simple look-up to the relationship chart, and an Excel spreadsheet for summation.</li><li>There will be an iterative process where we will start with a set of initial targets, calculate the results, and adjust the initial values based on them. In a more complex case, the output of the wells could affect each other (since they share the same pipeline) and result in actual values that differ from the initial estimation, where we need to further adjust based on that.</li></ol><p>We can build an Agent System to do the same work.</p><ul><li>We can start with fine-tuning the base model with the Well Reservoir and Facility terms. For a big international oil firm, they will have the resources to pay for this, and it can be used by the entire company.</li><li>We can build the Agent System with the required tools and data pipeline to feed the production data into it. An international oil firm could have hundreds of producing platforms, but it will use only two or three different production data systems.</li><li>We can add a localized layer to feed information specific to a particular platform only.</li></ul><p>The benefits of the agent could be huge.</p><ul><li>In the long run, the operating cost (tokens and infrastructure) can be less than the cost of hiring a specialized engineer.</li><li>And the operator can now have access to the expert 24 x 7.</li></ul><h3>How the Future of AI coding will Unfold?</h3><p>Let me lay some predictions at the end unresponsively.</p><p>Overall, there will be less demand for Software Development Engineers, especially at the entry level, as the efficiency gain from Coding Agents is real, even though the magnitude is debatable.</p><p>Only those SDEs who can handle complex tasks better than AI, or heavily (blindly) use AI, can survive. Eventually, if you refuse to use AI or cannot perform at a level equal to those who use AI, you may be at the top of the list to be let go. The productivity gains with AI Coding are debatable, but the vibe to drive productivity gain can weed out those who cannot keep up with this wave.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91dac3f4641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Guide on Building AI Agents with Strands Agent Framework]]></title>
            <link>https://chinsj.medium.com/quick-guide-on-building-ai-agents-with-strands-agent-framework-0c8619a4c017?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c8619a4c017</guid>
            <category><![CDATA[strands-agents]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 05:15:54 GMT</pubDate>
            <atom:updated>2025-12-23T05:15:54.164Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preface</h3><p><strong>Python</strong> is the best choice of programming language when it comes to building an Agentic AI system because of the following reasons:</p><ul><li>The majority of the agentic framework started with Python SDK support before other languages (like TypeScript). The Python version will contain the latest, greatest, and expanded classes, functions, and features that developers can use.</li><li>Python has a rich library for machine learning and data science applications (think of pandas, numpy, etc)</li></ul><p>Hyperscalers (Cloud Service Providers like AWS) are currently providing <strong>API access</strong> to use the latest State Of the Art (SOTA) Large Language Model (LLM) like Claude Sonnet 4.5, Claude Opus 4.5, etc. In the AWS case, we can directly use the Boto3 (Software Development Kit provided by AWS to access their services) Python SDK to send a prompt to a targeted LLM model.</p><p>Or we can also use an <strong>Agentic Framework</strong> (like Langgraph, Strands Agent) to create an Agent / Graph to work with the LLM. The benefit of doing so is that the Agentic Framework already has a boilerplate implementation of a ReAct (Reasoning and Act) agent, integration with the common LLMS hosted on hyperscalers, and provides other boilerplate functionality, such as tool usage and graph building.</p><p>To put the agent system into production, we can run our code from a compute instance, from a container, or using a <strong>managed service</strong> like Amazon Bedrock AgentCore. Managed services can be costlier, but usually provide better supporting features, such as integration with memory, observability (span &amp; traces), and identity and policy, which help reduce the time required to prototype and build products that reach the market.</p><p>In this article, I will mainly work with Python, Strands Agent, and Amazon Bedrock AgentCore services to showcase what you can do with the agent.</p><h3>Let&#39;s Take a Quick View of the Financials</h3><p>How much an agent system in a production environment costs you will largely depend on your usage, the LLM model used, and the agent architecture. I will walk through a hypothetical system with a three-agent, integrates with one Kendra AI-powered knowledge base and AgentCore Memory, serving 100 requests per day.</p><h4>Kendra Knowledge Base</h4><p>The lowest priced <a href="https://aws.amazon.com/kendra/pricing/">GenAI Enterprise Edition</a> is currently charging $0.32 per hour for 1 base unit (Storage + Query) + a Flat price of $30 per month.</p><p>If you start with a Kendra-powered knowledge base, you will be looking at 30 x 24 x $0.32 + $30 = $260.4</p><h4>Tokens Cost</h4><p>Price of LLM Invocation on Amazon Bedrock</p><ul><li>Claude 4.5 Opus — Input Token ($5 per million token), Output Token ($25 per million token)</li><li>Claude 4.5 Sonnet — Input Token ($3 per million token), Output Token ($15 per million token)</li><li>Claude 4.5 Haiku — Input Token ($1 per million token), Output Token ($5 per million token)</li></ul><p>A three-agent system, where each agent has access to multiple knowledge base tools, with a max node execution of 10, will use about 50k — 200K input tokens, with around 1/10th output tokens.</p><p>Say 100k input, 10k output, and your agent system will serve 100 API requests. With 4.5 Opus, you will be looking at 100 * 30 * (0.1 * 5 + 0.01 * 25)= $2250 per month, with 4.5 Sonnet, it will roughly be $1500.</p><h4>Other Cost</h4><p>Memory pricing</p><p>Short Term Memory — $0.25 per 1000 new events</p><p>Long Term Memory — (Storage) $0.75 per 1000 events stored. (Retrieval) $0.5 per 1000 events retrieved.</p><p>Say only the entry agent will have the integration with the memory, with the 3x memory event stored and 1x long-term memory retrieval per request, and the memory event will be stored up to 6 months.</p><p>Cost :</p><ul><li>Short term storage $0.25 x 3 x 100 x 30 / 1000 = $2.25</li><li>Long term storage $0.75 x 3 x 100 x 30 x 6 / 1000 = $40.5</li><li>Long term retrieval $0.5 x 1 x 100 x 30 / 1000 = $1.5</li></ul><h4>Summary</h4><p>In this example, the token cost looks like the largest cost component. A fully functional system will probably cost you around $2000 per month. Cost increases with higher requests, better LLM models, etc. Note that this analysis omits some other AWS costs, which could be significant as well.</p><h3>The Technical — Building Agents from the Ground Up</h3><p>Let&#39;s start to build the agent from ground zero, starting from the simplest use case, gradually adding capabilities to the agent when leveling up.</p><h4>Level 0 — Basic Invocation</h4><p>The most basic agent is to call (invoke) the LLM model directly. Take any model hosted on AWS Bedrock as an example. What you need to do is</p><ul><li>Create a bedrock-runtime client using boto3</li><li>Use the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse.html">converse</a> and <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse_stream.html">converse_stream</a> api. The first one is for direct invocation, while the second one is for streaming (async) invocation. For simple invocation, you only need 1) a Model ID to call and 2) the prompt text. For more details, you should read the API pages.</li></ul><pre>import boto3<br><br># Step 0 assume you have valid AWS credentials set up <br># Step 1 create the bedrock-runtime client<br>client = boto3.client(&#39;bedrock-runtime&#39;)<br><br># Step 2 start the invocation using converse API<br>response = client.converse(<br>    # Step 2a provide a Model ID<br>    modelId=&#39;us.anthropic.claude-sonnet-4-5-20250929-v1:0&#39;,<br>    # Step 2b provide prompt with the messages<br>    messages=[<br>        {<br>            &#39;role&#39;: &#39;user&#39;,<br>            &#39;content&#39;: [<br>                {<br>                    &#39;text&#39;: &#39;string&#39;,<br>                },<br>            ]<br>        },<br>    ],<br>)</pre><h4>Level 1 — Upgrade it to ReAct Agent</h4><p>You should notice that the converse API contains a ton of parameters that you can supply your arguments to:</p><ul><li><strong>modelId </strong>— The LLM model you want to use</li><li><strong>messages </strong>— The conversation history between you and the model. This is where you can supply the previous conversation into the current invocation call so the current LLM will have the “context” / “memory” of what you have been talking to it.</li><li><strong>system </strong>— Place for System Prompt, which tells the LLM how to react to a user prompt</li><li>InferenceConfig — Include model-specific parameters like temperature, maxTokens, etc.</li><li><strong>toolConfig</strong> — Provide definition of the tools for the LLM model to use</li><li><strong>guardrailConfig </strong>— <a href="https://aws.amazon.com/bedrock/guardrails/">Bedrock-specific guardrail </a>that the LLM model will use</li><li>etc etc</li></ul><p>If you are just building a prototype or testing out, and you want to have extra capability (like manipulating messages to enable conversation experience with the LLM), it will be impractical to write your own code to deal with every parameter.</p><p>This is where <strong>Agent frameworks </strong>like LangChain/LangGraph/Strands Agent came into the picture. They provide boilerplate code for a Reasoning and Act (<strong>ReAct</strong>) agent, which you just need to pass in a few arguments to implement an Agent. The agent can reason based on input given, use the tools provided, and remember conversations with you as long as you are talking with the same <strong>agent instance</strong> (By instance, it means a Python object instance within the runtime lifecycle).</p><p>Strands has a good example of a simple agent in <a href="https://strandsagents.com/latest/documentation/docs/examples/python/weather_forecaster/#creating-the-weather-agent">Weather Forecaster</a>. Extracting only the skeleton parts is shown below. Note: http_request is a custom tool available in the <a href="https://pypi.org/project/strands-agents-tools/">community package.</a> You can use an existing one available or create your own tool.</p><pre>from strands import Agent<br>from strands_tools import http_request <br><br># Define a weather-focused system prompt<br>WEATHER_SYSTEM_PROMPT = &quot;&quot;&quot;You are a weather assistant with HTTP capabilities.&quot;&quot;&quot;<br><br># Strands Agent by default will use claude-sonnet-4 model on Bedrock<br># you can customize the model use as below. <br>bedrock_model = BedrockModel(<br>    model_id=&quot;anthropic.claude-sonnet-4-20250514-v1:0&quot;<br>)<br><br># Create an agent with HTTP capabilities<br>weather_agent = Agent(<br>    model=bedrock_model<br>    system_prompt=WEATHER_SYSTEM_PROMPT,<br>    tools=[http_request],  # Explicitly enable http_request tool<br>)<br><br># Start interacting with the model<br>input_prompt = &quot;What&#39;s the weather like in Seattle?&quot;<br>response = weather_agent(input_prompt)</pre><h4>Level 1.5: Adding Tools to Extend the Capability of the Agent (like RAG)</h4><p>You can start adding <a href="https://strandsagents.com/latest/documentation/docs/user-guide/concepts/tools/custom-tools/"><strong>tools</strong></a> to extend the capability of the Agent. There is a <a href="https://strandsagents.com/latest/documentation/docs/user-guide/concepts/tools/community-tools-package/">community tools package</a> that contains some of the pre-built tools that you can use. In the previous example, the http_request is a community tool that allows the agent to search the internet.</p><p>One of the most common uses of the tool is to add a knowledge base tool (basically a vector store) to the Agent to build a <strong>Retrieval Augmented System (RAG), </strong>where the agent can try to pull the context from your data store before answering the questions. Interesting readers can explore the <strong>Bedrock </strong><a href="https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html"><strong>Knowledgebase</strong> </a>offered by AWS. Some of the key notes to know are as follows:</p><ul><li>The strands community tools package has a retrieve tool to retrieve relevant context from the bedrock knowledge base. Unfortunately, the tool currently only supports one knowledge base hardcoded. You will need to implement your own if you need to link to more than one knowledge base.</li><li>Bedrock Knowledgebase can be of two main types: structured data and unstructured data. The structured data type requires a Redshift query engine connected to a database.</li><li>The unstructured data type can connect to multiple data sources. One of the options is to add a Kendra AI Index layer to the data sources. But as we analyzed earlier, this could be expensive.</li></ul><h4>Level 2: Put the Agent into Production by Integrating with AgentCoreRuntime</h4><p>Most online courses&#39; content will stop at level 1, which is where you will run your code on a Jupyter Notebook instance or on your local VS Code editor, with an API token access to one of the online LLM models. Some courses may introduce you to the Fast API framework to start serving an API request.</p><p>But if you are serious about putting your agentic system into production, you need to start considering where to host your agent. You can either run it on a compute instance (like AWS EC2), run it on a container (like AWS Fargate), or run it on a managed serveless service like B<strong>edrock AgentCore Runtime</strong>.</p><p>One of the benefits of hosting your application with AgentCore Runtime is that you can easily integrate with AWS <strong>CloudWatch observability</strong> for good visualization of how your agent is performing. (See <a href="https://dev.to/aws-heroes/amazon-bedrock-agentcore-runtime-part-3-agentcore-observability-f08">this article</a>)</p><p>I won’t go into details of how to deploy the Agent to Bedrock AgentCore Runtime via their Python SDK, as interested readers can read the official documentation <a href="https://strandsagents.com/latest/documentation/docs/user-guide/deploy/deploy_to_bedrock_agentcore/python/">here</a>.</p><p>But on a high level, the following steps are normally what you need to do,</p><ol><li>Install Bedrock-agentcore SDK and wrap your agent code with BedrockAgentCoreApp.</li><li>Package your application into a container image, deploy to ECR.</li><li>Deploy the image to Bedrock AgentCore Runtime.</li><li>Associate your AgentCore Runtime services with an IAM role, with permissions to access all required tools like Knowledgebases, Bedrock Model, etc.</li><li>Enable observability with your application.</li></ol><h4>Level 2.5: Integrate with Bedrock AgentCore Memory</h4><p>Why the need to integrate your agent with a <strong>memory system</strong>?</p><ul><li>Each LLM invocation call is stateless. The LLM responds only to the input text.</li><li>Agent objects created using the agentic framework (like Strands Agent) are usually temporary stateful -&gt; stateful, as Strands Agent will keep the previous conversation history with the same agent in the agent. messages field. Temporary as this message has a lifetime of the agent object lifetime, once the agent object is destroyed (garbage collected by code), the messages are gone.</li><li>To mimic conversation experience between the agent and the users, you need to find a way for the agent to “remember” the previous conversation history across multiple agent object instances. This is where the memory system came into the picture.</li></ul><p>Some reading to get you started (<a href="https://aws.amazon.com/blogs/machine-learning/amazon-bedrock-agentcore-memory-building-context-aware-agents/">official blog</a>, <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/memory.html">official guide</a>, <a href="https://dev.to/aws-heroes/amazon-bedrock-agentcore-runtime-part-7-using-agentcore-long-term-memory-with-strands-agents-sdk-lb2">some examples</a> of integrating Bedrock agentcore memory with strands agents)</p><p>The key concepts you need to know are as follows:</p><ul><li>With a Strands Agent object, all the conversation history between the user and the agent (including use of tools) will be stored in the Agent’s <strong>messages</strong> (list) field. This is where you can retrieve the content to place into the <strong>Short Term Memory</strong> of Bedrock AgentCore Memory.</li><li>The namespace of Bedrock AgentCore Memory is flexible. You can store the short-term memory event in different memory IDs, different actor IDs, and different session IDs. Actor ID is usually used to identify the same user.</li><li>Bedrock AgentCore Memory can have <strong>built-in memory strategies </strong>that convert Short-Term Memory into <strong>Long-Term memory</strong> (a condensed version of short-term memory that is queriable like a vector store).</li><li>You can manipulate the Agent. messages by appending the retrieved long-term memory to it when needed.</li><li>The way you can retrieve content from the messages and append long-term memory to it can be done via the <a href="https://strandsagents.com/latest/documentation/docs/user-guide/concepts/agents/hooks/#hook-event-lifecycle"><strong>hook system</strong>.</a> More specifically, one way to do it is to retrieve the last message after each MessageAddedEvent and store it in the short-term memory, and append the content retrieved from long-term memory into the messages at the BeforeModelCallEvent.</li></ul><h4>Level 3: Upgrade to a Multi-Agent</h4><p>At this point, you will have a single <strong>ReAct </strong>agent that can “memorize” the conversation history of users and the agent, and use the tools to achieve the task given by user input. Your agent is hosted behind the AgentCore Runtime, which automatically scales according to demand to serve API requests, and integrates with Cloud Watch Observability for you to monitor and log for troubleshooting.</p><p>Now, as you want the agent to do more stuff, the system prompt of the agent will become longer and longer. When you have more steps defined in the system prompt, you might realize the agent will start “forgetting” steps. You might specify a five-step process in your system prompt, but the agent will sometimes skip step 4 or skip step 3 in another execution. You realized you have to start dealing with the <strong>non-deterministic</strong> nature of the LLM call (or the problem with the Attention mechanism?).</p><p>If you want to have <strong>reliable, persistent workflow execution,</strong> then you need to start considering a multi-agent system like a graph or a swamp. Ideally, the multi-agent system should break down the entire workflow into multiple smaller processes, where you can add more <strong>deterministic </strong>flow between the agents in the workflow.</p><p>The possibilities become almost endless, where an interesting reader should start exploring different multi-agent structures like <strong>Graph / Swarm / Workflow,</strong> starting from the <a href="https://strandsagents.com/latest/documentation/docs/user-guide/concepts/multi-agent/multi-agent-patterns/#multi-agent-patterns">official guide</a>. Some notable highlights</p><ul><li>There could be nested levels of Graph / Swarm; you can have a swarm as a node inside a graph.</li><li>The graph/swarm/workflow can be wrapped as a tool.</li><li>For the graph, there are two places to share the contexts between the agents. <strong>Graph.state</strong> is used by the Strands Agent framework to maintain state after each node’s execution, and it&#39;s not accessible to the individual node directly. <strong>invocation_state </strong>is a key-value dictionary that can be passed (and shared), accessed, and modified by all the individual nodes.</li><li>The strands graph will automatically include input from all dependency nodes for the current node. For example, if you have an execution workflow of A -&gt; B -&gt; C -&gt; B, on the 2nd call to node B, it will have input from node A and node C.</li></ul><h4><strong>Level 4: Customize the behavior of the Node</strong></h4><p>With a multi-agent system, you will want to add more control / more deterministic process to your workflow to ensure the accuracy of your agent system. One area is how the context is passed between the agents. As the output to one agent is the input to the other agent, you can do some manipulation on the outputs.</p><p>One way to do so is to replace the agent in your graph with a custom class that inherits <a href="https://github.com/strands-agents/sdk-python/blob/main/src/strands/multiagent/base.py">MultiAgentBase</a> and wraps the agent in it. Then, in your custom class, after the invocation is done with your agent, ensure your agent outputs the response in <a href="https://strandsagents.com/latest/documentation/docs/examples/python/structured_output/">Structured Output</a> format. Then you can use the Structured Output content to reconstruct the output (which becomes the input) for downstream agents. You can also use the Structured Output to set a Boolean flag value (like success/failure) to determine if node A should travel to node B.</p><h4>Level 5 and beyond: Further Customization and Optimization</h4><p>For some of the popular models (like Claude Haiku 4.5 ), you may quite often encounter the ServiceUnavailableException when calling Bedrock services. One way to deal with it is to implement a mechanism that retries your agent with a different inference profile whenever you encounter such an exception.</p><p>As illustrated, there are multiple ways to further customize and optimize your agentic system. Hope the guide above gives you some ideas on what you can do with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c8619a4c017" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[为什么定投美股指数(SPY) 是普通人过去和现在最优的投资选择？]]></title>
            <link>https://chinsj.medium.com/%E4%B8%BA%E4%BB%80%E4%B9%88%E5%AE%9A%E6%8A%95%E7%BE%8E%E8%82%A1%E6%8C%87%E6%95%B0-spy-%E6%98%AF%E6%99%AE%E9%80%9A%E4%BA%BA%E8%BF%87%E5%8E%BB%E5%92%8C%E7%8E%B0%E5%9C%A8%E6%9C%80%E4%BC%98%E7%9A%84%E6%8A%95%E8%B5%84%E9%80%89%E6%8B%A9-eb87dff50751?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb87dff50751</guid>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 06:43:22 GMT</pubDate>
            <atom:updated>2025-12-01T06:43:22.504Z</atom:updated>
            <content:encoded><![CDATA[<p>开篇总结：</p><p>对资产的供需决定价格， 资产带来的收益决定价值， 长期来看， 价值必然会反映到价格上。 在长期通胀的环境下， 债卷和定存都不是好的投资选择。 持有比特币和黄金不带来现金收益， 导致其价格完全由供需决定， 投资变成赌博。 房地产和股市相比持有成本高， 流动性差， 风险更集中， 买错退出困难。</p><p>美股由于目前美国的科技金融优势， 盈利长期看涨必然反映到其估值上。 如果赌的是长期趋势， 那么就选择指数基金（分散风险）， 同时定投， 避免市场择机(time the market)</p><h4>资产的价格是由供需决定的</h4><p>这句话应该不用多做解释，所有的资产， 包括黄金， 比特币， 债卷， 外汇， 房地产， 股票都有交易市场， 资产的当下价格就是由买卖双方拉扯后的成交价决定。</p><p>供大于求，就会有卖家愿意接受更低的出价， 拉低成交价， 求大于供， 就会有买家愿意出更高的价格， 拉高成交价。</p><p>你对资产的未来价格看好看涨， 就会愿意现在买入。 反之你对资产的未来价格看跌， 就会愿意现在卖出。</p><h4>资产带来的收益决定价值</h4><p>有兴趣的可以深入学习一下净现金流(Net Present Value) 和贴现率 (Discount rate)的概念。</p><p>太长不看的思考版：</p><p>黄金，比特币， 外汇这类资产是不产生现金流的， 不管你持有多久它带给你的现金收入都是零。 唯有价格上涨你才能获得资产增值的收益。</p><p>债卷或定存 带来的现金收益是固定的。 假设你现在有一百万， 定存的利息有百分之五， 如果你每年获得利息后再投入定存， 那你十年后能获得的收益大概是 1.05 ^10 x 1 million = $1.63 million.</p><p>房地产或股票带来的现金收益有增长的可能。 假设一个公司现在一年的收益有百分之四， 但每一年它的收益会以 百分之二十的速度增长， 即</p><p>第一年， 4%， 第二年， 4.8%， 第三年， 5.76% ….</p><p>那同样的一百万，十年后你获得的收益大概是 $2.66 million. 你可以得出一个简单的判断， 把同样的钱投入公司， 会比投入定存更有价值。</p><h4>价值必然会反映到价格上</h4><p>当多数人和你有同样的判断时， 市场对公司的股票求大于供， 必然导致股票价格上涨。</p><p>即使 可能有某段时间， 大家都对股票市场悲观， 导致股票大跌， 但只要基本面不变， 只要公司能维持现金收益， 且这个现金收益还会不断增长， 那股票的潜在价值 可以高过当下的价格。 等悲观情绪一过， 市场理性起来， 必然会追逐价值高于价格的股票， 直到价格提升到和价值相当的水平。</p><h4>通胀或通缩影响 资产的长期价格趋势</h4><p>通胀 (inflation) 或者通缩 反映的是现金(cash) 和资产的相对价格。 通胀意味着物价（资产）会越来越贵， 通缩则相反。</p><p>定存/债卷由于其现金收益是固定的，因此可以把它们看成是现金资产， 和其他资产区分。</p><p>长期通胀， 黄金/比特币/地产/股票等资产价格会持续上升， 现金资产的实际收益会降低， 因为十年后同样的一万收益， 能买的东西变少了。</p><p>长期通缩， 现金资产的实际收益会增加， 因为十年后同样的一万收益， 能买的东西会变多了。 但黄金/比特币/地产/股票等资产价格可能会持续承压。</p><h4>通胀是目前世界范围内的长期趋势</h4><p>原因一是主观的， 不管是经济史上的教训 (1920年代的大萧条), 还是目前各国政府和民间债台高筑的现实， 导致各国政府都倾向于维持温和的通货膨胀。 唯有持续长期的温和通胀， 才能稀疏目前的债务负担。</p><p>原因二是客观的， 各国政府都在维持扩张性（即举债来维持支出)的财政预算：</p><ol><li>发展中国家， 政府带头牵动基础建设投资对经济发展的回报是巨大的(例子如中国）</li><li>社会福利支出高的国家， 政府开支极大影响民众所得， 任何削减福利开支的举措都会招致民意反弹， 进而导致民选政府的下台。</li><li>经济增长停滞/面临通缩压力的国家， 会希望有政府实行扩张性财政预算， 来制造通膨， 带动国家摆脱通缩陷阱 (比如日本）</li></ol><h4>定存和债卷是最差的投资选择</h4><p>在长期通胀趋势下， 不难得出这个结论。</p><p>还有一点， 决定定存和债卷收益的是各国中央银行的央行利息。 各国央行决定利息水平的决策都是要平衡两大目标， 一是维持目前的物价水平(避免通胀过热）， 二是维持经济增长来保持就业。 存户/债卷卷主的利益从来不在央行考量内。</p><h4>黄金、比特币是勉强可以的投资选择</h4><p>黄金 -》 美元黄金脱钩前， 人类社会货币史上长期占据主导地位的贵重金属。 即使是脱钩后， 工业金属， 首饰， 对保值资产的需求推动黄金价格持续上涨， 且抗通膨。</p><p>比特币 是电子黄金。 其发行量最多2100万， 且长期交易过程会有损耗的特点保证 比特币的 供应量会持续减少， 黑市交易的需求， 加上投资热潮带动比特币的上涨。</p><p>但这两类资产本身不带来持续现金收益， 其价格由市场波动影响。</p><p>从2025年11月30日算起， 过去五年购买黄金的收益率是 138%。 看起来很不错， 但把时间尺度拉长到过去十四年， 购买黄金的收益率是 143%. 也就是如果你在2012年购入黄金， 直到2020年新冠疫情爆发前， 你的收益大概率是负的， 还不如投入定存或债卷。</p><p>比特币自诞生以来的需求暴涨， 其过去五年的收益率为372%。 但它过去一年的收益率为 负6%. 个人估计其未来的长期收益率会比照黄金。</p><h4>地产投资有门槛，需耕耘</h4><p>地产投资的缺点</p><p>一， 流动性差 且因为单价贵， 进入成本高。 普通人投资房产大概是每五到十年才会入场一次。</p><p>二， 不可控的因素很多， 比如宏观经济层面的变化， 比如微观所在地区的发展差异， 本来是好区但因为地区经济下滑，治安变坏而变成烂尾区。</p><p>因为一和二，在错误的时间点入场（比如次贷危机前的美国， 2020–2022年的中国）， 很容易倾家荡产。</p><p>三， 同时有持有成本(地产税） 和折旧的问题。 好的房子需要时间精力维护， 如果买入的是公寓， 还需要有好的物业。</p><p>四， 土地供应在黄金地带是有限的， 但同时其地价往往偏高通常反映了供求关系。 土地价格在城市周边和郊区是便宜的，但也是充裕， 这导致其价格上限有限。</p><h4>股市（指数基金）是理论上的最佳资产</h4><p>相比地产</p><ul><li>流动性高</li><li>持有成本低</li><li>折旧已经反映在业绩里， 不太需要花精力去维护。</li></ul><p>投资个股，有可能重现押中 Nvidia 而暴富的神话。 但也有可能因为押错安然和暴亏。 单个企业可能会在市场竞争中落败（比如Nokia)， 可能会因为行业变化而衰弱（比如柯达）， 也可能会因为监管不力， 会计丑闻而暴雷（比如安然）。 但押注指数基金可以分散市场竞争的风险，可以分散行业变化的风险， 可以分散监管不力的风险。</p><p>整个指数的长期回报增长率可以等于两个因素相加</p><ul><li>通货膨胀率 -&gt; 物价越贵， 企业卖同份额商品的利润更高</li><li>经济增长率 -&gt; 市场（由于人口和经济增长）变大， 企业能卖的商品更多， 总利润更高。</li></ul><h4>美股和其他国家股市的区别</h4><p>相比其他国家， 美股会倾向于股票回购而非分发股息(dividend). 这很大原因受美国的税务制度影响， 因为股票回购带来的股票价格上涨只需在卖出时交资本利得税， 且这个资本利得税最高才20%。 反之如果分发股息， 散户受到股息后要按收入缴交个人所得税， 最高的边际税率可以到37%.</p><h4>美股是否过热？</h4><p>SNP 500 的 P/E (price / earning ratio) 目前接近<a href="https://www.macrotrends.net/2577/sp-500-pe-ratio-price-to-earnings-chart">三十</a>， 处于历史高位。换句话说， 假设盈利成长和通货膨胀为零， 现在买入需要三十年才能回本。</p><p>但SNP 500 的盈利仍然在强劲增长中， 如果我们用另一个估值公式Gordon Growth Formula,</p><p>P = D/(r -g)</p><p>where P = 现在估值</p><p>D = Dividend, 对不发股息的公司而言， 可以把它理解为 Discounted Free Cash Flow.</p><p>r = Required Rate of Return -&gt; 一般为10–15%。</p><p>g = growth rate. SNP 500 的盈利增长<a href="https://www.multpl.com/s-p-500-earnings-growth/table/by-year">目前</a>接近10%</p><p>重组一下</p><p>P/D 约等于 P/E ratio 约等于 1/(r-g), 假设 r 等于 10%, g = 8%, 1/(0.1–0.08) = 50 =&gt; SNP500 目前并不太贵。</p><p>但从公式可以观察， 当 g 无限接近甚至大于 r 时， P/E ratio 是无法计算的。 正如目前发生的情况， 当SNP500 的盈利增长达到双位数百分比时， 其估值波动是巨大的。</p><p>从另一个指标 巴菲特的 SNP500 总市值 除以美国 GDP 来看， 这个指标目前约 226%， 处于<a href="https://en.macromicro.me/collections/34/us-stock-relative/406/us-buffet-index-gspc">历史最高点</a> 。但同时我们得意识到， 过去几十年全球化的趋势下， 美股不仅只在美国市场经营， 其业务已经扩展到全世界。 科技巨头(Nvidia, Alphabet, Meta, Microsoft, Amazon, Apple， Netflix 等等) 都在赚全世界的钱。 单纯盯着SNP500 / 美国GDP 的指标已经没有太大意义。</p><h4>为什么是定投？ 为什么不选Nasdaq100?</h4><p>两个观察， 一是过去五年SNP500 和 Nasdaq100 的总回报都差不多， 二是 Nasdaq100 的<a href="https://www.slickcharts.com/nasdaq100/returns">波动</a>比 <a href="https://ycharts.com/indicators/sp_500_total_return_annual#:~:text=S&amp;P%20500%20Annual%20Total%20Return%20(I:SP500ATR)&amp;text=S&amp;P%20500%20Annual%20Total%20Return%20is%20at%2025.02%25%2C%20compared%20to,500%20returned%2026.46%25%20in%202009.">SNP500</a> 大， 在最差的年份的回撤可以是SNP500 的1.5–2倍。</p><p>选择定投，则是避免 Timing market, 因为你永远不知道你会在最高点入场， 还是在最低点的时候没有买入。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb87dff50751" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[从Nvidia 的财报谈AI 泡沫]]></title>
            <link>https://chinsj.medium.com/%E4%BB%8Envidia-%E7%9A%84%E8%B4%A2%E6%8A%A5%E8%B0%88ai-%E6%B3%A1%E6%B2%AB-d6306f7e1de4?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6306f7e1de4</guid>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[ai-bubble]]></category>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 02:14:27 GMT</pubDate>
            <atom:updated>2025-11-24T02:16:33.819Z</atom:updated>
            <content:encoded><![CDATA[<p>Nvidia Q3 Earnings 是 $57 billion, 年化大概是$228 billion.</p><p>其收入主要来源于六大客户 (AWS, Azure, GCP, Oracle, Meta, Grok) 持续投入, 网上传言这六大客户占 Nvidia 收入的百分之八十五， 据此可推这六大客户每年在买卡上的花费约$200 billion, 那以这个数字反推， 这六大公司的营收得到什么程度才能回本/ 赚钱？</p><p>简单假设， 云服务商 (hyperscaler) 建设和运营 AI Data Center 的主要成本为 （1） AI 卡 (blackwell 200), (2) 土地， 厂房， 配套设施。 (3) 运营成本（电力， 冷却水， 人工，设备维护）。 其中 （1） 是每年持续投入， 以五年折旧期 （5 year depreciation schedule) 计算。 （2） 是一次性投入。 有<a href="https://www.wheresyoured.at/openai-onetrillion/#it-takes-25-years-and-325-billion-per-gigawatt-of-data-center-compute">预估</a> 每 $20 billion 的卡投入需要 $12.5 billion 的 基建投入(for 1 GW capacity) 。 按基建投入二十年折旧期计算的话， 每年需要 $200 billion x 5 x 12.5/20 / 20 = $31 billion 的基建投入。 (3) Opex 相对较低， 但<a href="https://www.investing.com/news/stock-market-news/how-much-does-a-gw-of-data-center-capacity-actually-cost-4314046">预估</a>每1 GW 得有 $1.3 billion, 即每年约 $200 billion x 5 / 20 billion x $1.3 billion = $65 billion.</p><p>得出小结论， 每年买卡花 $200 billion, 六大公司每年得花总约 $300 billion 来建设和运营。 这还不包括给大模型公司(Open AI, Anthropic， Gemini 3, Grok) 的支付 或训练成本分摊， 也不包括其他设备的支持， 比如储存， 网路， 服务器等）</p><p>于是反推得出另两个结论， 要回本的话， 六大公司每年得赚至少 $300 billion, 要赚钱， 以40% Gross profit margin 计算， 六大公司每年得赚至少 $ 500 billion.</p><p>作为对比， 预计2025年整个云市场的营收约 $400 billion (包括传统云服务）， 整个AI Cloud Service Market 2025年营收也许有 $100 billion?</p><p>这是个问号，首先这是全球的数据, 即大概最多八成才是六大公司的份额， 其次OpenAI 2025年营收预估才 $13 billion, Anthropic 大概 $5/6 billion, 微软 谷歌 的 AI 营收虽然亮眼， 但这是建立在以自身本来体量巨大的业务 (微软的 Office， 谷歌的搜索/youtube) 哺育AI 的前提下）</p><p>AI 云市场<a href="https://www.grandviewresearch.com/industry-analysis/cloud-ai-market-report">预计</a>得到 2029/2030 年 才能成长到 六大公司能回本或挣钱的规模。 而且这有三个问题，</p><p>一现在买的显卡到届时会落后至少两到三代， 基本等于废卡。</p><p>二是新的， 大规模的业务增长点从何而来？ 微软/Anthropic To Business, 谷歌/Meta/OpenAI/Grok To Customer 的业务已经接上了， 下一群 AI Killer App 还没有出现。 于是我们看到 OpenAI 和 Google 都大规模的推广免费体验， 期望培育下一群业务增长点。</p><p>三是 除了少数业务以外， <a href="https://fortune.com/2025/08/18/mit-report-95-percent-generative-ai-pilots-at-companies-failing-cfo/">大部分</a>的AI 商业应用目前还不挣钱。</p><p>现阶段结论， 我们正处于泡沫形成中，而且这泡沫爆破的伤害， 会随着投入增长和营收增长的不成比例而放大。</p><p>但 Nvidia 没有倒闭的可能， 因为它轻资产（晶片制造都是 台积电做的）且高 profit margin. 只不过AI 泡沫结束时，其市值可能会回撤一半以上。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6306f7e1de4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[北美信用卡开卡和长期持有思路]]></title>
            <link>https://chinsj.medium.com/%E5%8C%97%E7%BE%8E%E4%BF%A1%E7%94%A8%E5%8D%A1%E5%BC%80%E5%8D%A1%E5%92%8C%E9%95%BF%E6%9C%9F%E6%8C%81%E6%9C%89%E6%80%9D%E8%B7%AF-8376c21f0509?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/8376c21f0509</guid>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 01:46:45 GMT</pubDate>
            <atom:updated>2025-08-23T02:51:42.467Z</atom:updated>
            <content:encoded><![CDATA[<p>更丰富的中文资讯请点 <a href="https://blog.tripplus.cc/zh/">繁体</a> / <a href="https://www.uscreditcardguide.com/zh/">简体网站</a></p><h4>前言</h4><p>在北美， 许多信用卡都有高额的开卡奖励来吸引新顾客， 有的给积分， 有的给现金回扣(cash back) . 然而， 我们是不可能通过不断重复申新卡这类行为 (英文 叫 churning）来刷这些奖励的 。 原因如下</p><ol><li>信用卡发行商有各自不同的规则来限制刷奖励的行为。 比如 Chase 银行 有 5/24 rule. 两年内不可获批超过５张卡. 同系列 CSR 和CSP 卡每四年只能拿一次开卡奖励, 且一张卡一生只能拿一次。 比如 Amex 的所有卡 开卡奖励一生只能拿一次， 且同系列卡拿了高级卡的奖励就不能再拿低级卡的奖励。</li><li>刷开卡奖励是有成本的。 首先得满足最低消费金额， 平均每张中高级卡会要求你在短期内最少刷几千实质消费（不能刷 制造消费-manufactured spending). 这就表示除非你个人消费额特别大， 不然最快每两三个月申一张新卡才能满足消费额。其次， 开卡奖励越高的信用卡往往年费也越高。 尽管某些高年费的信用卡(比如 Amex platinum) 有一大堆报销福利 (比如$200 Uber credit）来返还年费， 但如果这些福利你平常就不会去用， 那这些福利对你来说其实价值等于 0.</li><li>满足申卡规则 和 消费金额之余， 还要避免太频繁申卡 以免影响个人的信用分 (Credit Rating). 有些发卡银行对 会对近期申卡记录 (Hard pull) 相当敏感， 频繁申卡 会导致申请被直接拒掉 或者拿不到开卡奖励。</li></ol><p>那么， 对刚满足基本信用分要求的新手来说， 应该先申拿几张卡来刷开卡奖励呢？</p><p>我个人建议， 在遵循<strong>价值最大化</strong>的原则下，</p><ol><li>个人持有信用卡在五张以下， 优先选择 Chase 的。因为之后在你申完市面上所有 有高额开卡礼的信用卡前， 你很难满足 两年内不可获批超过５张卡的要求。</li><li>AMEX 的卡 从低级卡 申起， 并且等待 其开卡奖励接近史上最高 时才申。</li><li>其他银行的卡， 在留意各自申卡规则的情况下， 有高额开卡奖励且有需求就申。</li></ol><p>另外， 由于信用卡的积分不能随意转换， 如果想要价值最大化， 就必须专注刷 特定积分系统的卡。 这就表示除了刷开卡奖励外， 还要考虑选择拿几张卡来长期持有。</p><p>但这就牵涉到 今天最重要的 问题， 到底<strong>怎样衡量开卡奖励 （积分） 的价值？</strong></p><h4>信用卡积分价值排序思路</h4><p>先来句废话， 信用卡不同积分系统的价值对每个人是不一样的 (Your mileage may vary, YMMV).</p><p>但大致上来说</p><p>信用卡积分（Amex MR,Chase UR,Citi TYP, Marriott BP) 换航空公司里程 &gt;&gt; 信用卡积分 换连锁酒店积分 &gt;&gt; 直接当现金使用。</p><p>不同里程/ 积分系统的价值可以参<a href="https://thepointsguy.com/guide/monthly-valuations/">这里</a> 。</p><p>我个人认为， 赎回 （Redeem） 积分价值最大化的方法只有一种， 即换成航空公司的里程 (miles) -&gt; 来换取 长途航线 （比如跨洲， 北美到东亚）的商务舱或头等舱。 以美国西岸飞亚洲为例子，我感觉ANA 的里程最值钱 (1 mile 可以用出 $3.5–4c 的价值，不过要加近70k 日元的税)， 只有 AMEX MR 能换。其他亚洲航司大概 1 mile = $2-3c. 采动态定价的北美航司 (UA, Delta, AA, Alaska) 商务舱和经济舱的价值目前差不多一样 1 mile = $1.5c。</p><p>不同航空公司的里程对每个人的价值是不一样的。 只有当该行程是你的刚需 （比如每年春节北美的打工人想要回国）或者软需（比如计划蜜月旅行到马尔代夫或欧洲）时其价值才是最大的。</p><p>另外，需要注意的是 里程要能用 才有价值。 有些航司 尽管理论上能用里程换商务舱座位， 但实际查询时往往 是 No seat is available. 那这里程实际上 就没用。 例子是 Avianca Lifemile, 理论上兑换北美东南亚商务舱只需 81K miles, 但实际上基本搜不到票。</p><p>且目前各航司的趋势是， 放给自家里程的商务舱机票是充足的， 放给伙伴航司的商务舱机票是有限的。</p><p>唯有选定你想要乘搭的主力航司， 才能选择你应该累计的信用卡积分系统。</p><h4>太长不看版，我推荐的申卡优先级</h4><p>Prime card</p><ol><li>Citi Strata Premier</li><li>Chase CSP （因为 Chase 5/24 政策）</li><li>Chase Aeroplan （因为 Chase 5/24 政策）</li><li>Amex Gold</li><li>BoA Alaska （因为星宇）</li><li>Amex Platinum （纯粹因为年费贵）</li><li>Capital Venture / Venture X</li><li>Citi Strata Elite （纯粹因为年费贵）</li><li>Chase CSR （纯粹因为年费贵）</li><li>Chase UA (all 3)</li><li>Other hotels card (Marriott, Hyatt, Hilton)</li><li>Amex Delta / AA</li></ol><p>No annual Fee</p><ol><li>Bilt</li><li>Citi Double Cash</li><li>Citi Strata</li><li>Citi Custom Cash</li></ol><h4>个人评价，里程 X 信用卡积分的 综合排序</h4><p>以目前的航班数量来看， 我个人认为 ANA 和长荣 (Eva Air) 目前的里程比较有价值的原因在于，</p><ol><li>自营航班数量比较多。 比如中美直航 目前每周85 个航班，基于目前的客运需求量， 基本上是不可能以很少的里程换到商务舱的 （UA 能换， 但仅单程商务舱就要 200k miles, 里程的价值给压的很低）。 而长荣本身每周就有84 个航班 飞北美， 且目前长荣兑换亚洲-北美航线商务舱的价格固定为单程75k — 80k ， 基本很容易刷到。</li><li>即便没有直航， ANA 和 长荣连接到东亚其他地区往往只是one stop away. 比如 目前 美西飞往东亚几大城市的主要航司有。</li></ol><p>美西日本东京 — ANA/UA/Delta/JAL</p><p>美西台北- EVA (长荣) — TYP</p><p>美西香港 — UA / CX (国泰）</p><p>美西新加坡 — UA / SQ</p><p>另外有以下注意事项：</p><ol><li>美国东南亚的兑换有个threshold, 7.5k miles 飞行距离. 这大概是旧金山到 台北、香港， 马尼拉的距离。 超过这个距离有些航司需要兑换的里程会上升。</li></ol><p>2. ANA 不管是自家还是对星盟伙伴， 固定远期放票是一张头等，两张商务。 但ANA 对临期（两周内）的商务舱往往会放很多张。</p><p>3. 长荣对星盟伙伴固定远期放票是两张商务， 会有一定数量的商务舱保留给自家里程会员。</p><p>4. 星宇近期开始放临期（三周内）的商务舱给BoA Alaska</p><p>个人认为， 综合兑换商务舱需要的里程, 附加费 和 Availability, 目前（2025年6月）最好的兑换选择是 如下：</p><p>信用卡积分标注 (Amex MR, City TYP, Capital C1, Chase UR)</p><ol><li>日本 ANA — Amex MR, 2025年6月起可兑换单程， 54–86.5K miles 可到台北或香港, 高附加费 (接近五百美金).</li><li>台湾长荣 EVA — TYP, C1 (75%), 单程商务舱 75K mile 可到东南亚, 低附加费， high availability。</li><li>用 Aeroplan 兑换星盟伙伴 (Star Alliance, EVA, SQ, ANA) —Chase UR, Amex MR, C1， 单程商务舱 75K 到台北。低附加费，大概两百加币来回美西到台北。 缺点是很少伙伴票 会给放出， 而且 Aeroplan 是票贩子的重灾区， 故 availability 很差。</li><li>用 Alaska 兑换星宇 — 单程商务舱 75K 到台北。低附加费。 临期Availability 还可以。</li><li>日本 ANA — Amex MR, 2025年6月起可兑换单程， 68.5–100.2K miles 可到东南亚, 高附加费 (接近五百美金).</li><li>用 Aeroplan 兑换星盟伙伴 到东南亚, 87.5K mile,</li><li>JL单程商务舱 北美 — 日本 = 50K miles, 日本-东南亚 40K miles, Marriot 和 BILT 能转。</li><li>国泰 Cathay — Amex MR , TYP, C1–84–89K mile 到香港。高附加费</li><li>Singapore Airline SQ — Chase UR, Amex MR, C1, TYP — 单程商务舱 saver award 107K mile, 低附加费。SQ 偶尔能兑换 ANA 单程（包含临期） — 约 117K mile + $300 surcharge.</li><li>国泰 Cathay — Amex MR , TYP, C1 — 单程商务舱 110 K mile 左右到东南亚， 但航线比较抢手so Availability 比较差。 Cathay 偶尔能兑换 日本航空 (JL) 单程 （包含临期) 但附加费很高.</li><li>其他北美航司 UA, Delta, AA 基本是动态定价， 想兑换伙伴航班商务舱则面临 Availability 不足的问题， 暂时不考虑。Alaska -&gt; 唯一优点是兑换临期商务舱 （星宇/JL), UA 可换 ANA 临期商务舱， AA 可换 JL 临期商务舱。 Delta 不管是临期或者是远期的 商务舱都采动态定价， mile 价值犹如冥纸。</li><li>其他非北美或亚洲的航司 （欧洲航司等），理论上需要的里程不多， 但实际上基本没有 Availability, 基本不考虑。</li></ol><p>Note 除了 Aeroplan/Cathay/北美航司 外， 其他航司点数三年过期。</p><p>所以对信用卡积分来说， 最好的兑换选项顺序是</p><p>AMEX MR -&gt; 1. ANA， 2. Aeroplan (75K),3. Cathay (美西香港, 89K), 4. Aeroplan (87.5K) 5. SQ, 6. Cathay</p><p>Capital One C1 -&gt; 1. Aeroplan (75K), 2. Cathay (美西香港, 89K）， 3. Aeroplan (87.5K) , 4. EVA, 5. SQ, 6. Cathay（东南亚）</p><p>Chase UR -&gt;1. Aeroplan (75K), 2. Cathay (美西香港, 89K）， 3. Aeroplan (87.5K), 4. SQ, 5. Cathay（东南亚）, UA (JL) 临期票</p><p>City TYP -&gt; 1. EVA, &gt;&gt;&gt; 2. Cathay (美西香港, 89K）， 3. SQ, 4. Cathay</p><p>City AA 卡 唯一甜点是 JL 临期票，Chase UA 卡唯一甜点是 ANA 临期（在ANA 开放单程后已经无用）， 基本可以不考虑</p><p>Amex Delta 系列卡 没有甜点， 基本可以不考虑。</p><p>Marriot 点数换所有航司都是 2.4 : 1 (UA 2: 1) . 如果 Marriott 点数太多换 JL (远期） 或者 UA (近期） 也是一条出路。</p><p>如果有转点奖励活动，</p><ol><li>优先有兑换需求的航司， 2. 自家商务舱里程票充足且价格固定， 里程永不过期的航司 (只有国泰符合标准）3. 加航。</li></ol><p>另附商务舱参考票价</p><p>ANA — Seattle — KUL Return, Economy — around $900, Business — around $5800</p><p>长荣, economy — around $1100, Business — around $5700</p><p>Singapore airline — economy around $1400, Business — around $6500</p><h3>其他信用卡事项：</h3><h4>算一下酒店联名卡攒的积分</h4><p>次选兑换酒店积分 -&gt; World of Hyatt 积分最值钱 (1point = $1.6–1.7c)， 只有 Chase UR 能换 。 其他酒店积分不太值钱。</p><p>经济酒店 -&gt; Barclays Wyndham Earner Plus</p><p>经济＋高级混合 -&gt; Chase IHG Premier， Choices</p><p>高级酒店 -&gt; 短住（Chase World of Hyatt) — 常住 (Amex Marriott Bonvoy)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfrvsCuQ4gu_FOlDoS8pgQ.png" /><figcaption>各主要联名卡</figcaption></figure><h4>信用卡还税注意事项</h4><p>Underpayment penalty</p><ul><li>当实交 少于 当年应交 90% 或实交 少于 去年税额的 100% (110% if adjusted gross income &gt; $150k — file jointly or &gt; $75K — file single)</li><li>且欠税超过 $1000 才触发。</li></ul><p><a href="https://www.nerdwallet.com/article/taxes/underpayment-penalty-what-it-is-how-to-avoid-it#:~:text=An%20underpayment%20penalty%20is%20a,on%20the%20prior%20year&#39;s%20return">https://www.nerdwallet.com/article/taxes/underpayment-penalty-what-it-is-how-to-avoid-it#:~:text=An%20underpayment%20penalty%20is%20a,on%20the%20prior%20year&#39;s%20return</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8376c21f0509" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relearning React Basic]]></title>
            <link>https://chinsj.medium.com/relearning-react-basic-72c7db929e25?source=rss-28e03c706898------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c7db929e25</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[sjchin]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 06:57:21 GMT</pubDate>
            <atom:updated>2025-07-03T06:17:50.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Key diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_1ZD_a4PwSRdSgb_s5ULw.png" /></figure><h3>Getting Start</h3><pre># Prerequisite - Node.js install<br># using vscode<br># Jumpstart project using vite<br>npm create vite@latest<br><br># Then follow instruction of vite to<br>cd &lt;project_name&gt;<br>npm install<br>npm run dev</pre><h3>Key Concepts</h3><h4>Component</h4><ul><li>Component is a function that return html component</li><li>Once created, it can then be imported and used in the App as a tag.</li></ul><pre>// Example, we have a component call Message, <br>function Message(){<br>    return &lt;p&gt;Hello from Message component.&lt;/p&gt;<br>}<br><br>export default Message<br><br>// then in the App.tsx entry point, <br>// we can do <br>import Message from &#39;./components/Message&#39;<br><br>function App() {<br>  return (<br>    &lt;Message/&gt;  // this will call the function and return the &lt;p&gt; <br>  )<br>}<br><br>export default App</pre><h4>DOM &amp; Fragment</h4><ul><li>Multiple React JSX (html) expressions at the top level must have one parent root element.</li><li>Two ways to do it — Fragment or use a div (or other HTML elements)</li><li>Fragment is prefer as it dont produce extra element to wrap child components which can lead to bloated HTML, styling issues, and other unnecessary DOM nodes.</li></ul><pre># Use a Fragment, either empty bracket or <br>&lt;&gt;<br>      &lt;h1&gt;Hello World!&lt;/h1&gt;<br>      &lt;Message/&gt;<br>&lt;/&gt;<br>&lt;Fragment&gt;<br>      &lt;h1&gt;Hello World!&lt;/h1&gt;<br>      &lt;Message/&gt;<br>&lt;/Fragment&gt;<br><br># Use a div<br>&lt;div&gt;<br>      &lt;h1&gt;Hello World!&lt;/h1&gt;<br>      &lt;Message/&gt;<br>&lt;/div&gt;</pre><h4>Displaying List</h4><ul><li>React treat anything inside a {} bracket as javascript expression.</li></ul><pre>// Sample structure for a list<br>const dudes = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]<br><br>// map function iterate over the list<br>// each list element require an unique key within the ul <br>&lt;ul&gt;<br>        {dudes.map((dude, index) =&gt; (<br>          &lt;li key={index}&gt;{dude}&lt;/li&gt;<br>        ))}<br>&lt;/ul&gt;</pre><h4>Conditional Rendering</h4><pre>// normal javascript if else is not allow within React, only <br>// tertiary operator<br>// null will return empty element <br>{languages.length === 0 ? &lt;p&gt;No languages&lt;/p&gt; : null}<br></pre><h4>Handling event</h4><pre>// Say we have a function to handle click<br>const languages = [&#39;C++&#39;, &#39;Java&#39;, &#39;Python&#39;]<br>const handleclick = (language:string) =&gt; {<br>    alert(`${language} was clicked!`)<br>}<br><br>// if we pass this function as onClick event to the list then<br>&lt;ul&gt;<br>        {languages.map((language, index) =&gt; (<br>          &lt;li onClick={()=&gt;handleclick(language)} key={index}&gt;{language}&lt;/li&gt;<br>        ))}<br>&lt;/ul&gt;</pre><h4>State Manipulation</h4><ul><li>During run time, if we want to use a variable changed dynamically, have to use the useState() from ‘react’</li><li>Note if we place the state inside a component, and the component is used more than once, each component state is maintained independently by React (think of it like an object)</li></ul><pre>import { useState } from &#39;react&#39;<br><br>// useState declaration syntax as <br>// const [&lt;variable&gt;, &lt;setVariable&gt;] = useState(&lt;default&gt;)<br>// the second item is used later to change the state of variable. <br>const [selectedItem, setSelectedItem] = useState(0)<br><br>// In example below, the setSelectedItem(index) will triggered when <br>// onClick<br>{languages.map((language, index) =&gt; (<br>          &lt;li <br>            onClick={() =&gt; setSelectedItem(index)} <br>            className={selectedItem === index ? &#39;py-2 px-3 bg-gray-800 text-white&#39; : &#39;py-2 px-3&#39;}<br>            key={index}<br>          &gt;{language}<br>          &lt;/li&gt;<br>))}</pre><h4>Using Props</h4><ul><li>to pass variable to a component</li></ul><pre>// Sample component<br>interface ListProps {<br>    heading: string<br>    items: string[]<br>}<br><br>const ListComponent = ({ heading, items }: ListProps) =&gt; {<br>    const [selectedItem, setSelectedItem] = useState(0)<br><br>    return (<br>        &lt;&gt;<br>            &lt;div className=&quot;flex flex-col justify-center items-center&quot;&gt;<br>                &lt;h1 className=&quot;text-2xl font-bold mb-2&quot;&gt;{heading}&lt;/h1&gt;<br>                &lt;ul className=&quot;w-1/2 border border-gray-200 rounded-lg divide-y divide-gray-300 overflow-hidden&quot;&gt;<br>                    {items.map((item, index) =&gt; (<br>                        &lt;li<br>                            key={index}<br>                            className={<br>                                selectedItem === index<br>                                    ? &#39;py-2 px-3 bg-gray-800 text-white&#39;<br>                                    : &#39;py-2 px-3&#39;<br>                            }<br>                            onClick={() =&gt; setSelectedItem(index)}<br>                        &gt;<br>                            {item}<br>                        &lt;/li&gt;<br>                    ))}<br>                &lt;/ul&gt;<br>            &lt;/div&gt;<br>        &lt;/&gt;<br>    )<br>}<br><br>export default ListComponent<br><br>// Then on the App.tsx<br>function App() {<br>    const items = [&#39;JavaScript&#39;, &#39;PHP&#39;, &#39;Python&#39;, &#39;Swift&#39;]<br>    const frameworks = [&#39;Laravel&#39;, &#39;Ruby on Rails&#39;, &#39;Django&#39;]<br><br>    return (<br>        &lt;&gt;<br>            &lt;div className=&quot;flex flex-col&quot;&gt;<br>                &lt;ListComponent items={items} heading=&quot;Programming Languages&quot; /&gt;<br>                &lt;ListComponent items={frameworks} heading=&quot;Frameworks&quot; /&gt;<br>            &lt;/div&gt;<br>        &lt;/&gt;<br>    )<br>}</pre><p>To pass a function to a component</p><pre>// Add default function to the ListProps <br>interface ListProps {<br>    //prop can be made optional using ?<br>    // heading? : string<br>    // Can also limit prop selection like <br>    // heading? : &#39;Programming&#39; | &#39;Framework&#39; | &#39;Tool&#39;<br>    heading: string<br>    items: string[]<br>    onSelectItem: (item: string) =&gt; void<br>}<br><br>// Add it to onClick <br>// we can also set a default value for prop like <br>// const ListComponent = ({ heading=&quot;Title&quot;, items, onSelectItem<br>const ListComponent = ({ heading, items, onSelectItem }: ListProps) =&gt; {<br>    const [selectedItem, setSelectedItem] = useState(0)<br><br>    return (<br>        &lt;&gt;<br>            &lt;div className=&quot;flex flex-col justify-center items-center&quot;&gt;<br>                &lt;h1 className=&quot;text-2xl font-bold mb-2&quot;&gt;{heading}&lt;/h1&gt;<br>                &lt;ul className=&quot;w-1/2 border border-gray-200 rounded-lg divide-y divide-gray-300 overflow-hidden&quot;&gt;<br>                    {items.map((item, index) =&gt; (<br>                        &lt;li<br>                            key={index}<br>                            className={<br>                                selectedItem === index<br>                                    ? &#39;py-2 px-3 bg-gray-800 text-white&#39;<br>                                    : &#39;py-2 px-3&#39;<br>                            }<br>                            onClick={() =&gt; {<br>                                setSelectedItem(index)<br>                                onSelectItem(item)  {/*Use here*/}<br>                            }}<br>                        &gt;<br>                            {item}<br>                        &lt;/li&gt;<br>                    ))}<br>                &lt;/ul&gt;<br>            &lt;/div&gt;<br>        &lt;/&gt;<br>    )<br>}<br><br><br>// Pass the function like below<br>function App() {<br>    const items = [&#39;JavaScript&#39;, &#39;PHP&#39;, &#39;Python&#39;, &#39;Swift&#39;]<br>    const frameworks = [&#39;Laravel&#39;, &#39;Ruby on Rails&#39;, &#39;Django&#39;]<br>    const handleOnSelectItem = (item:string) =&gt; {<br>      alert(item + &#39; was selected.&#39;) <br>    }<br>    return (<br>        &lt;&gt;<br>            &lt;div className=&quot;flex flex-col&quot;&gt;<br>                &lt;ListComponent items={items} heading=&quot;Programming Languages&quot; onSelectItem={handleOnSelectItem}/&gt;<br>                &lt;ListComponent items={frameworks} heading=&quot;Frameworks&quot; onSelectItem={handleOnSelectItem}/&gt;<br>            &lt;/div&gt;<br>        &lt;/&gt;<br>    )<br>}</pre><h4>Props vs State</h4><p>Props</p><ul><li>Parameters or inputs to a component (change the component from outside)</li><li>Should be immutable</li></ul><p>State</p><ul><li>Component’s internally managed data</li><li>mutable</li></ul><p>Both will force the DOM to rerender when properly changed</p><h4>Passing Children Component</h4><ul><li>Use the ReactNode class</li></ul><pre>// Example in interface<br>import { useState, type ReactNode } from &#39;react&#39;<br><br>interface ListProps {<br>    children: ReactNode<br>    items: string[]<br>    onSelectItem: (item: string) =&gt; void<br>}<br><br>// Then in the app, we can do<br>  return (<br>        &lt;&gt;<br>            &lt;div className=&quot;flex flex-col&quot;&gt;<br>                &lt;ListComponent items={items} onSelectItem={handleOnSelectItem}&gt;<br>                  {/*We can insert entire component here*/}<br>                  &lt;h2&gt;Programming 2Language&lt;/h2&gt;<br>                &lt;/ListComponent&gt;<br>                &lt;ListComponent items={frameworks} onSelectItem={handleOnSelectItem}&gt;<br>                  &lt;h2&gt;Framework&lt;/h2&gt;<br>                &lt;/ListComponent&gt;<br>            &lt;/div&gt;<br>        &lt;/&gt;<br>    )</pre><h3>State Management</h3><ul><li>React update State Hook asynchronously (so it will update in one go for performance reason)</li><li>React stores the state outside of the component</li><li>Hook should be at the top level of the components</li></ul><p>State Structuring Best Practise</p><ul><li>Use a variable to combine multiple states</li><li>Group related states together in an object (like firstName and lastName for a person)</li><li>Avoid deeply nested structure, always use flat or 1 level object</li></ul><h4>Pure Component / Function</h4><ul><li>given same input, always return the same output and no side effects</li><li>keep any changes as part of rendering the component</li></ul><pre>// Pure component explanation<br>// if count declared outside component, during rendering this count<br>// will keep incrementing<br>// let count = 0<br><br>const Component = ()=&gt; {<br>  // should define the count here to keep it pure<br>  let count = 0<br>  count++<br>  return &lt;div&gt;Count:{count}&lt;/div&gt;<br>}</pre><h4>Strict Mode</h4><ul><li>activated during development only</li><li><a href="https://react.dev/reference/react/StrictMode">https://react.dev/reference/react/StrictMode</a></li></ul><p>Strict Mode enables the following development-only behaviors:</p><ul><li>Your components will <a href="https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-double-rendering-in-development">re-render an extra time</a> to find bugs caused by impure rendering.</li><li>Your components will <a href="https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-re-running-effects-in-development">re-run Effects an extra time</a> to find bugs caused by missing Effect cleanup.</li><li>Your components will <a href="https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-re-running-ref-callbacks-in-development">re-run refs callbacks an extra time</a> to find bugs caused by missing ref cleanup.</li><li>Your components will <a href="https://react.dev/reference/react/StrictMode#fixing-deprecation-warnings-enabled-by-strict-mode">be checked for usage of deprecated APIs.</a></li></ul><h4>Working with State</h4><p>Update object</p><ul><li>cannot directly update state, object need to be copied and recreate</li><li>use spread operator to copy all other properties,</li><li>note spread do shallow copy at top level only</li></ul><pre>// Update property <br>const [object, setObject] = useState({<br>  item: &#39;item1&#39;<br>  name: &#39;name&#39;<br>  quantity: 10<br>  contact: {<br>    mobile: &#39;123-456-7890&#39;<br>  }<br>})<br><br>// Then to update<br>const handleAddItem = ()=&gt;{<br>  setObject({...object, quantity:object.quantity+1})<br>}<br><br>// To update nested object<br>const handleUpdate = ()=&gt;{<br>  setObject({<br>    ...object, <br>    contact: {<br>      ...object.contact, mobile: &lt;new mobile&gt;<br>    }<br>  })<br>}</pre><p>Updating array</p><ul><li>similar to update an object</li></ul><pre>// say we have an array<br>const [names, setNames] = useState([&#39;Ali&#39;,&#39;Muthu&#39;, &#39;Chong&#39;])<br>const handleClick = () =&gt; {<br>  // Add<br>  setNames([...names, &#39;James&#39;])<br><br>  // Remove, use map filter<br>  setNames(names.filter(name =&gt; name !== &#39;Chong&#39;))<br><br>  // Update, use map with ternary operator<br>  setNames(names.map(name =&gt; (name === &#39;Chong&#39;? &#39;James&#39;:name)))<br>}</pre><h4>Sharing states between components</h4><ul><li>Basically the component holding the state need to be one level above the components that use the same state</li><li>Eg. if we have Navigation &amp; ProfilePage sharing user state, than the next level up (say App) need to hold the user state.</li><li>and the function to update the same state within same component holding the state.</li></ul><h3>Form</h3><ul><li>Default form event action is to reload the webpage. Can prevent this.</li></ul><pre>// A basic form<br>const App = () =&gt; {<br>    // useRef used together with form<br>    // specifying as HTMLInputElement so TypeScript know to use <br>    // nameRef.curr.value<br>    const nameRef = useRef&lt;HTMLInputElement&gt;(null)<br>    // pass event: FormEvent to handleSubmit function<br>    const handleSubmit = (event: FormEvent) =&gt; {<br>        // Prevent default reload<br>        event.preventDefault()<br>        if (nameRef.current !== null)<br>          console.log(nameRef.current.value)<br>    }<br>    return (<br>        &lt;div&gt;<br>            &lt;form onSubmit={handleSubmit}&gt;<br>                &lt;div&gt;<br>                    &lt;label htmlFor=&quot;name&quot;&gt;Name&lt;/label&gt;<br>                    &lt;input <br>                      ref = {nameRef}  // correspond to nameRef<br>                      id=&quot;name&quot;        // id to this input field<br>                      type=&quot;text&quot;     // acceptable type, can be number<br>                      placeholder=&quot;Enter name&quot; // default placeholder text<br>                    /&gt;<br>                &lt;/div&gt;<br>                &lt;button &gt;Save&lt;/button&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br>    )<br>}<br><br>// Alternative to useRef is to useState<br>const App = () =&gt; {<br>    const [person, setPerson] = useState({<br>      name:&#39;&#39;<br>    })<br>    const handleSubmit = (event: FormEvent) =&gt; {<br>        event.preventDefault()<br>    }<br>    return (<br>        &lt;div&gt;<br>            &lt;form onSubmit={handleSubmit}&gt;<br>                &lt;div&gt;<br>                    &lt;label htmlFor=&quot;name&quot;&gt;Name&lt;/label&gt;<br>                    &lt;input <br>                      // this will set the state to new person for <br>                      // form event<br>                      onChange={(event)=&gt;{<br>                        setPerson({...person, name:(event.target.value)})<br>                        console.log(person)<br>                      }}<br>                      // this will directly link the form input value to <br>                      // state value<br>                      value={person.name}<br>                      id=&quot;name&quot; <br>                      type=&quot;text&quot; <br>                      placeholder=&quot;Enter name&quot;<br>                    /&gt;<br>                &lt;/div&gt;<br>                &lt;button&gt;Save&lt;/button&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><h3>UseEffect &amp; Backend</h3><p>common React side effects</p><ul><li>Save data in local storage</li><li>Make API request to the back end</li><li>manually changing DOM elements</li></ul><p>useEffect hook allow execution of a piece of code after the component has been rendered but</p><ul><li>simply add another rendering task inside the useEffect will trigger the useEffect hook again and again</li><li>this behavior can be changed by passing a dependency array. Read more <a href="https://react.dev/reference/react/useEffect#examples-dependencies">here</a></li></ul><pre>useEffect(()=&gt;{<br>  //<br>}) ; // without dependency will always run after render<br><br>useEffect(()=&gt;{<br>  //<br>}, []) ; // Does not run again<br><br>useEffect(()=&gt;{<br>  //<br>}, [a. b]) ; // Runs again if a or b are different</pre><p>useEffect can add a clean up function, example below as copy from the official documentation</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { createConnection } from &#39;./chat.js&#39;;<br><br>function ChatRoom({ roomId }) {<br>  const [serverUrl, setServerUrl] = useState(&#39;https://localhost:1234&#39;);<br><br>  useEffect(() =&gt; {<br>    const connection = createConnection(serverUrl, roomId);<br>    connection.connect();<br>    // This part is the clean up function, during useEffect we connect to<br>    // the connection, if the user navigate away and exit the useEffect<br>    // then we disconnect the connection<br>    return () =&gt; {<br>      connection.disconnect();<br>    };<br>  }, [serverUrl, roomId]);<br>  // ...<br>}</pre><p>To make API request to the backend, can either use</p><ul><li>javascript fetch function or</li><li><a href="https://www.npmjs.com/package/axios">axios</a></li></ul><p><a href="https://jsonfakery.com/">https://jsonfakery.com/</a> provide some apis for you to practise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c7db929e25" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>