1. Product Agent

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. 使用Ollama tool calling

  • 定义tools_for_llm
# Difference 2: Without @tool, we must MANUALLY define the JSON schema for each function.
# This is exactly what LangChain's @tool decorator generates automatically
# from the function's type hints and docstring.
tools_for_llm = [
    {
        "type": "function",
        "function": {
            "name": "get_product_price",
            "description": "Look up the price of a product in the catalog.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product": {
                        "type": "string",
                        "description": "The product name, e.g. 'laptop', 'headphones', 'keyboard'",
                    },
                },
                "required": ["product"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "apply_discount",
            "description": "Apply a discount tier to a price and return the final price. Available tiers: bronze, silver, gold.",
            "parameters": {
                "type": "object",
                "properties": {
                    "price": {"type": "number", "description": "The original price"},
                    "discount_tier": {
                        "type": "string",
                        "description": "The discount tier: 'bronze', 'silver', or 'gold'",
                    },
                },
                "required": ["price", "discount_tier"],
            },
        },
    },
]


# NOTE: Ollama can also auto-generate these schemas if you pass the functions
# directly as tools (similar to LangChain's @tool decorator):
#   tools_for_llm = [get_product_price, apply_discount]
# However, this requires your docstrings to follow the Google docstring format
# so Ollama can parse parameter descriptions from the Args section. For example:
#   def get_product_price(product: str) -> float:
#       """Look up the price of a product in the catalog.
#
#       Args:
#           product: The product name, e.g. 'laptop', 'headphones', 'keyboard'.
#
#       Returns:
#           The price of the product, or 0 if not found.
#       """
# We keep the manual JSON version here so you can see what @tool hides from you.
  • Helper: traced Ollama call
# --- Helper: traced Ollama call ---
# Difference 3: Without LangChain, we must manually trace LLM calls for LangSmith.


@traceable(name="Ollama Chat", run_type="llm")
def ollama_chat_traced(messages):
    return ollama.chat(model=MODEL, tools=tools_for_llm, messages=messages)
  • Defensive Prompting
@traceable(name="Ollama Agent Loop")
def run_agent(question: str):
    tools_dict = {
        "get_product_price": get_product_price,
        "apply_discount": apply_discount,
    }



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

    messages = [
        {
            "role": "system",
            "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."
            ),
        },
        {"role": "user", "content": question},
    ]
  • using ollama_chat_traced
# Difference 5: ollama.chat() directly instead of llm_with_tools.invoke()
response = ollama_chat_traced(messages=messages)
ai_message = response.message

tool_calls = ai_message.tool_calls
  • tool_name、tool_args
# Difference 6: Attribute access (.function.name) instead of dict access (.get("name"))
tool_name = tool_call.function.name
tool_args = tool_call.function.arguments
  • Direct function call instead of tool.invoke()
# Difference 7: Direct function call instead of tool.invoke()
observation = tool_to_use(**tool_args)
  • messages.append
messages.append(
    {
        "role": "tool",
        "content": str(observation),
    }
)

1.7. Run and view langsmith

[Running] /Users/admin/Code/langchain/.venv/bin/python -u "/Users/admin/Code/langchain/2_agent_loop_raw_function_calling.py"
Hello LangChain Agent (.bind_tools)!

Question: What is the price of a laptop after applying a gold discount?
============================================================

--- Iteration 1 ---
  [Tool Selected] get_product_price with args: {'product': 'laptop'}
    >> Executing get_product_price(product='laptop')
  [Tool Result] 1299.99

--- Iteration 2 ---
  [Tool Selected] apply_discount with args: {'price': 1299.99, 'discount_tier': 'gold'}
    >> Executing apply_discount(price=1299.99, discount_tier='gold')
  [Tool Result] 1000.99

--- Iteration 3 ---

Final Answer: The price of the laptop after applying the gold discount is **$1000.99**.

[Done] exited with code=0 in 8.792 seconds

1.8. 工程代码

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

更新日期:11/17/2026

results matching ""

    No results matching ""