SixpertAI commited on
Commit
f97fae3
·
verified ·
1 Parent(s): 4f785fa

Upload examples/function_calling.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. examples/function_calling.py +198 -0
examples/function_calling.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Sixpert K2 - Function Calling Agent Example
4
+ ============================================
5
+ Demonstrates how to use Sixpert K2's function calling capabilities
6
+ in an agentic loop. K2's MoE architecture provides specialized experts
7
+ for tool selection and argument formatting.
8
+
9
+ Usage:
10
+ python function_calling.py
11
+ """
12
+
13
+ import json
14
+ import sys
15
+
16
+ try:
17
+ from llama_cpp import Llama
18
+ except ImportError:
19
+ print("Installing llama-cpp-python...")
20
+ import subprocess
21
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "llama-cpp-python"])
22
+ from llama_cpp import Llama
23
+
24
+
25
+ TOOLS = [
26
+ {
27
+ "type": "function",
28
+ "function": {
29
+ "name": "search_research_papers",
30
+ "description": "Search for academic research papers on a topic",
31
+ "parameters": {
32
+ "type": "object",
33
+ "properties": {
34
+ "query": {"type": "string", "description": "Research topic"},
35
+ "year_from": {"type": "integer", "description": "Start year"},
36
+ "max_results": {"type": "integer", "default": 10},
37
+ },
38
+ "required": ["query"],
39
+ },
40
+ },
41
+ },
42
+ {
43
+ "type": "function",
44
+ "function": {
45
+ "name": "run_python_code",
46
+ "description": "Execute Python code in a sandboxed environment",
47
+ "parameters": {
48
+ "type": "object",
49
+ "properties": {
50
+ "code": {"type": "string", "description": "Python code to execute"},
51
+ "timeout": {"type": "integer", "description": "Timeout in seconds", "default": 30},
52
+ },
53
+ "required": ["code"],
54
+ },
55
+ },
56
+ },
57
+ {
58
+ "type": "function",
59
+ "function": {
60
+ "name": "analyze_data",
61
+ "description": "Analyze a dataset and provide statistical insights",
62
+ "parameters": {
63
+ "type": "object",
64
+ "properties": {
65
+ "data_description": {"type": "string", "description": "Description of the data"},
66
+ "analysis_type": {"type": "string", "enum": ["descriptive", "inferential", "predictive"], "description": "Type of analysis"},
67
+ },
68
+ "required": ["data_description", "analysis_type"],
69
+ },
70
+ },
71
+ },
72
+ {
73
+ "type": "function",
74
+ "function": {
75
+ "name": "calculate_math",
76
+ "description": "Perform mathematical calculations",
77
+ "parameters": {
78
+ "type": "object",
79
+ "properties": {
80
+ "expression": {"type": "string", "description": "Mathematical expression"},
81
+ "precision": {"type": "integer", "description": "Decimal places", "default": 6},
82
+ },
83
+ "required": ["expression"],
84
+ },
85
+ },
86
+ },
87
+ ]
88
+
89
+
90
+ def mock_execute_tool(tool_call: dict) -> str:
91
+ """Mock execution of a tool call. Replace with real implementations."""
92
+ name = tool_call["function"]["name"]
93
+ args = json.loads(tool_call["function"]["arguments"])
94
+
95
+ print(f" Tool call: {name}({json.dumps(args, indent=2)})")
96
+
97
+ if name == "search_research_papers":
98
+ return json.dumps({
99
+ "papers": [
100
+ {"title": f"Advances in {args['query']}", "year": 2025, "citations": 42},
101
+ {"title": f"Survey of {args['query']} Methods", "year": 2024, "citations": 128},
102
+ ],
103
+ "total_found": 1247,
104
+ })
105
+ elif name == "run_python_code":
106
+ return json.dumps({"stdout": "42", "stderr": "", "exit_code": 0})
107
+ elif name == "analyze_data":
108
+ return json.dumps({
109
+ "summary": "Dataset shows normal distribution with mean=0.0, std=1.0",
110
+ "insights": ["No significant outliers detected", "Data is well-scaled"],
111
+ })
112
+ elif name == "calculate_math":
113
+ return json.dumps({"result": 3.141593, "expression": args["expression"]})
114
+
115
+ return json.dumps({"error": f"Unknown tool: {name}"})
116
+
117
+
118
+ def run_agent(model_path: str, user_query: str, max_turns: int = 5):
119
+ """Run an agentic loop with function calling."""
120
+ print(f"\nUser Query: {user_query}")
121
+ print("-" * 50)
122
+
123
+ llm = Llama(
124
+ model_path=model_path,
125
+ n_ctx=16384,
126
+ n_gpu_layers=-1,
127
+ verbose=False,
128
+ )
129
+
130
+ messages = [
131
+ {
132
+ "role": "system",
133
+ "content": (
134
+ "You are Sixpert K2, a deep reasoning engine with advanced "
135
+ "agentic capabilities. When the user asks a question that "
136
+ "requires external tools, use the available functions. "
137
+ "Think step-by-step and plan your approach before calling tools. "
138
+ "You can call multiple tools in sequence to solve complex problems."
139
+ ),
140
+ },
141
+ {"role": "user", "content": user_query},
142
+ ]
143
+
144
+ for turn in range(max_turns):
145
+ print(f"\n--- Turn {turn + 1} ---")
146
+
147
+ response = llm.create_chat_completion(
148
+ messages=messages,
149
+ tools=TOOLS,
150
+ tool_choice="auto",
151
+ temperature=0.6,
152
+ stream=False,
153
+ )
154
+
155
+ choice = response["choices"][0]
156
+ message = choice["message"]
157
+
158
+ if message.get("tool_calls"):
159
+ for tool_call in message["tool_calls"]:
160
+ print(f" Tool call: {tool_call['function']['name']}")
161
+ tool_result = mock_execute_tool(tool_call)
162
+ print(f" Result: {tool_result[:150]}...")
163
+
164
+ messages.append({
165
+ "role": "assistant",
166
+ "content": None,
167
+ "tool_calls": [tool_call],
168
+ })
169
+ messages.append({
170
+ "role": "tool",
171
+ "tool_call_id": tool_call["id"],
172
+ "content": tool_result,
173
+ })
174
+ else:
175
+ print(f"\nSixpert K2: {message['content']}")
176
+ break
177
+ else:
178
+ print("\nReached maximum turns.")
179
+
180
+
181
+ def main():
182
+ import argparse
183
+ parser = argparse.ArgumentParser(description="Sixpert K2 Function Calling")
184
+ parser.add_argument("--model", type=str, default="SixpertK2.gguf", help="Path to GGUF model")
185
+ parser.add_argument("--query", type=str, default="Calculate pi to 6 decimal places and search for research on numerical methods", help="User query")
186
+
187
+ args = parser.parse_args()
188
+
189
+ print("=" * 60)
190
+ print(" Sixpert K2 - Function Calling Agent")
191
+ print(" MoE Architecture | Deep Reasoning")
192
+ print("=" * 60)
193
+
194
+ run_agent(args.model, args.query)
195
+
196
+
197
+ if __name__ == "__main__":
198
+ main()