"""Native Qwen tool calling on ZeroGPU or Hugging Face Inference Providers.""" import json import os import re import uuid MODEL_ID = "Qwen/Qwen2.5-7B-Instruct" BACKEND = os.getenv("LLM_BACKEND", "zerogpu") CALL_BLOCK = re.compile(r"(.*?)", re.S) def parse_call(name, arguments, call_id=None): call = {"id": call_id or "call_" + uuid.uuid4().hex, "name": name, "arguments": arguments} try: if isinstance(arguments, str): arguments = json.loads(arguments) if not isinstance(name, str) or not name or not isinstance(arguments, dict): raise ValueError("invalid shape") call["arguments"] = arguments except (ValueError, TypeError): call["error"] = "malformed tool call" return call def parse_qwen(text): calls = [] for block in CALL_BLOCK.findall(text): try: value = json.loads(block) if not isinstance(value, dict): raise ValueError("invalid shape") calls.append(parse_call(value.get("name"), value.get("arguments"))) except (ValueError, TypeError): calls.append({"id": "call_" + uuid.uuid4().hex, "name": "malformed", "arguments": {}, "error": "malformed tool call"}) content = CALL_BLOCK.sub("", text).strip() if "" in content or "" in content: calls.append({"id": "call_" + uuid.uuid4().hex, "name": "malformed", "arguments": {}, "error": "malformed tool call"}) content = content.split("")[0].replace("", "").strip() return {"content": content, "tool_calls": calls} class APIBackend: def generate(self, messages, tools): from huggingface_hub import InferenceClient # Instantiate on demand: the UI can start without a token and report errors honestly. client = InferenceClient(model=MODEL_ID, token=os.environ["HF_TOKEN"]) response = client.chat_completion(messages, tools=tools, tool_choice="auto", temperature=0, max_tokens=1024) message = response.choices[0].message calls = [parse_call(c.function.name, c.function.arguments, c.id) for c in (message.tool_calls or [])] return {"content": message.content or "", "tool_calls": calls} if BACKEND == "zerogpu": import spaces import torch from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map="cuda", torch_dtype=torch.bfloat16) model.eval() @spaces.GPU def generate_zero(messages, tools): # Qwen templates expect tool arguments as objects; APIs expect JSON strings. local_messages = [] for message in messages: message = dict(message) if message.get("tool_calls"): message["tool_calls"] = [ {**call, "function": {**call["function"], "arguments": json.loads(call["function"]["arguments"])}} for call in message["tool_calls"] ] local_messages.append(message) prompt = tokenizer.apply_chat_template(local_messages, tools=tools, add_generation_prompt=True, tokenize=False) inputs = tokenizer(prompt, return_tensors="pt").to("cuda") with torch.inference_mode(): output = model.generate(**inputs, do_sample=False, max_new_tokens=1024) return parse_qwen(tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)) class ZeroBackend: def generate(self, messages, tools): return generate_zero(messages, tools) def get_backend(): if BACKEND == "hf_api": return APIBackend() if BACKEND == "zerogpu": return ZeroBackend() raise ValueError("LLM_BACKEND must be zerogpu or hf_api")