How Many r’s Are in Cranberry?

In an age when AGI is a common topic of conversation, it may seem strange that some models cannot even count the letters in a word correctly.
This weakness arises because LLMs process text as tokens rather than individual characters. That said, it is rarely reproducible in the latest frontier models.
There are also benchmarks that similarly probe the weaknesses of LLMs. SimpleBench consists of questions that are easy for humans but likely to confuse models that rely on statistical patterns learned during pretraining.
So when you encounter a problem, the first question to ask is, ‘Is AI the right tool for solving this problem?’
For problems with a clear correct answer, such as counting letters, a traditional program using deterministic logic is more accurate and efficient.
That single line, "cranberry".count("r"), is faster, cheaper, and never wrong compared with calling a model. It is even more environmentally friendly.
Local Tools

Let’s reproduce the problem directly in Python. If we ask the gemini-2.5-flash-lite model, we can see that it gives the wrong answer.
from langchain.chat_models import init_chat_modelllm = init_chat_model("google_genai:gemini-2.5-flash-lite")response = llm.invoke("How many r's are in cranberry?")print(response.text) # There are **two** r's in the word "cranberry" ❌Even a somewhat limited model can solve this problem when connected to a tool.
A local tool with explicitly defined internal logic is simple yet accurate, predictable, and reliable.
Let’s look at the complete code first, then break it down piece by piece.
from langchain.chat_models import init_chat_modelfrom langchain_core.messages import HumanMessagefrom langchain_core.tools import tool# 1. Define the tool@tooldef count(letter: str, word: str) -> int: """Count how many times a letter appears in a word.""" return word.count(letter)llm = init_chat_model("google_genai:gemini-2.5-flash-lite")# 2. Bind the tooltools = [count]llm_with_tools = llm.bind_tools(tools)messages = [HumanMessage("How many r's are in cranberry?")]# 3. Infer which tool to call and with what argsai_msg = llm_with_tools.invoke(messages)messages.append(ai_msg)# 4. Execute the requested tooltools_by_name = {tool.name: tool for tool in tools}for tool_call in ai_msg.tool_calls: selected_tool = tools_by_name[tool_call["name"]] tool_msg = selected_tool.invoke(tool_call) messages.append(tool_msg)# 5. Generate the final answer from the tool resultresponse = llm_with_tools.invoke(messages)print(response.text) # That's 3. ✅Defining the Tool
@tooldef count(letter: str, word: str) -> int: """Count how many times a letter appears in a word.""" return word.count(letter)- The
@tooldecorator converts an ordinary function into a LangChain tool object - Function name ➡️ tool name, type hints ➡️ argument schema, docstring ➡️ tool description
- The model cannot see the code inside the function, so it uses only this metadata to determine the tool’s purpose and when and how to call it
- This is why a clear function signature and docstring matter
Binding the Tool
tools = [count]llm_with_tools = llm.bind_tools(tools)bind_toolsconverts tool information into a schema that the model vendor (Google, OpenAI, and so on) can understand- This step tells the model which tools are available
- The model does not execute the tool itself; it only decides which tool to call and with which arguments
Inferring Which Tool to Call and with Which Arguments
messages = [HumanMessage("How many r's are in cranberry?")]ai_msg = llm_with_tools.invoke(messages)messages.append(ai_msg)Instead of answering directly, the model returns information for a tool call
It may not be able to count letters, but it is good at extracting arguments from a question and passing them to the right tool
ai_msg.tool_callscontains a value like the followingPython [ { "name": "count", "args": {"word": "cranberry", "letter": "r"}, "id": "1b922040-f8c1-4884-b365-a52fc1cf3141", "type": "tool_call", }]
Executing the Tool
tools_by_name = {tool.name: tool for tool in tools}for tool_call in ai_msg.tool_calls: selected_tool = tools_by_name[tool_call["name"]] tool_msg = selected_tool.invoke(tool_call) messages.append(tool_msg)Finds and executes the actual tool by the name requested by the model
The model can request multiple tool calls at once, so they are handled in a loop
Passing the entire
tool_calldictionary toinvokereturns the execution result wrapped in aToolMessagePython ToolMessage( content="3", name="count", tool_call_id="1b922040-f8c1-4884-b365-a52fc1cf3141",)
Generating the Final Answer from the Tool Result
response = llm_with_tools.invoke(messages)print(response.text) # That's 3. ✅At this point,
messagescontains the conversation history in orderPython [ HumanMessage(...), # User's question AIMessage(...), # Information for the tool call ToolMessage(...), # Tool execution result]The model reads the entire conversation history and generates a final answer based on the tool’s result
This creates a division of labor: the model handles understanding the question, selecting a tool, and communicating the result, while deterministic logic handles the calculations that need to be exact
API-Based Tools

A tool that a developer defines directly with the @tool decorator is called a custom tool.
The count tool we created earlier is also a custom tool, and more specifically, a local tool.
With a local tool, both the logic and the data reside in the same process as the agent.
An API-based tool is also defined within the agent application, but the actual service is provided by another server behind an API.
In this case, the tool acts as a custom adapter connecting the model to an external API.
It builds an API request from the arguments provided by the model, then processes the response into a form the model can easily read and returns it.
This allows the model to use data outside the agent, such as Pokémon types.
Below is an example using PokeAPI, along with its output.
@tooldef get_pokemon_types(pokemon: str) -> str: """Get a Pokemon's types by its English name. Returns comma-separated types.""" api_url = f"https://pokeapi.co/api/v2/pokemon/{pokemon.lower()}" try: response = requests.get(api_url) if response.status_code == 200: data = response.json() types = [t["type"]["name"] for t in data["types"]] return ", ".join(types) else: return f"fail: PokeAPI returned HTTP {response.status_code}, try again later" except requests.exceptions.RequestException as e: return f"fail: could not reach PokeAPI ({type(e).__name__})"Slowking is a Water and Psychic type Pokémon.
(Note: Its regional variant, Galarian Slowking, is Poison/Psychic).
I asked about Slowking, and it even tells me the types of Galarian Slowking.