File size: 10,359 Bytes
d7d68cb
 
 
 
 
 
 
 
 
 
 
da7f35e
d7d68cb
 
 
 
 
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
 
 
 
 
d7d68cb
 
 
 
 
 
 
da7f35e
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7d68cb
 
da7f35e
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
 
 
 
 
d7d68cb
 
da7f35e
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
d7d68cb
 
 
 
da7f35e
d7d68cb
 
 
 
da7f35e
 
d7d68cb
da7f35e
 
 
d7d68cb
 
 
da7f35e
d7d68cb
 
 
 
 
 
da7f35e
d7d68cb
da7f35e
d7d68cb
 
da7f35e
 
 
 
d7d68cb
 
 
da7f35e
d7d68cb
da7f35e
d7d68cb
 
 
da7f35e
d7d68cb
 
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7d68cb
 
da7f35e
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
 
 
 
d7d68cb
da7f35e
 
 
 
d7d68cb
da7f35e
 
 
d7d68cb
 
da7f35e
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
 
d7d68cb
 
da7f35e
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
 
 
 
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
d7d68cb
da7f35e
d7d68cb
da7f35e
 
 
 
 
 
d7d68cb
 
 
da7f35e
d7d68cb
 
 
 
da7f35e
 
d7d68cb
 
 
 
 
 
 
da7f35e
d7d68cb
 
da7f35e
d7d68cb
da7f35e
 
 
d7d68cb
da7f35e
 
 
 
 
 
d7d68cb
da7f35e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
---
license: gemma
language:
- en
pipeline_tag: text-generation
tags:
- litert
- litert-lm
- gemma
- agent
- tool-calling
- function-calling
- multimodal
- on-device
library_name: litert-lm
---

# Agent Gemma 3n E2B - Tool Calling Edition

A specialized version of **Gemma 3n E2B** optimized for **on-device tool/function calling** with LiteRT-LM. While Google's standard LiteRT-LM models focus on general text generation, this model is specifically designed for agentic workflows with advanced tool calling capabilities.

## Why This Model?

Google's official LiteRT-LM releases provide excellent on-device inference but don't include built-in tool calling support. This model bridges that gap by:

- βœ… **Native tool/function calling** via Jinja templates
- βœ… **Multimodal support** (text, vision, audio)
- βœ… **On-device optimized** - No cloud API required
- βœ… **INT4 quantized** - Efficient memory usage
- βœ… **Production ready** - Tested and validated

Perfect for building AI agents that need to interact with external tools, APIs, or functions while running completely on-device.

## Model Details

- **Base Model**: Gemma 3n E2B
- **Format**: LiteRT-LM v1.4.0
- **Quantization**: INT4
- **Size**: ~3.2GB
- **Tokenizer**: SentencePiece
- **Capabilities**:
  - Advanced tool/function calling
  - Multi-turn conversations with tool interactions
  - Vision processing (images)
  - Audio processing
  - Streaming responses

## Tool Calling Example

The model uses a sophisticated Jinja template that supports OpenAI-style function calling:

```python
from litert_lm import Engine, Conversation

# Load the model
engine = Engine.create("gemma-3n-E2B-it-agent-fixed.litertlm", backend="cpu")
conversation = Conversation.create(engine)

# Define tools the model can use
tools = [
    {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City name"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["location"]
        }
    },
    {
        "name": "search_web",
        "description": "Search the internet for information",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "Search query"}
            },
            "required": ["query"]
        }
    }
]

# Have a conversation with tool calling
message = {
    "role": "user",
    "content": "What's the weather in San Francisco and latest news about AI?"
}

response = conversation.send_message(message, tools=tools)
print(response)
```

### Example Output

The model will generate structured tool calls:

```
<start_function_call>call:get_weather{location:San Francisco,unit:celsius}<end_function_call>
<start_function_call>call:search_web{query:latest AI news}<end_function_call>
<start_function_response>
```

You then execute the functions and send back results:

```python
# Execute tools (your implementation)
weather = get_weather("San Francisco", "celsius")
news = search_web("latest AI news")

# Send tool responses back
tool_response = {
    "role": "tool",
    "content": [
        {
            "name": "get_weather",
            "response": {"temperature": 18, "condition": "partly cloudy"}
        },
        {
            "name": "search_web",
            "response": {"results": ["OpenAI releases GPT-5...", "..."]}
        }
    ]
}

final_response = conversation.send_message(tool_response)
print(final_response)
# "The weather in San Francisco is 18Β°C and partly cloudy.
#  In AI news, OpenAI has released GPT-5..."
```

## Advanced Features

### Multi-Modal Tool Calling

Combine vision, audio, and tool calling:

```python
message = {
    "role": "user",
    "content": [
        {"type": "image", "data": image_bytes},
        {"type": "text", "text": "What's in this image? Search for more info about it."}
    ]
}

response = conversation.send_message(message, tools=[search_tool])
# Model can see the image AND call search functions
```

### Streaming Tool Calls

Get tool calls as they're generated:

```python
def on_token(token):
    if "<start_function_call>" in token:
        print("Tool being called...")
    print(token, end="", flush=True)

conversation.send_message_async(message, tools=tools, callback=on_token)
```

### Nested Tool Execution

The model can chain tool calls:

```python
# User: "Book me a flight to Tokyo and reserve a hotel"
# Model: calls check_flights() β†’ calls book_hotel() β†’ confirms both
```

## Performance

Benchmarked on CPU (no GPU acceleration):

- **Prefill Speed**: 21.20 tokens/sec
- **Decode Speed**: 11.44 tokens/sec
- **Time to First Token**: ~1.6s
- **Cold Start**: ~4.7s
- **Tool Call Latency**: ~100-200ms additional

GPU acceleration provides 3-5x speedup on supported hardware.

