Function Calling Example¶
OpenAI-compatible function calling with tools:
1#!/usr/bin/env python
2"""
330 Function Calling - Let AI Call Your Functions
4
5Learn how to give the AI access to tools/functions.
6The AI can decide when and how to call your functions.
7
8Level: Advanced Feature
9"""
10
11from config_loader import get_chat_config, parse_args
12
13from lexilux import Chat, FunctionTool, create_conversation_history, execute_tool_calls
14
15
16def main():
17 """Demonstrate function calling."""
18 args = parse_args()
19 try:
20 config = get_chat_config(config_path=args.config)
21 except (FileNotFoundError, KeyError) as e:
22 print(f"Configuration error: {e}")
23 print("\nUsing placeholder values. Please configure test_endpoints.json")
24 config = {
25 "base_url": "https://api.example.com/v1",
26 "api_key": "your-api-key",
27 "model": "gpt-4",
28 }
29
30 chat = Chat(**config)
31
32 # Example 1: Simple function calling
33 print("=" * 50)
34 print("Example 1: Simple Function Calling")
35 print("=" * 50)
36
37 # Define a function the AI can call
38 get_weather = FunctionTool(
39 name="get_weather",
40 description="Get the current weather for a location",
41 parameters={
42 "type": "object",
43 "properties": {
44 "location": {
45 "type": "string",
46 "description": "City name, e.g. Paris, Tokyo",
47 },
48 "unit": {
49 "type": "string",
50 "enum": ["celsius", "fahrenheit"],
51 "description": "Temperature unit",
52 },
53 },
54 "required": ["location"],
55 },
56 )
57
58 # Make a request with the tool
59 messages = [{"role": "user", "content": "What's the weather in Paris?"}]
60
61 result = chat(messages, tools=[get_weather])
62
63 # Check if AI wants to call a function
64 if result.has_tool_calls:
65 print("AI wants to call a function:")
66 for tool_call in result.tool_calls:
67 print(f" Function: {tool_call.name}")
68 print(f" Arguments: {tool_call.get_arguments()}")
69 else:
70 print(f"AI response: {result.text}")
71
72 # Example 2: Execute the function and continue
73 print("\n" + "=" * 50)
74 print("Example 2: Execute and Continue Conversation")
75 print("=" * 50)
76
77 # Simulated function implementations
78 def get_weather_impl(location: str, unit: str = "celsius") -> str:
79 """Simulated weather function."""
80 temps = {
81 "Paris": "22°C",
82 "Tokyo": "28°C",
83 "New York": "25°C",
84 }
85 temp = temps.get(location, "20°C")
86 return f"The weather in {location} is {temp}."
87
88 def get_time_impl(location: str) -> str:
89 """Simulated time function."""
90 times = {
91 "Paris": "14:30",
92 "Tokyo": "21:30",
93 "New York": "08:30",
94 }
95 time = times.get(location, "12:00")
96 return f"The current time in {location} is {time}."
97
98 # Define another tool
99 get_time = FunctionTool(
100 name="get_time",
101 description="Get the current time for a location",
102 parameters={
103 "type": "object",
104 "properties": {
105 "location": {
106 "type": "string",
107 "description": "City name",
108 },
109 },
110 "required": ["location"],
111 },
112 )
113
114 tools = [get_weather, get_time]
115 tool_map = {
116 "get_weather": get_weather_impl,
117 "get_time": get_time_impl,
118 }
119
120 # Make a request
121 messages = [{"role": "user", "content": "What's the weather and time in Paris?"}]
122
123 result = chat(messages, tools=tools)
124
125 # Loop until AI has all information it needs
126 max_iterations = 5
127 for i in range(max_iterations):
128 if result.has_tool_calls:
129 print(f"\nIteration {i + 1}: Executing tool calls...")
130
131 # Execute the tool calls
132 tool_responses = execute_tool_calls(result, tool_map)
133
134 for response in tool_responses:
135 print(f" Tool result: {response.content}")
136
137 # Continue conversation with tool results
138 messages = create_conversation_history(messages, result, tool_responses)
139 result = chat(messages, tools=tools)
140 else:
141 print(f"\nFinal answer: {result.text}")
142 break
143
144 # Example 3: Parallel function calls
145 print("\n" + "=" * 50)
146 print("Example 3: Parallel Function Calls")
147 print("=" * 50)
148
149 messages = [
150 {"role": "user", "content": "What's the weather in Paris, Tokyo, and New York?"}
151 ]
152
153 result = chat(messages, tools=[get_weather])
154
155 if result.has_tool_calls:
156 print(f"AI wants to call {len(result.tool_calls)} functions in parallel:")
157 for tool_call in result.tool_calls:
158 print(f" - {tool_call.name}({tool_call.get_arguments()})")
159
160
161if __name__ == "__main__":
162 main()