Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
# Load API key from environment variables
|
| 7 |
+
load_dotenv()
|
| 8 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 9 |
+
client = OpenAI(api_key=api_key)
|
| 10 |
+
|
| 11 |
+
# Function to fetch weather details (mock implementation)
|
| 12 |
+
def get_weather(city: str):
|
| 13 |
+
weather_data = {
|
| 14 |
+
"New York": "☀️ Sunny, 25°C",
|
| 15 |
+
"London": "🌧️ Rainy, 18°C",
|
| 16 |
+
"Mumbai": "⛅ Cloudy, 30°C"
|
| 17 |
+
}
|
| 18 |
+
return weather_data.get(city, "Weather data not available for this city.")
|
| 19 |
+
|
| 20 |
+
# Function to handle user queries
|
| 21 |
+
def chat_with_llm(user_query):
|
| 22 |
+
# Define function schema
|
| 23 |
+
functions = [
|
| 24 |
+
{
|
| 25 |
+
"name": "get_weather",
|
| 26 |
+
"description": "Fetch weather details for a given city.",
|
| 27 |
+
"parameters": {
|
| 28 |
+
"type": "object",
|
| 29 |
+
"properties": {
|
| 30 |
+
"city": {"type": "string", "description": "Name of the city"}
|
| 31 |
+
},
|
| 32 |
+
"required": ["city"]
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
# Get response from GPT with function calling enabled
|
| 38 |
+
response = client.chat.completions.create(
|
| 39 |
+
model="gpt-4-turbo",
|
| 40 |
+
messages=[{"role": "user", "content": user_query}],
|
| 41 |
+
functions=functions,
|
| 42 |
+
function_call="auto" # GPT decides if function calling is needed
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
message = response.choices[0].message
|
| 46 |
+
|
| 47 |
+
# Check if function was called
|
| 48 |
+
if message.function_call:
|
| 49 |
+
try:
|
| 50 |
+
function_args = json.loads(message.function_call.arguments)
|
| 51 |
+
city = function_args.get("city")
|
| 52 |
+
if city:
|
| 53 |
+
return get_weather(city)
|
| 54 |
+
except Exception as e:
|
| 55 |
+
return f"Error processing function call: {str(e)}"
|
| 56 |
+
|
| 57 |
+
# If no function was called, return normal LLM response
|
| 58 |
+
return message.content
|
| 59 |
+
|
| 60 |
+
# Example Queries
|
| 61 |
+
print(chat_with_llm("What's the weather like in New York?")) # Function Call
|
| 62 |
+
print(chat_with_llm("Tell me a joke.")) # Normal LLM Response
|