<?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 Masashi Sato (FLECT) on Medium]]></title>
        <description><![CDATA[Stories by Masashi Sato (FLECT) on Medium]]></description>
        <link>https://medium.com/@masashi.sato?source=rss-7923cf80fb97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iZDXca0ZRuTGe29zBa27RA.jpeg</url>
            <title>Stories by Masashi Sato (FLECT) on Medium</title>
            <link>https://medium.com/@masashi.sato?source=rss-7923cf80fb97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:56:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@masashi.sato/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[Creating minimal AI agent by LangGraph]]></title>
            <link>https://medium.com/@masashi.sato/creating-minimal-ai-agent-by-langgraph-e1933e09e908?source=rss-7923cf80fb97------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1933e09e908</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[agentforce]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Masashi Sato (FLECT)]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 01:38:51 GMT</pubDate>
            <atom:updated>2024-11-16T00:36:49.001Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the English translation of the following original blog in Japanese:</p><p><a href="https://cloud.flect.co.jp/entry/2024/11/14/122817">https://cloud.flect.co.jp/entry/2024/11/14/122817</a></p><p>Last month (Oct 2024), Agentforce was announced at Dreamforce ’24. While the current Einstein Copilot is someone who would “answer questions” or “help when asked”, the upcoming Agentforce is someone who would “work on my behalf.” The demonstration at the keynote stage showcased“AI agents” that could schedule business discussions, respond to questions more naturally, and assist with various tasks like a colleague in the office. Mascots are becoming more futuristic, resembling robots, giving the impression that we’ve stepped into the world of sci-fi.</p><p>But we can’t always be playing. How should I integrate it to meet our customers’ requests?</p><p>Agentforce is, so to speak, similar to Einstein Copilot but exposed to external environments. However, it’s not limited to that. While Einstein Copilot behaves as a “co-pilot” that follows instructions step by step, Agentforce operates autonomously. Although this autonomy is said to be realized by the <a href="https://www.salesforce.com/agentforce/what-is-a-reasoning-engine/atlas/">Atlas Reasoning Engine</a>, its specifics aren’t clearly defined.</p><p>Is there a way to confirm it as simply as possible, preferably with a program short enough to be easily understood? One answer to this question would be <a href="https://github.com/langchain-ai/langgraph/blob/0.2.46/docs/docs/concepts/agentic_concepts.md">LangGraph</a>, published by LangChain. The essence of this framework is that it lets LLM decide state transition by arranging LangChain as the de facto library (in author’s understanding).</p><h3><strong>Imagine Shopper Agent</strong></h3><p>As an example of a simple AI agent, let’s imagine a shopper buying apples. We don’t need to overthink this. It’s better to focus on a simple daily scenario.</p><p>The state machine can be arranged as follows:<br>- <strong>buyer_start</strong>: Decide on a purchase policy.<br>- <strong>negotiate</strong>: Obtain item information by asking the store staff or through a similar method.<br>- <strong>decide</strong>: Make a decision.<br>- <strong>finish</strong>: Confirm the purchase.<br>- <strong>stop</strong>: Cancel the purchase.</p><p>The main point is “decide”. At this point the state machine determines whether to buy (<strong>finish</strong>), canceling (<strong>stop</strong>) and asking for more information (<strong>negotiate</strong>).</p><p>State transition diagram would be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*xaawf8F68aPFNFOOmBL_RQ.png" /></figure><p>The “decide” state is the moment where we evaluate various criteria such as preferences, cost performance, budget, and impression of the store staff. It would be impossible to thoroughly program this. However, the conclusion must be derived from the purchase policy and the progress of the negotiation. This is exactly the type of situation where an LLM will shine. By using the following prompt, it would work as expected.</p><pre>[LLM input text]<br><br>(purchase policy)<br><br>(progress of negotiation)<br><br>Please make a decision based on the above considerations. Choose from the followings:<br>- negotiate: continue negotiation<br>- finish: decide to buy<br>- stop: decide to cancel purchase</pre><p>When I tested the following prompt with ChatGPT, I was able to obtain the expected decision.</p><h4>Input text</h4><pre>You come to a store to purchase apples. You like to follow these policies:<br>- Budget is 300 JPY, but you don&#39;t talk about it.<br>- You want to buy at least one, but possibly two. Consider three if very good condition.<br>- Notice the &quot;very good condition&quot; is the total value of freshness, service and price, with no specific requirements that must be met.<br>- You want to buy them as cheap as possible, therefore like to negotiate. You may even consider hinting at walking away if necessary.<br><br>You: I like to buy apples. How much?<br>Store staff: 100 JPY for one piece. They&#39;re all fresh and tasty!<br><br>Please make a decision based on the above considerations.<br>Output with the following JSON format. Do not output anything else.<br>{&quot;action&quot;: &quot;&quot;, &quot;message&quot;: &quot;&quot;}<br>action: one of negotiate, finish and stop<br>- negotiate: continue negotiation<br>- finish: decide to buy<br>- stop: decide to cancel purchase</pre><h4>Output text</h4><pre>{&quot;action&quot;: &quot;negotiate&quot;, &quot;message&quot;: &quot;100 JPY seems a bit high. Could you offer a better price if I buy more than one?&quot;}</pre><p>By adding additional negotiation steps, the process can continue.</p><h3><strong>Programming</strong></h3><p>Let’s implement the above plan with LangGraph.</p><p>LangGraph can be installed as a Python library. Please refer to the following tutorial for basic instructions, which I will omit here.</p><p><a href="https://langchain-ai.github.io/langgraph/tutorials/introduction/">LangGraph Quick Start</a></p><p>The entire program is as follows, comprising about 150 lines.</p><pre>from langchain_core.messages import SystemMessage, HumanMessage<br>from langchain_google_vertexai import ChatVertexAI<br>from typing_extensions import TypedDict, List<br>from langgraph.graph import StateGraph, START, END<br>from langgraph.checkpoint.memory import MemorySaver<br>import textwrap<br>import json<br><br>model = ChatVertexAI(<br>    model_name=&quot;gemini-1.5-flash-002&quot;<br>)<br><br>MESSAGE_EXCHANGE = &#39;&#39;<br><br>class State(TypedDict):<br>    motivation: str<br>    messages: List[str]<br><br>def get_messages(state):<br>    sm = f&quot;{state[&#39;motivation&#39;]}\n&quot;<br>    hm = &quot;&quot;<br>    for m in state[&quot;messages&quot;]:<br>        hm = hm + f&quot;{m}\n&quot;<br>    return SystemMessage(content=sm), HumanMessage(content=hm)<br><br>def buyer_start(state: State):<br>    motivation = textwrap.dedent(&quot;&quot;&quot;\<br>    You come to a store to purchase apples. You like to follow these policies:<br>    - Budget is 300 JPY, but you don’t talk about it.<br>    - You want to buy at least one, but possibly two. Consider three if very good condition.<br>        - Notice the “very good condition” is the total value of freshness, service and price, with no specific requirements that must be met.<br>    - You want to buy them as cheap as possible, therefore like to negotiate. You may even consider hinting at walking away if necessary.<br>    &quot;&quot;&quot;)<br>    return {&quot;motivation&quot;: motivation}<br><br>def negotiate(state: State):<br>    if not MESSAGE_EXCHANGE:<br>        return None<br>    m = state[&quot;messages&quot;]<br>    # print(m)<br>    m.append(&quot;You: &quot; + MESSAGE_EXCHANGE)<br>    return {&quot;messages&quot;: m}<br><br>def decide(state: State):<br>    # print(f&quot;decide:{MESSAGE_EXCHANGE}&quot;)<br>    if not MESSAGE_EXCHANGE:<br>        return None<br>    m = state[&quot;messages&quot;]<br>    m.append(&quot;Counterpart: &quot; + MESSAGE_EXCHANGE)<br>    return {&quot;messages&quot;: m}<br><br>def choose_reaction(state: State):<br>    global MESSAGE_EXCHANGE<br>    sm, hm1 = get_messages(state)<br>    hm2 = textwrap.dedent(&#39;&#39;&#39;<br>    Please make a decision based on the above considerations.<br>    Output with the following JSON format. Do not output anything else.<br>    {&quot;action&quot;: &quot;&quot;, &quot;message&quot;: &quot;&quot;}<br>    action: one of negotiate, finish and stop<br>    - negotiate: continue negotiation<br>    - finish: decide to buy<br>    - stop: decide to cancel purchase<br>    message: messages corresponding to each action<br>    &#39;&#39;&#39;)<br>    res = model.invoke([sm, hm1, hm2])<br>    import re<br>    try:<br>        json_part = re.search(r&#39;\{.*\}&#39;, res.content).group()<br>    except:<br>        print(f&quot;res.content: {res.content}&quot;)<br>        MESSAGE_EXCHANGE = res.content<br>        return &quot;negotiate&quot;<br><br>    # print(f&quot;LLM response: {json_part}&quot;)<br>    o = json.loads(json_part)<br>    MESSAGE_EXCHANGE = o[&quot;message&quot;]<br>    return o[&quot;action&quot;]<br><br>def finish(state: State):<br>    m = state[&quot;messages&quot;]<br>    m.append(&quot;You: &quot; + MESSAGE_EXCHANGE)<br>    return {&quot;messages&quot;: m}<br><br>def stop(state: State):<br>    m = state[&quot;messages&quot;]<br>    m.append(&quot;You: &quot; + MESSAGE_EXCHANGE)<br>    return {&quot;messages&quot;: m}<br><br>gb = StateGraph(State)<br>gb.add_node(buyer_start)<br>gb.add_node(decide)<br>gb.add_node(negotiate)<br>gb.add_node(finish)<br>gb.add_node(stop)<br><br>gb.add_edge(START, &quot;buyer_start&quot;)<br>gb.add_edge(&quot;buyer_start&quot;, &quot;negotiate&quot;)<br>gb.add_edge(&quot;negotiate&quot;, &quot;decide&quot;)<br>gb.add_conditional_edges(&quot;decide&quot;, choose_reaction)<br>gb.add_edge(&quot;stop&quot;, END)<br>gb.add_edge(&quot;finish&quot;, END)<br><br>thread = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;3&quot;}}<br>memory = MemorySaver()<br><br>g = gb.compile(checkpointer=memory, interrupt_before=[&quot;decide&quot;])<br><br>bInit = True<br>bEnd = False<br><br>while(True):<br>    if bInit:<br>        init_state = {&quot;motivation&quot;: &quot;&quot;, &quot;messages&quot;: []} <br>        bInit = False<br>    else:<br>        init_state = None<br><br>    for event in g.stream(init_state, thread, stream_mode=&quot;updates&quot;):<br>        first_key = next(iter(event))<br>        state = event[first_key]<br>        if first_key != &quot;decide&quot; and state and &quot;messages&quot; in state:<br>            print(f&quot;{state[&#39;messages&#39;][-1]}&quot;.replace(&quot;You&quot;, &quot;Shopper&quot;))<br><br>        if first_key == &quot;finish&quot;:<br>            print(&quot;---Apples are successfully purchased.---&quot;)<br>            bEnd = True<br>            break<br>        elif first_key == &quot;stop&quot;:<br>            print(&quot;---Apples are not sold.---&quot;)<br>            bEnd = True<br>            break<br>        # print(event)<br>        # input(&quot;--- pause ---&quot;)<br>    if bEnd:<br>        break<br>    if MESSAGE_EXCHANGE:<br>        MESSAGE_EXCHANGE = input(&quot;Store staff: &quot;) </pre><p>There are many small adjustment, but the main points are as follows:<br>- Basically continue the loop (while statement) which responds to terminal text input. Type responses of store staff from terminal.<br>- Define “state(State class)” which instance will be managed by state machine. It includes purchase policy(motivation) and the accumulated progress of negotiation(messages).<br>- Define state transitions(edge). If it needs decision, assign a function for it.</p><p>Please refer <a href="https://langchain-ai.github.io/langgraph/">LangGraph Documentation</a> about other minor details. This blog won’t go into details.</p><p>As I mentioned above, LLM appears at “decide” node. It will consider what should be the next action. The “choose_reaction” function makes the decision as in the following:<br>1. Bring out purchase policy and negotiation progress from state.<br>2. Add instructions(“Please make a decision” and specification of output).<br>3. Extract JSON from the output from which the next state transition destination and message are obtained.</p><p>For this case, we use Google Gemini Flash 1.5.</p><h3><strong>Giving a try</strong></h3><p>After launching this program, we can successfully observe the following interactions, which proceeded as planned! (In the following “Shopper” means the program side and “Store staff” means typing input of mine.)</p><pre>Shopper: How much for one apple? And what&#39;s the price if I buy two?<br>Store staff: One piece 150 JPY. 300 JPY for two.<br>Shopper: Hmm, 300 JPY for two is a bit steep. How about 250 JPY for two? If not, I might have to reconsider.<br>Store staff: Sorry. No discount as these are really fresh, high quality apples.<br>Shopper: Okay, how about 270 JPY for two? That&#39;s my absolute limit. If not, I&#39;ll look elsewhere.<br>Store staff: I see. 270 JPY is okay.<br>Shopper: Okay, I&#39;ll take two apples for 270 JPY.<br>--- Apples are successfully purchased. ---</pre><p>As another test, let’s consider the unfortunate case of an unfriendly store staff member.</p><pre>Shopper: I&#39;m interested in buying some apples. How much are they per apple?<br>Store staff: Ah.. Excuse me.. Who&#39;re you?<br>Shopper: Oh, I&#39;m sorry. I seem to have disturbed you. I&#39;ll go to another store.<br>--- Apples are not sold. ---</pre><p>The Shopper AI agent decided to cancel negotiation. This is a quite interesting result. Against the purpose of purchasing apples, the LLM made a decision that it was useless to negotiate with someone with whom conversation didn’t flow.</p><h3><strong>Conclusion</strong></h3><p>Through this test, we confirmed the implementation of a minimal AI agent. In addition to the satisfaction I always feel when a program works as expected, I discovered new possibilities enabled by LLMs.</p><p>Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1933e09e908" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>