1. Agent Loop With LangChain

1.1. Resources

1.2. Set up env

  1. 添加依赖
uv add langchain langchain-ollama langchain-openai python-dotenv black isort
  1. Add .env
OPENAI_API_KEY=xxxx
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=xxxx
LANGSMITH_PROJECT=product-agent
  1. Install qwen3 by ollama

    • 打开qwen3,可以看到所有的models,我们选择下载qwen3:1.7b
    • 命令行执行:ollama pull qwen3:1.7b
    • 运行qwen3:1.7b:ollama run qwen3:1.7b

      >>> Hello
      Thinking...
      Okay, the user said "Hello" so I should respond politely. Let me check the previous messages to make sure I'm consistent. The user hasn't provided any specific context yet, so I should keep it general. Maybe 
      start with a greeting and offer help. Let me make sure the tone is friendly and open-ended. I'll say something like, "Hello! How can I assist you today?" That sounds good. No need for any extra details 
      unless the user mentions something specific. Keep it simple and welcoming.
      ...done thinking.
      
      Hello! How can I assist you today?
      
      >>> /bye
      
    • 启动ollama:ollama serve

1.3. Add tools

from langchain.tools import tool

# --- Tools (Langchain @tool decorator) ---

@tool
def get_product_price(product: str) -> float:
    """Look up the price of a product in the catalog."""
    print(f"    >> Executing get_product_price(product='{product}')")
    prices = {"laptop": 1299.99, "headphones": 149.95, "keyboard": 89.50}
    return prices.get(product, 0)


@tool
def apply_discount(price: float, discount_tier: str) -> float:
    """Apply a discount tier to a price and return the final price.
    Available tiers: bronze, silver, gold."""
    print(f"    >> Executing apply_discount(price={price}, discount_tier='{discount_tier}')")
    discount_percentages = {"bronze": 5, "silver": 12, "gold": 23}
    discount = discount_percentages.get(discount_tier, 0)
    return round(price * (1 - discount / 100), 2)

1.4. Using LangChain And Defensive Prompting

from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
from langsmith import traceable

MAX_ITERATIONS = 10
MODEL = "qwen3:1.7b"

# --- Agent Loop ---

@traceable(name="LangChain Agent Loop")
def run_agent(question: str):
    tools = [get_product_price, apply_discount]
    tools_dict = {t.name: t for t in tools}

    llm = init_chat_model(f"ollama:{MODEL}", temperature=0)
    llm_with_tools = llm.bind_tools(tools)

    print(f"Question: {question}")
    print("=" * 60)

    messages = [
        SystemMessage(
            content=(
                "You are a helpful shopping assistant. "
                "You have access to a product catalog tool "
                "and a discount tool.\n\n"
                "STRICT RULES — you must follow these exactly:\n"
                "1. NEVER guess or assume any product price. "
                "You MUST call get_product_price first to get the real price.\n"
                "2. Only call apply_discount AFTER you have received "
                "a price from get_product_price. Pass the exact price "
                "returned by get_product_price — do NOT pass a made-up number.\n"
                "3. NEVER calculate discounts yourself using math. "
                "Always use the apply_discount tool.\n"
                "4. If the user does not specify a discount tier, "
                "ask them which tier to use — do NOT assume one."
            )
        ),
        HumanMessage(content=question),
    ]

    for iteration in range(1, MAX_ITERATIONS + 1):
        print(f"\n--- Iteration {iteration} ---")

        ai_message = llm_with_tools.invoke(messages)

        tool_calls = ai_message.tool_calls

        # If no tool calls, this is the final answer
        if not tool_calls:
            print(f"\nFinal Answer: {ai_message.content}")
            return ai_message.content

        # Process only the FIRST tool call — force one tool per iteration
        tool_call = tool_calls[0]
        tool_name = tool_call.get("name")
        tool_args = tool_call.get("args", {})
        tool_call_id = tool_call.get("id")

        print(f"  [Tool Selected] {tool_name} with args: {tool_args}")

        tool_to_use = tools_dict.get(tool_name)
        if tool_to_use is None:
            raise ValueError(f"Tool '{tool_name}' not found")

        observation = tool_to_use.invoke(tool_args)

        print(f"  [Tool Result] {observation}")

        messages.append(ai_message)
        messages.append(
            ToolMessage(content=str(observation), tool_call_id=tool_call_id)
        )

    print("ERROR: Max iterations reached without a final answer")
    return None

if __name__ == "__main__":
    print("Hello LangChain Agent (.bind_tools)!")
    print()
    result = run_agent("What is the price of a laptop after applying a gold discount?")

1.5. Run and View LangSmith

1.6. 工程代码

  • git@gitee.com:learnany/langchain.git
    • project/product-agent-loop-in-langchain

更新日期:11/17/2026

results matching ""

    No results matching ""