Skip to content

Commit fb69f1b

Browse files
author
RobuRishabh
committed
Ollama_api_testing
1 parent 00693ef commit fb69f1b

File tree

4 files changed

+230
-0
lines changed

4 files changed

+230
-0
lines changed

mock_database.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
flights = [
2+
{
3+
"flight_number": "NY100",
4+
"origin": "New York",
5+
"destination": "London",
6+
"time": "2025-05-01 08:00",
7+
"airline": "Global Airways"
8+
},
9+
{
10+
"flight_number": "LA200",
11+
"origin": "Los Angeles",
12+
"destination": "Tokyo",
13+
"time": "2025-05-01 10:30",
14+
"airline": "Pacific Routes"
15+
},
16+
{
17+
"flight_number": "CH300",
18+
"origin": "Chicago",
19+
"destination": "Paris",
20+
"time": "2025-05-01 15:45",
21+
"airline": "Euro Connect"
22+
},
23+
{
24+
"flight_number": "SF400",
25+
"origin": "San Francisco",
26+
"destination": "Sydney",
27+
"time": "2025-05-01 23:15",
28+
"airline": "Ocean Pacific"
29+
},
30+
{
31+
"flight_number": "MI500",
32+
"origin": "Miami",
33+
"destination": "Rio de Janeiro",
34+
"time": "2025-05-02 07:30",
35+
"airline": "South American Airways"
36+
}
37+
]
38+
39+
def search_flights(query_params):
40+
"""
41+
Search for flights based on query parameters
42+
"""
43+
results = []
44+
for flight in flights:
45+
matches = True
46+
for key, value in query_params.items():
47+
if key not in flight:
48+
matches = False
49+
break
50+
# Handle the exact matches
51+
if value.lower() != flight[key].lower():
52+
matches = False
53+
break
54+
if matches:
55+
results.append(flight)
56+
return results

ollama_api.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
"""
2+
Integration with the Ollama API for natural language generation.
3+
"""
4+
import os
5+
import json
6+
import requests
7+
from dotenv import load_dotenv
8+
from typing import Tuple, List
9+
10+
load_dotenv()
11+
12+
OLLAMA_URL = os.getenv("OLLAMA_URL")
13+
if not OLLAMA_URL:
14+
raise ValueError("OLLAMA_URL environment variable is not set.")
15+
MODEL = os.getenv("OLLAMA_MODEL", "llama2")
16+
17+
def check_ollama_availability() -> Tuple[bool, str]:
18+
"""
19+
Check if the Ollama server is available by querying its health endpoint.
20+
Returns: Tuple[bool, str]: (success, message)
21+
"""
22+
try:
23+
response = requests.get(f"{OLLAMA_URL}/api/tags")
24+
if response.status_code == 200:
25+
return True, "Ollama server is available."
26+
return False, "Ollama server is not available. status code: {response.status_code}"
27+
except requests.exceptions.ConnectionError:
28+
return False, "Ollama server is not available. Connection error."
29+
except Exception as e:
30+
return False, f"An error occurred while checking Ollama availability: {str(e)}"
31+
32+
def generate_fallback_response(query:str, flights:List[dict]) -> str:
33+
"""
34+
Generate a simple response when Ollama is not available.
35+
Args: query (str): User's question
36+
flights (List[dict]): List of matching flights
37+
Returns: str: Fallback response
38+
"""
39+
if not flights:
40+
return "No flights found matching your criteria."
41+
42+
response = "Here are the flights that match your criteria:\n"
43+
for flight in flights:
44+
response += f"Flight {flight['flight_number']} from {flight['origin']} to {flight['destination']} on {flight['time']} by {flight['airline']}\n"
45+
return response
46+
47+
def generate_response(query: str, flights: List[dict]) -> str:
48+
"""
49+
Generate a natural language response using the Ollama model.
50+
Args: query (str): User's question
51+
flights (List[dict]): List of matching flights
52+
Returns: str: Natural language response
53+
"""
54+
# Check is ollama server is available
55+
is_available, message = check_ollama_availability()
56+
if not is_available:
57+
return generate_fallback_response(query, flights)
58+
try:
59+
# Prepare the prompt for Ollama model
60+
if flights:
61+
flight_info = json.dumps(flights, indent = 2)
62+
prompt = f"""
63+
User Question: {query}
64+
65+
Available Flights Information:
66+
{flight_info}
67+
Please provide a concise, natural language response that summarizes these flights, including flight numbers, times, and destinations.
68+
"""
69+
else:
70+
prompt = f"""
71+
User Question: {query}
72+
73+
No flights found matching your criteria.
74+
"""
75+
# Make the api call to Ollama
76+
response = requests.post(f"{OLLAMA_URL}/api/generate",
77+
json={
78+
"model": MODEL,
79+
"prompt": prompt,
80+
"stream": False},
81+
timeout=10 # Timeout after 10 seconds
82+
)
83+
if response.status_code == 200:
84+
try:
85+
response_data = response.json()
86+
return response_data.get("response", "Sorry, I couldn't generate a response.")
87+
except ValueError:
88+
return "There was an error processing the response from the server."
89+
else:
90+
return generate_fallback_response(query, flights)
91+
92+
except requests.exceptions.RequestException as e:
93+
return generate_fallback_response(query, flights) + f" Error: {str(e)}"
94+
except Exception as e:
95+
return generate_fallback_response(query, flights) + f" Unexpected error: {str(e)}"

