Hands and Feet: Tools πŸ› οΈ

Tools are Python functions that your agents and teams call to interact with external systems.

Without tools, an LLM is like a brain floating in a jar: it can think and talk, but it can't interact with the world.

Tools are the hands and feet of your agents! πŸ› οΈ

Equip your agents with tools, and they can browse the web, execute database queries, send emails, query stock markets, or read files.

Kern comes with 120+ pre-built toolkits, and you can write custom Python functions to create your own tools in seconds.


πŸ› οΈ The Hello World Weather Tool

Here's how to turn a standard Python function into an agent tool:

1import random
2from kern.agent import Agent
3from kern.models.openai import OpenAIChat
4
5# 1. Write your custom Python function 🐍
6def get_weather(city: str) -> str:
7 """Get the current weather for a city.
8
9 Args:
10 city (str): The city to fetch the weather for.
11 """
12 conditions = ["sunny β˜€οΈ", "rainy 🌧️", "cloudy ☁️", "windy πŸ’¨"]
13 return f"The weather in {city} is {random.choice(conditions)}."
14
15# 2. Hand it to the agent!
16agent = Agent(
17 model=OpenAIChat(id="llama3.2:3b", base_url="http://localhost:11434/v1"),
18 tools=[get_weather], # Just pass the function directly!
19 markdown=True,
20)
21
22# The agent will analyze the query, detect it needs the weather, and call the tool πŸš€
23agent.print_response("What is the weather in Tokyo?", stream=True)
Tip

Kern inspects your Python function's name, type hints, and docstring to automatically build the JSON schema that tells the LLM how to call it. Always write descriptive docstrings! πŸ“


βš™οΈ How Tools Work Under the Hood

The execution loop follows these steps:

  1. Definition: Kern converts your Python functions into standard tool schemas.
  2. Delivery: The agent sends these schemas along with the user's prompt to the model.
  3. Execution: The model returns a tool request payload. The agent runs the Python function with the parameters provided by the model.
  4. Resynthesis: The tool outputs are sent back to the model as context. The model reads the results and generates a final response.

⚑ Concurrency: Running Tools in Parallel

If a model decides to execute multiple tool calls (e.g. "Get weather in London AND Paris"), executing them one-by-one is slow.

Kern supports parallel tool execution! When running asynchronously with arun() or aprint_response(), Kern fires off all requested tool calls concurrently on separate threads. πŸš€

βœ“

Parallel tool calling requires a model that supports concurrent function calls (like GPT-4o or Ollama running newer models like Llama 3).


βš™οΈ Smart Parameter Injection

Kern can automatically inject agent state, media inputs, or execution metadata into your tool functions without the model knowing about it.

🧠 Accessing Session State via RunContext

If your tool needs to read or write persistent session data, add run_context to its parameters:

1from kern.agent import Agent
2from kern.models.openai import OpenAIChat
3from kern.run import RunContext
4
5def add_shopping_item(run_context: RunContext, item: str) -> str:
6 """Add an item to the user's shopping list.
7
8 Args:
9 item (str): The item to add.
10 """
11 if not run_context.session_state:
12 run_context.session_state = {"list": []}
13
14 run_context.session_state["list"].append(item)
15 return f"Added. Current list: {run_context.session_state['list']}"
16
17agent = Agent(
18 model=OpenAIChat(id="llama3.2:3b", base_url="http://localhost:11434/v1"),
19 tools=[add_shopping_item],
20 session_state={"list": []},
21)
22
23agent.print_response("Add milk to my list", stream=True)

πŸ–ΌοΈ Accessing Media Inputs

You can also accept special arguments like images, videos, audio, or files directly in your tool parameters to analyze multimodal inputs.


πŸ“¦ Complex Tool Outputs with ToolResult

Sometimes tools return more than just text. What if your tool generates an image, exports a file, or plays audio?

Return a ToolResult object to send structured media content back to the agent:

1from kern.tools.function import ToolResult
2from kern.media import Image
3
4def generate_avatar(prompt: str) -> ToolResult:
5 """Generate an avatar image.
6
7 Args:
8 prompt (str): Image generation prompt.
9 """
10 # Simulate generating an avatar
11 avatar_image = Image(
12 id="avatar_1",
13 url="https://example.com/avatar.png",
14 original_prompt=prompt
15 )
16
17 return ToolResult(
18 content=f"Successfully generated avatar for prompt: '{prompt}'",
19 images=[avatar_image]
20 )

πŸ—ΊοΈ Next Steps

Explore the tool ecosystem in Kern: