SixpertAI commited on
Commit
4075fc2
·
verified ·
1 Parent(s): 0dc9af3

Upload examples/function_calling.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. examples/function_calling.py +197 -0
examples/function_calling.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Sixpert K1 - Function Calling Example
4
+ ======================================
5
+ Demonstrates how to use Sixpert K1's function calling capabilities.
6
+
7
+ Usage:
8
+ python function_calling.py
9
+ """
10
+
11
+ import json
12
+ import sys
13
+
14
+ try:
15
+ from llama_cpp import Llama
16
+ except ImportError:
17
+ print("Installing llama-cpp-python...")
18
+ import subprocess
19
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "llama-cpp-python"])
20
+ from llama_cpp import Llama
21
+
22
+
23
+ # Define available functions
24
+ TOOLS = [
25
+ {
26
+ "type": "function",
27
+ "function": {
28
+ "name": "get_weather",
29
+ "description": "Get the current weather for a given location",
30
+ "parameters": {
31
+ "type": "object",
32
+ "properties": {
33
+ "location": {
34
+ "type": "string",
35
+ "description": "The city name, e.g. 'San Francisco'",
36
+ },
37
+ "unit": {
38
+ "type": "string",
39
+ "enum": ["celsius", "fahrenheit"],
40
+ "description": "Temperature unit",
41
+ },
42
+ },
43
+ "required": ["location"],
44
+ },
45
+ },
46
+ },
47
+ {
48
+ "type": "function",
49
+ "function": {
50
+ "name": "execute_code",
51
+ "description": "Execute Python code and return the result",
52
+ "parameters": {
53
+ "type": "object",
54
+ "properties": {
55
+ "code": {
56
+ "type": "string",
57
+ "description": "The Python code to execute",
58
+ },
59
+ },
60
+ "required": ["code"],
61
+ },
62
+ },
63
+ },
64
+ {
65
+ "type": "function",
66
+ "function": {
67
+ "name": "search_web",
68
+ "description": "Search the web for information on a topic",
69
+ "parameters": {
70
+ "type": "object",
71
+ "properties": {
72
+ "query": {
73
+ "type": "string",
74
+ "description": "The search query",
75
+ },
76
+ "max_results": {
77
+ "type": "integer",
78
+ "description": "Maximum number of results to return",
79
+ "default": 5,
80
+ },
81
+ },
82
+ "required": ["query"],
83
+ },
84
+ },
85
+ },
86
+ ]
87
+
88
+
89
+ def mock_execute_tool(tool_call: dict) -> str:
90
+ """Mock execution of a tool call. Replace with real implementations."""
91
+ name = tool_call["function"]["name"]
92
+ args = json.loads(tool_call["function"]["arguments"])
93
+
94
+ print(f" Executing: {name}({args})")
95
+
96
+ if name == "get_weather":
97
+ return json.dumps({
98
+ "location": args["location"],
99
+ "temperature": 22,
100
+ "condition": "Partly cloudy",
101
+ "unit": args.get("unit", "celsius"),
102
+ })
103
+ elif name == "execute_code":
104
+ return json.dumps({"result": "42", "success": True})
105
+ elif name == "search_web":
106
+ return json.dumps({
107
+ "results": [
108
+ {"title": f"Result 1 for {args['query']}", "url": "https://example.com"},
109
+ {"title": f"Result 2 for {args['query']}", "url": "https://example.org"},
110
+ ]
111
+ })
112
+ return json.dumps({"error": f"Unknown tool: {name}"})
113
+
114
+
115
+ def run_agent(model_path: str, user_query: str, max_turns: int = 5):
116
+ """Run an agentic loop with function calling."""
117
+ print(f"\nUser Query: {user_query}")
118
+ print("-" * 50)
119
+
120
+ llm = Llama(
121
+ model_path=model_path,
122
+ n_ctx=8192,
123
+ n_gpu_layers=-1,
124
+ verbose=False,
125
+ )
126
+
127
+ messages = [
128
+ {
129
+ "role": "system",
130
+ "content": (
131
+ "You are Sixpert K1, a precision logic engine. "
132
+ "When the user asks a question that requires external tools, "
133
+ "use the available functions to gather information. "
134
+ "Think step-by-step before calling any tools."
135
+ ),
136
+ },
137
+ {"role": "user", "content": user_query},
138
+ ]
139
+
140
+ for turn in range(max_turns):
141
+ print(f"\n--- Turn {turn + 1} ---")
142
+
143
+ response = llm.create_chat_completion(
144
+ messages=messages,
145
+ tools=TOOLS,
146
+ tool_choice="auto",
147
+ temperature=0.7,
148
+ stream=False,
149
+ )
150
+
151
+ choice = response["choices"][0]
152
+ message = choice["message"]
153
+
154
+ # Check if model wants to call a tool
155
+ if message.get("tool_calls"):
156
+ for tool_call in message["tool_calls"]:
157
+ print(f" Tool call: {tool_call['function']['name']}")
158
+ tool_result = mock_execute_tool(tool_call)
159
+ print(f" Result: {tool_result[:100]}...")
160
+
161
+ # Add assistant message with tool call
162
+ messages.append({
163
+ "role": "assistant",
164
+ "content": None,
165
+ "tool_calls": [tool_call],
166
+ })
167
+ # Add tool result
168
+ messages.append({
169
+ "role": "tool",
170
+ "tool_call_id": tool_call["id"],
171
+ "content": tool_result,
172
+ })
173
+ else:
174
+ # Model responded directly
175
+ print(f"\nSixpert K1: {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 K1 Function Calling")
184
+ parser.add_argument("--model", type=str, default="SixpertK1.gguf", help="Path to GGUF model")
185
+ parser.add_argument("--query", type=str, default="What's the weather in Tokyo?", help="User query")
186
+
187
+ args = parser.parse_args()
188
+
189
+ print("=" * 60)
190
+ print(" Sixpert K1 - Function Calling Agent")
191
+ print("=" * 60)
192
+
193
+ run_agent(args.model, args.query)
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()