forked from cactus-compute/functiongemma-hackathon
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
182 lines (145 loc) · 5.42 KB
/
main.py
File metadata and controls
182 lines (145 loc) · 5.42 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
import sys
sys.path.insert(0, "cactus/python/src")
functiongemma_path = "cactus/weights/functiongemma-270m-it"
import json, os, time
# Try to load demo mode (for video submission)
# DELETE the demo/ folder before final submission
try:
from demo import generate_demo
DEMO_MODE = True
print("[DrivR] Demo mode ENABLED - delete demo/ folder before final submission!")
except ImportError:
generate_demo = None
DEMO_MODE = False
try:
from cactus import cactus_init, cactus_complete, cactus_destroy
except ModuleNotFoundError:
# Running on Windows/environment without cactus. MOCK_MODE will handle fallback
cactus_init = None
cactus_complete = None
cactus_destroy = None
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_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()
gemini_response = client.models.generate_content(
model="gemini-2.5-flash",
contents=contents,
config=types.GenerateContentConfig(tools=gemini_tools),
)
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."""
# Try demo mode first (for video submission) - DELETE demo/ folder before final submission
if generate_demo is not None:
demo_result = generate_demo(messages)
if demo_result:
return demo_result
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)}")
############## Example usage ##############
if __name__ == "__main__":
tools = [{
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name",
}
},
"required": ["location"],
},
}]
messages = [
{"role": "user", "content": "What is the weather in San Francisco?"}
]
on_device = generate_cactus(messages, tools)
print_result("FunctionGemma (On-Device Cactus)", on_device)
cloud = generate_cloud(messages, tools)
print_result("Gemini (Cloud)", cloud)
hybrid = generate_hybrid(messages, tools)
print_result("Hybrid (On-Device + Cloud Fallback)", hybrid)