-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
278 lines (244 loc) · 8.33 KB
/
main.py
File metadata and controls
278 lines (244 loc) · 8.33 KB
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
import sys
sys.path.insert(0, "cactus/python/src")
functiongemma_path = "cactus/weights/functiongemma-270m-it"
import json, os, time
from cactus import cactus_init, cactus_complete, cactus_destroy
from google import genai
from google.genai import types
def generate_cactus(messages, tools):
"""Run function calling on-device via FunctionGemma + Cactus."""
model = cactus_init(functiongemma_path)
cactus_tools = [{
"type": "function",
"function": t,
} for t in tools]
raw_str = cactus_complete(
model,
[{"role": "system",
"content": "You are a helpful assistant "
"that can use tools."}] + messages,
tools=cactus_tools,
force_tools=True,
max_tokens=256,
stop_sequences=["<|im_end|>", "<end_of_turn>"],
)
cactus_destroy(model)
try:
raw = json.loads(raw_str)
except json.JSONDecodeError:
return {
"function_calls": [],
"total_time_ms": 0,
"confidence": 0,
}
return {
"function_calls": raw.get("function_calls", []),
"total_time_ms": raw.get("total_time_ms", 0),
"confidence": raw.get("confidence", 0),
}
def generate_cactus_chat(messages):
"""Run on-device chat (no forced tools); returns text and confidence."""
model = cactus_init(functiongemma_path)
raw_str = cactus_complete(
model,
[{"role": "system",
"content": "You are a helpful assistant."}] + messages,
tools=None,
force_tools=False,
max_tokens=256,
stop_sequences=["<|im_end|>", "<end_of_turn>"],
)
cactus_destroy(model)
try:
raw = json.loads(raw_str)
except json.JSONDecodeError:
return {
"response": None,
"confidence": 0,
"cloud_handoff": True,
}
return {
"response": raw.get("response"),
"confidence": raw.get("confidence", 0),
"cloud_handoff": raw.get("cloud_handoff", True),
}
def generate_cloud(messages, tools):
"""Run function calling via Gemini Cloud API."""
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
gemini_tools = [
types.Tool(function_declarations=[
types.FunctionDeclaration(
name=t["name"],
description=t["description"],
parameters=types.Schema(
type="OBJECT",
properties={
k: types.Schema(type=v["type"].upper(), description=v.get("description", ""))
for k, v in t["parameters"]["properties"].items()
},
required=t["parameters"].get("required", []),
),
)
for t in tools
])
]
contents = [m["content"] for m in messages if m["role"] == "user"]
start_time = time.time()
# Try the newest Flash model first, then fall back to stable if needed.
model_candidates = ["gemini-3-flash-preview", "gemini-2.5-flash"]
last_error = None
gemini_response = None
for model_name in model_candidates:
try:
gemini_response = client.models.generate_content(
model=model_name,
contents=contents,
config=types.GenerateContentConfig(tools=gemini_tools),
)
break
except Exception as exc:
last_error = exc
if gemini_response is None:
raise last_error
total_time_ms = (time.time() - start_time) * 1000
function_calls = []
for candidate in gemini_response.candidates:
for part in candidate.content.parts:
if part.function_call:
function_calls.append({
"name": part.function_call.name,
"arguments": dict(part.function_call.args),
})
return {
"function_calls": function_calls,
"total_time_ms": total_time_ms,
}
def generate_hybrid(messages, tools, confidence_threshold=0.99):
"""Baseline hybrid inference strategy; fall back to cloud if Cactus Confidence is below threshold."""
local = generate_cactus(messages, tools)
if local["confidence"] >= confidence_threshold:
local["source"] = "on-device"
return local
cloud = generate_cloud(messages, tools)
cloud["source"] = "cloud (fallback)"
cloud["local_confidence"] = local["confidence"]
cloud["total_time_ms"] += local["total_time_ms"]
return cloud
def print_result(label, result):
"""Pretty-print a generation result."""
print(f"\n=== {label} ===\n")
if "source" in result:
print(f"Source: {result['source']}")
if "confidence" in result:
print(f"Confidence: {result['confidence']:.4f}")
if "local_confidence" in result:
print(f"Local confidence (below threshold): {result['local_confidence']:.4f}")
print(f"Total time: {result['total_time_ms']:.2f}ms")
for call in result["function_calls"]:
print(f"Function: {call['name']}")
print(f"Arguments: {json.dumps(call['arguments'], indent=2)}")
############## Tool definitions ##############
TOOLS = [
{
"name": "lookup_company_data",
"description":
"Look up data about a company such as "
"revenue, payments, contracts, or costs",
"parameters": {
"type": "object",
"properties": {
"company": {
"type": "string",
"description": "Company name",
},
"metric": {
"type": "string",
"description":
"What to look up: revenue, "
"profit, cost, payments, "
"or contract",
},
"period": {
"type": "string",
"description":
"Time period like 2025, Q3, "
"or last quarter",
},
},
"required": ["company"],
},
},
{
"name": "lookup_person",
"description":
"Look up information about a person "
"such as salary, role, or contact details",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description":
"Person's full name",
},
"info_type": {
"type": "string",
"description":
"What to look up: salary, "
"role, department, or contact",
},
},
"required": ["name"],
},
},
{
"name": "general_query",
"description":
"Handle a general question that does "
"not involve a specific company or person",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description":
"The user's question",
},
},
"required": ["query"],
},
},
]
############## Example usage ##############
if __name__ == "__main__":
test_queries = [
"Give me our revenue from Nvidia for 2025",
"What is John Smith's salary?",
"Show me the contract with Microsoft Azure",
"How much did we pay Amazon last quarter?",
"What role does Maria Garcia have?",
"Pull up costs for Tesla in Q3",
"What is the weather today?",
"Who is our contact at Google?",
"Compare payments to Apple vs Samsung",
]
for query in test_queries:
msgs = [{"role": "user", "content": query}]
result = generate_cactus(msgs, TOOLS)
fc = result.get("function_calls", [])
conf = result.get("confidence", 0)
t = result.get("total_time_ms", 0)
if fc:
c = fc[0]
args = json.dumps(
c["arguments"], ensure_ascii=False
)
print(
f"[{conf:.3f}] {query}\n"
f" -> {c['name']}({args})"
)
else:
print(
f"[{conf:.3f}] {query}\n"
f" -> MISS"
)