Views
No views yet

| Agent | Handles | Parameters |
|---|---|---|
| 🔧 Technical Support | Crashes, bugs, API errors, authentication issues | issue_type, priority |
| 💰 Billing | Payments, refunds, subscriptions, invoices | request_type, urgency |
| 📊 Product Info | Features, integrations, plans, compliance | query_type, category |
google/functiongemma-270m-it| Metric | Before Training | After Training | Improvement |
|---|---|---|---|
| Accuracy | 4.3% | 82.6% | +78.3% |
| Correct Predictions | 1/23 | 19/23 | +18 |
pip install transformers torch1from transformers import AutoTokenizer, AutoModelForCausalLM
2import re
3import json
4
5# Load model and tokenizer
6model_name = "bhaiyahnsingh45/functiongemma-multiagent-router"
7tokenizer = AutoTokenizer.from_pretrained(model_name)
8model = AutoModelForCausalLM.from_pretrained(
9 model_name,
10 device_map="auto",
11 torch_dtype="auto"
12)
13
14# Define your agent tools
15from transformers.utils import get_json_schema
16
17def technical_support_agent(issue_type: str, priority: str) -> str:
18 """
19 Routes technical issues to specialized support team.
20
21 Args:
22 issue_type: Type of technical issue (crash, authentication, performance, api_error, etc.)
23 priority: Priority level (low, medium, high)
24 """
25 return f"Routing to Technical Support: {issue_type} with {priority} priority"
26
27def billing_agent(request_type: str, urgency: str) -> str:
28 """
29 Routes billing and payment queries.
30
31 Args:
32 request_type: Type of request (refund, invoice, upgrade, cancellation, etc.)
33 urgency: How urgent (low, medium, high)
34 """
35 return f"Routing to Billing: {request_type} with {urgency} urgency"
36
37def product_info_agent(query_type: str, category: str) -> str:
38 """
39 Routes product information queries.
40
41 Args:
42 query_type: Type of query (features, comparison, integrations, limits, etc.)
43 category: Category (plans, storage, mobile, security, etc.)
44 """
45 return f"Routing to Product Info: {query_type} about {category}"
46
47# Get tool schemas
48AGENT_TOOLS = [
49 get_json_schema(technical_support_agent),
50 get_json_schema(billing_agent),
51 get_json_schema(product_info_agent)
52]
53
54# System message
55SYSTEM_MSG = "You are an intelligent routing agent that directs customer queries to the appropriate specialized agent."
56
57# Function to route queries
58def route_query(user_query: str):
59 """Route a user query to the appropriate agent"""
60
61 messages = [
62 {"role": "developer", "content": SYSTEM_MSG},
63 {"role": "user", "content": user_query}
64 ]
65
66 # Format prompt
67 inputs = tokenizer.apply_chat_template(
68 messages,
69 tools=AGENT_TOOLS,
70 add_generation_prompt=True,
71 return_dict=True,
72 return_tensors="pt"
73 )
74
75 # Generate
76 outputs = model.generate(
77 **inputs.to(model.device),
78 max_new_tokens=128,
79 pad_token_id=tokenizer.eos_token_id
80 )
81
82 # Decode
83 result = tokenizer.decode(
84 outputs[0][len(inputs["input_ids"][0]):],
85 skip_special_tokens=False
86 )
87
88 return result
89
90# Example usage
91query = "My app crashes when I try to upload large files"
92result = route_query(query)
93print(f"Query: {query}")
94print(f"Routing: {result}")<start_function_call>call:technical_support_agent{issue_type:crash,priority:high}<end_function_call>1query = "I'm getting a 500 error when calling the API"
2result = route_query(query)
3# Output: technical_support_agent(issue_type="api_error", priority="high")1query = "I need a refund for my annual subscription"
2result = route_query(query)
3# Output: billing_agent(request_type="refund", urgency="medium")1query = "What integrations do you support for project management?"
2result = route_query(query)
3# Output: product_info_agent(query_type="integrations", category="project_management")1def parse_function_call(output: str) -> dict:
2 """Extract function name and arguments from model output"""
3
4 pattern = r'<start_function_call>call:(\w+)\{([^}]+)\}<end_function_call>'
5 match = re.search(pattern, output)
6
7 if match:
8 func_name = match.group(1)
9 params_str = match.group(2)
10
11 # Parse parameters
12 params = {}
13 param_pattern = r'(\w+):(?:<escape>(.*?)<escape>|([^,{}]+))'
14 for p_match in re.finditer(param_pattern, params_str):
15 key = p_match.group(1)
16 val = p_match.group(2) or p_match.group(3).strip()
17 params[key] = val
18
19 return {
20 "agent": func_name,
21 "parameters": params
22 }
23
24 return {"agent": "unknown", "parameters": {}}
25
26# Use it
27query = "I was charged twice this month"
28result = route_query(query)
29parsed = parse_function_call(result)
30print(parsed)
31# Output: {'agent': 'billing_agent', 'parameters': {'request_type': 'dispute', 'urgency': 'high'}}1class MultiAgentRouter:
2 def __init__(self, model_name: str):
3 self.tokenizer = AutoTokenizer.from_pretrained(model_name)
4 self.model = AutoModelForCausalLM.from_pretrained(
5 model_name,
6 device_map="auto",
7 torch_dtype="auto"
8 )
9 self.system_msg = "You are an intelligent routing agent..."
10
11 def route(self, query: str) -> dict:
12 """Route query and return agent + parameters"""
13 messages = [
14 {"role": "developer", "content": self.system_msg},
15 {"role": "user", "content": query}
16 ]
17
18 inputs = self.tokenizer.apply_chat_template(
19 messages,
20 tools=AGENT_TOOLS,
21 add_generation_prompt=True,
22 return_dict=True,
23 return_tensors="pt"
24 )
25
26 outputs = self.model.generate(
27 **inputs.to(self.model.device),
28 max_new_tokens=128,
29 pad_token_id=self.tokenizer.eos_token_id
30 )
31
32 result = self.tokenizer.decode(
33 outputs[0][len(inputs["input_ids"][0]):],
34 skip_special_tokens=False
35 )
36
37 return parse_function_call(result)
38
39# Usage
40router = MultiAgentRouter("bhaiyahnsingh45/functiongemma-multiagent-router")
41routing = router.route("My payment failed but I don't know why")
42print(f"Route to: {routing['agent']}")
43print(f"Parameters: {routing['parameters']}")1@misc{functiongemma_multiagent_router,
2 author = {Bhaiya Singh},
3 title = {Multi-Agent Router: Fine-tuned FunctionGemma for Customer Support},
4 year = {2025},
5 publisher = {Hugging Face},
6 howpublished = {\url{https://huggingface.co/bhaiyahnsingh45/functiongemma-multiagent-router}}
7}