-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroq_code_function_calling_2.py
More file actions
99 lines (82 loc) · 2.46 KB
/
Copy pathgroq_code_function_calling_2.py
File metadata and controls
99 lines (82 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from groq import Groq
from dotenv import load_dotenv
import os
import json
# Load environment
load_dotenv(dotenv_path=".env", override=True)
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
# ✅ WEATHER FUNCTION
def get_weather(city: str, unit: str = "celsius"):
return {
"city": city,
"temperature": 32,
"unit": unit,
"condition": "Sunny"
}
# ✅ TEMPERATURE FUNCTION ONLY
def get_temperature(city: str, unit: str = "celsius"):
return {
"city": city,
"temperature": 32,
"unit": unit
}
# ✅ FUNCTIONS DEFINITION FOR LLM
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the full weather report of a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "get_temperature",
"description": "Get only the temperature of a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}
]
# ✅ ASK MODEL
response = client.chat.completions.create(
model="openai/gpt-oss-120b",
messages=[
{"role": "system", "content": "You are an assistant that uses tools when required."},
{"role": "user", "content": "What is the temperature in Chennai now?"}
],
tools=tools,
tool_choice="auto"
)
# ✅ HANDLE FUNCTION CALL
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
for call in tool_calls:
func_name = call.function.name
args = json.loads(call.function.arguments)
print("Function Called:", func_name)
print("Arguments:", args)
# ✅ MAP FUNCTIONS
if func_name == "get_weather":
result = get_weather(**args)
elif func_name == "get_temperature":
result = get_temperature(**args)
print("\n✅ Function Result:", result)
else:
print("✅ Model Text Response:")
print(response.choices[0].message.content)