## Installation & Usage

### Requirements

1. **LiteRT-LM Runtime** - Build from source:
   ```bash
   git clone https://github.com/google-ai-edge/LiteRT.git
   cd LiteRT/LiteRT-LM
   bazel build -c opt //runtime/engine:litert_lm_main
   ```

2. **Supported Platforms**: Linux (clang), macOS, Android

### Quick Start

```bash
# Download model
wget https://huggingface.co/kontextdev/agent-gemma/resolve/main/gemma-3n-E2B-it-agent-fixed.litertlm

# Run with simple prompt
./bazel-bin/runtime/engine/litert_lm_main \
  --model_path=gemma-3n-E2B-it-agent-fixed.litertlm \
  --backend=cpu \
  --input_prompt="Hello, I need help with some tasks"

# Run with GPU (if available)
./bazel-bin/runtime/engine/litert_lm_main \
  --model_path=gemma-3n-E2B-it-agent-fixed.litertlm \
  --backend=gpu \
  --input_prompt="What can you help me with?"
```

### Python API (Recommended)

```python
from litert_lm import Engine, Conversation, SessionConfig

# Initialize
engine = Engine.create("gemma-3n-E2B-it-agent-fixed.litertlm", backend="gpu")

# Configure session
config = SessionConfig(
    max_tokens=2048,
    temperature=0.7,
    top_p=0.9
)

# Start conversation
conversation = Conversation.create(engine, config)

# Define your tools
tools = [...]  # Your function definitions

# Chat with tool calling
while True:
    user_input = input("You: ")
    response = conversation.send_message(
        {"role": "user", "content": user_input},
        tools=tools
    )

    # Handle tool calls if present
    if has_tool_calls(response):
        results = execute_tools(extract_calls(response))
        response = conversation.send_message({
            "role": "tool",
            "content": results
        })

    print(f"Agent: {response['content']}")
```

## Tool Call Format

The model uses this format for tool interactions:

**Function Declaration** (system/developer role):
```
<start_of_turn>developer
<start_function_declaration>
{
  "name": "function_name",
  "description": "What it does",
  "parameters": {...}
}
<end_function_declaration>
<end_of_turn>
```

**Function Call** (assistant):
```
<start_function_call>call:function_name{arg1:value1,arg2:value2}<end_function_call>
```

**Function Response** (tool role):
```
<start_function_response>response:function_name{result:value}<end_function_response>
```

## Use Cases

### Personal AI Assistant
- Calendar management
- Email sending
- Web searching
- File operations

### IoT & Smart Home
- Device control
- Sensor monitoring
- Automation workflows
- Voice commands

### Development Tools
- Code generation with API calls
- Database queries
- Deployment automation
- Testing & debugging

### Business Applications
- CRM integration
- Data analysis
- Report generation
- Customer support

## Model Architecture

Built on Gemma 3n E2B with 9 optimized components:

```
Section 0: LlmMetadata (Agent Jinja template)
Section 1: SentencePiece Tokenizer
Section 2: TFLite Embedder
Section 3: TFLite Per-Layer Embedder
Section 4: TFLite Audio Encoder (HW accelerated)
Section 5: TFLite End-of-Audio Detector
Section 6: TFLite Vision Adapter
Section 7: TFLite Vision Encoder
Section 8: TFLite Prefill/Decode (INT4)
```

All components are optimized for on-device inference with hardware acceleration support.

## Comparison

| Feature | Standard Gemma LiteRT-LM | This Model |
|---------|-------------------------|------------|
| Text Generation | βœ… | βœ… |
| Tool Calling | ❌ | βœ… |
| Multimodal | βœ… | βœ… |
| Streaming | βœ… | βœ… |
| On-Device | βœ… | βœ… |
| Jinja Templates | Basic | Advanced Agent Template |
| INT4 Quantization | βœ… | βœ… |

## Limitations

- **Tool Execution**: The model generates tool calls but doesn't execute them - you need to implement the actual functions
- **Context Window**: Limited to 4096 tokens (configurable)
- **Streaming Tool Calls**: Partial tool calls may need buffering
- **Hardware Requirements**: Minimum 4GB RAM recommended
- **No Native GPU on CPU-only systems**: Falls back to CPU inference

## Tips for Best Results

1. **Clear Tool Descriptions**: Provide detailed function descriptions
2. **Schema Validation**: Validate tool call arguments before execution
3. **Error Handling**: Handle malformed tool calls gracefully
4. **Context Management**: Keep conversation history concise
5. **Temperature**: Use 0.7-0.9 for creative tasks, 0.3-0.5 for precise tool calls
6. **Batching**: Process multiple tool calls in parallel when possible

## License

This model inherits the [Gemma license](https://ai.google.dev/gemma/terms) from the base model.

## Citation

```bibtex
@misc{agent-gemma-litertlm,
  title={Agent Gemma 3n E2B - Tool Calling Edition},
  author={kontextdev},
  year={2025},
  publisher={HuggingFace},
  howpublished={\url{https://huggingface.co/kontextdev/agent-gemma}}
}
```

## Links

- [LiteRT-LM GitHub](https://github.com/google-ai-edge/LiteRT/tree/main/LiteRT-LM)
- [Gemma Model Family](https://ai.google.dev/gemma)
- [LiteRT Documentation](https://ai.google.dev/edge/litert)
- [Tool Calling Guide](https://ai.google.dev/gemma/docs/function-calling)

## Support

For issues or questions:
- Open an issue on [GitHub](https://github.com/google-ai-edge/LiteRT/issues)
- Check the [LiteRT-LM docs](https://ai.google.dev/edge/litert/inference)
- Community forum: [Google AI Edge](https://discuss.ai.google.dev/)

---

Built with ❀️ for the on-device AI community