はじめに
LangChainでFunction Callingを試した時の記事はこちらです。touch-sp.hatenablog.com
その時作ったToolがそのままSmolAgentsで使えました。
課題
4桁の数字の間に四則演算を加えて10を作る
Toolを定義したファイル(langchain_tool.py)
from langchain.tools import tool from itertools import product # ツールとしての関数を定義 @tool def solve_puzzle(numbers: list[int]) -> list[str]: """4桁の数字の間に四則演算を加えて10を作るパズルを解く関数。 Args: numbers (list[int]): 4つの数字のリスト Returns: list[str]: 10になる数式のリスト """ operators = ['+', '-', '*', '/'] expressions = [] # すべての演算子の組み合わせを試す for ops in product(operators, repeat=3): patterns = [ f"{numbers[0]} {ops[0]} {numbers[1]} {ops[1]} {numbers[2]} {ops[2]} {numbers[3]}", f"({numbers[0]} {ops[0]} {numbers[1]}) {ops[1]} {numbers[2]} {ops[2]} {numbers[3]}", f"({numbers[0]} {ops[0]} {numbers[1]} {ops[1]} {numbers[2]}) {ops[2]} {numbers[3]}", f"({numbers[0]} {ops[0]} {numbers[1]}) {ops[1]} ({numbers[2]} {ops[2]} {numbers[3]})", f"{numbers[0]} {ops[0]} ({numbers[1]} {ops[1]} {numbers[2]}) {ops[2]} {numbers[3]}", f"{numbers[0]} {ops[0]} ({numbers[1]} {ops[1]} {numbers[2]} {ops[2]} {numbers[3]})", f"{numbers[0]} {ops[0]} {numbers[1]}) {ops[1]} ({numbers[2]} {ops[2]} {numbers[3]})" ] for exp in patterns: try: if eval(exp) == 10: expressions.append(exp) except: continue return expressions
SmolAgents実行ファイル
たったこれだけです。from smolagents import CodeAgent, OpenAIServerModel, Tool from langchain_tool import solve_puzzle my_tool = Tool.from_langchain(solve_puzzle) model = OpenAIServerModel( model_id="gemma-3-12b-it-4bit", api_base="http://localhost:8080", api_key="EMPTY" ) agent = CodeAgent( model=model, tools=[my_tool] ) agent.run("「9999」で10を作るには?")
もっと短く書くこともできます。
from smolagents import CodeAgent, OpenAIServerModel, Tool from langchain_tool import solve_puzzle agent = CodeAgent( model=OpenAIServerModel( model_id="gemma-3-12b-it-4bit", api_base="http://localhost:8080", api_key="EMPTY" ), tools=[Tool.from_langchain(solve_puzzle)] ) agent.run("「9999」で10を作るには?")
実行結果

時間がかかっているのは言語モデルを非力なPCで実行しているためです。
補足①
言語モデルはllama.cppで実行している「gemma-3-12b-it-Q4_K_M.gguf」です。./llama-server -m ~/models/gemma-3-12b-it-Q4_K_M.gguf -c 8192 -ngl 30
補足②
インストールしたのは以下の二つだけです。pip install langchain pip install smolagents[openai]