Spaces:
Sleeping
Sleeping
bug fix
Browse files
app.py
CHANGED
|
@@ -1,25 +1,46 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import torch
|
| 3 |
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 4 |
|
| 5 |
-
|
| 6 |
model_id = "google/functiongemma-270m-it"
|
| 7 |
-
processor = AutoProcessor.from_pretrained(model_id)
|
| 8 |
-
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
demo = gr.Interface(
|
| 18 |
-
fn=
|
| 19 |
-
inputs="
|
| 20 |
-
outputs="
|
| 21 |
-
title="FunctionGemma 270M Demo",
|
| 22 |
-
description="A lightweight 270M model specialized in function calling."
|
| 23 |
)
|
| 24 |
-
|
| 25 |
demo.launch()
|
|
|
|
| 1 |
+
import os, json, gradio as gr, torch
|
|
|
|
| 2 |
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 3 |
|
| 4 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 5 |
model_id = "google/functiongemma-270m-it"
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
processor = AutoProcessor.from_pretrained(model_id, token=hf_token)
|
| 8 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 9 |
+
model_id, torch_dtype=torch.float16, device_map="auto", token=hf_token
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
def process_request(user_prompt, tools_json):
|
| 13 |
+
try:
|
| 14 |
+
# 1. Parse the tools sent from the client
|
| 15 |
+
tools = json.loads(tools_json) if tools_json.strip() else []
|
| 16 |
+
|
| 17 |
+
# 2. Build the message history
|
| 18 |
+
messages = [
|
| 19 |
+
{"role": "developer", "content": "You are a model that can do function calling with the following functions"},
|
| 20 |
+
{"role": "user", "content": user_prompt}
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
# 3. Apply template with DYNAMIC tools
|
| 24 |
+
inputs = processor.apply_chat_template(
|
| 25 |
+
messages, tools=tools, add_generation_prompt=True,
|
| 26 |
+
return_dict=True, return_tensors="pt"
|
| 27 |
+
).to(model.device)
|
| 28 |
|
| 29 |
+
# 4. Generate
|
| 30 |
+
with torch.no_grad():
|
| 31 |
+
outputs = model.generate(**inputs, max_new_tokens=128, do_sample=False)
|
| 32 |
+
|
| 33 |
+
# 5. Decode just the new part
|
| 34 |
+
input_len = inputs.input_ids.shape[1]
|
| 35 |
+
return processor.decode(outputs[0][input_len:], skip_special_tokens=True)
|
| 36 |
+
|
| 37 |
+
except Exception as e:
|
| 38 |
+
return f"Error: {str(e)}"
|
| 39 |
+
|
| 40 |
+
# Gradio interface with TWO inputs
|
| 41 |
demo = gr.Interface(
|
| 42 |
+
fn=process_request,
|
| 43 |
+
inputs=[gr.Textbox(label="User Prompt"), gr.Textbox(label="Tools (JSON Array)")],
|
| 44 |
+
outputs=gr.Code(label="Model Output"),
|
|
|
|
|
|
|
| 45 |
)
|
|
|
|
| 46 |
demo.launch()
|