Spaces:
Paused
Paused
File size: 5,687 Bytes
1f77df0 |
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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
"""
Simple tool-calling chat with ExCom AI
Works around vLLM's tool_choice requirements
"""
from openai import OpenAI
import json
from datetime import datetime
import math
# Configure OpenAI client for your vLLM endpoint
client = OpenAI(
base_url="https://plarnholt-excom-ai-demo.hf.space/v1",
api_key="not-needed"
)
# Define tools
tools = [
{
"type": "function",
"function": {
"name": "calculator",
"description": "Evaluates a mathematical expression",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Math expression to evaluate, e.g., '2 + 2 * 3'"
}
},
"required": ["expression"]
}
}
},
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Returns the current date and time",
"parameters": {
"type": "object",
"properties": {}
}
}
},
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Gets the weather for a city (simulated)",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
}
},
"required": ["city"]
}
}
}
]
# Tool implementations
def calculator(expression: str) -> str:
try:
result = eval(expression, {"__builtins__": {}, "math": math})
return str(result)
except Exception as e:
return f"Error: {str(e)}"
def get_current_time() -> str:
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def get_weather(city: str) -> str:
weather_data = {
"paris": "18°C, sunny",
"london": "15°C, cloudy",
"new york": "22°C, partly cloudy",
"tokyo": "25°C, clear",
}
return weather_data.get(city.lower(), f"Weather data not available for {city}")
# Function dispatcher
def execute_tool(tool_name: str, arguments: dict) -> str:
if tool_name == "calculator":
return calculator(arguments["expression"])
elif tool_name == "get_current_time":
return get_current_time()
elif tool_name == "get_weather":
return get_weather(arguments["city"])
else:
return f"Unknown tool: {tool_name}"
def chat(user_message: str, messages: list = None):
"""Send a message and handle tool calls"""
if messages is None:
messages = []
# Add user message
messages.append({"role": "user", "content": user_message})
# Call the model with tools (no tool_choice parameter)
response = client.chat.completions.create(
model="excom-ai",
messages=messages,
tools=tools,
temperature=0.4
)
assistant_message = response.choices[0].message
# Check if model wants to use tools
if assistant_message.tool_calls:
# Add assistant's tool call request to messages
messages.append({
"role": "assistant",
"content": assistant_message.content,
"tool_calls": [
{
"id": tc.id,
"type": "function",
"function": {
"name": tc.function.name,
"arguments": tc.function.arguments
}
}
for tc in assistant_message.tool_calls
]
})
# Execute each tool call
for tool_call in assistant_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
print(f"🔧 Calling tool: {function_name}({function_args})")
# Execute the tool
tool_result = execute_tool(function_name, function_args)
# Add tool result to messages
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"name": function_name,
"content": tool_result
})
# Get final response from model
final_response = client.chat.completions.create(
model="excom-ai",
messages=messages,
temperature=0.4
)
return final_response.choices[0].message.content, messages
else:
# No tools needed, return direct response
return assistant_message.content, messages
def main():
print("=" * 60)
print("ExCom AI - Simple Tool Calling Chat")
print("=" * 60)
print("Available tools:")
print(" • calculator - Evaluate math expressions")
print(" • get_current_time - Get current date/time")
print(" • get_weather - Get weather for cities")
print("\nType 'quit' or 'exit' to end.")
print("=" * 60)
print()
messages = []
while True:
user_input = input("You: ").strip()
if user_input.lower() in ['quit', 'exit', 'q']:
print("Goodbye!")
break
if not user_input:
continue
try:
response, messages = chat(user_input, messages)
print(f"Assistant: {response}\n")
except Exception as e:
print(f"❌ Error: {e}\n")
# Reset messages on error
messages = []
if __name__ == "__main__":
main()
|