query_handler.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
Query Handler to process the queries from the user and etract the required information from the database.
3+
"""
4+
from mock_database import search_flights
5+
import re
6+
7+
def parse_query(query):
8+
""""
9+
Parse user query to extract relevant search parameters
10+
11+
Args: query (str): User query
12+
Returns: dict: Query parameters
13+
"""
14+
query = query.lower()
15+
search_params = {}
16+
17+
# Check for origin city
18+
origin_indicator = ["from", "originating", "origin", "out of", "departing from", "leaving from"]
19+
for indicator in origin_indicator:
20+
if indicator in query:
21+
parts = query.split(indicator, 1) # maximum split of 1
22+
if len(parts) > 1:
23+
potential_origin = parts[1].split()[0:2].strip()
24+
search_params["origin"] = " ".join(potential_origin).title()
25+
26+
# Check for destination city
27+
dest_indicators = ["to", "arriving at", "going to"]
28+
for indicator in dest_indicators:
29+
if indicator in query:
30+
parts = query.split(indicator, 1)
31+
if len(parts) > 1:
32+
potential_dest = parts[1].split()[0:2] # Assuming 2-word city names
33+
search_params["destination"] = " ".join(potential_dest).title()
34+
35+
# Check for flight number (even if 'flight' isn't explicitly mentioned)
36+
flight_number_match = re.search(r'\b[A-Z]{2,4}\d{3,4}\b', query) # Match patterns like 'NY100' or 'LA200'
37+
if flight_number_match:
38+
search_params["flight_number"] = flight_number_match.group(0).upper()
39+
40+
return search_params
41+
42+
def process_query(query):
43+
"""
44+
Process user query and return relevant flight information
45+
46+
Args: query (str): User's question
47+
Returns: tuple: (bool success, str message, list matching_flights)
48+
"""
49+
try:
50+
search_params = parse_query(query)
51+
52+
if not search_params:
53+
return False, "I couldn't understand the flight details in your question. Please try asking about specific origins, destinations, or flight numbers.", []
54+
55+
matching_flights = search_flights(search_params)
56+
57+
if not matching_flights:
58+
return False, "No flights found matching your criteria.", []
59+
60+
return True, "Found matching flights!", matching_flights
61+
62+
except Exception as e:
63+
return False, f"An error occurred while processing your query: {str(e)}", []

test_ollama.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from ollama_api import check_ollama_availability, generate_response
2+
3+
# Test Ollama server availability
4+
is_available, message = check_ollama_availability()
5+
print(f"Server Availability: {message}")
6+
7+
# Example query and flight data to test generate_response function
8+
query = "What are the flights from New York to London?"
9+
flights = [
10+
{"flight_number": "NY100", "origin": "New York", "destination": "London", "time": "2025-05-01 08:00", "airline": "Global Airways"},
11+
{"flight_number": "NY200", "origin": "New York", "destination": "London", "time": "2025-05-02 12:00", "airline": "Air London"}
12+
]
13+
14+
# Test generating a response based on the query and flights
15+
response = generate_response(query, flights)
16+
print(f"Generated Response: \n{response}")

0 commit comments

Comments
 (0)