Spaces:
Sleeping
Sleeping
Added Files
Browse files- .gitignore +194 -0
- LICENSE +21 -0
- README.md +1 -12
- app.py +77 -50
- appointments.db +0 -0
- database/__init__.py +0 -0
- database/db_handler.py +123 -0
- identifier.sqlite +0 -0
- langchain_logic/__init__.py +0 -0
- langchain_logic/agent_setup.py +49 -0
- langchain_logic/tools.py +100 -0
- requirements.txt +6 -1
.gitignore
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
.idea
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
share/python-wheels/
|
24 |
+
*.egg-info/
|
25 |
+
.installed.cfg
|
26 |
+
*.egg
|
27 |
+
MANIFEST
|
28 |
+
|
29 |
+
# PyInstaller
|
30 |
+
# Usually these files are written by a python script from a template
|
31 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
32 |
+
*.manifest
|
33 |
+
*.spec
|
34 |
+
|
35 |
+
# Installer logs
|
36 |
+
pip-log.txt
|
37 |
+
pip-delete-this-directory.txt
|
38 |
+
|
39 |
+
# Unit test / coverage reports
|
40 |
+
htmlcov/
|
41 |
+
.tox/
|
42 |
+
.nox/
|
43 |
+
.coverage
|
44 |
+
.coverage.*
|
45 |
+
.cache
|
46 |
+
nosetests.xml
|
47 |
+
coverage.xml
|
48 |
+
*.cover
|
49 |
+
*.py,cover
|
50 |
+
.hypothesis/
|
51 |
+
.pytest_cache/
|
52 |
+
cover/
|
53 |
+
|
54 |
+
# Translations
|
55 |
+
*.mo
|
56 |
+
*.pot
|
57 |
+
|
58 |
+
# Django stuff:
|
59 |
+
*.log
|
60 |
+
local_settings.py
|
61 |
+
db.sqlite3
|
62 |
+
db.sqlite3-journal
|
63 |
+
|
64 |
+
# Flask stuff:
|
65 |
+
instance/
|
66 |
+
.webassets-cache
|
67 |
+
|
68 |
+
# Scrapy stuff:
|
69 |
+
.scrapy
|
70 |
+
|
71 |
+
# Sphinx documentation
|
72 |
+
docs/_build/
|
73 |
+
|
74 |
+
# PyBuilder
|
75 |
+
.pybuilder/
|
76 |
+
target/
|
77 |
+
|
78 |
+
# Jupyter Notebook
|
79 |
+
.ipynb_checkpoints
|
80 |
+
|
81 |
+
# IPython
|
82 |
+
profile_default/
|
83 |
+
ipython_config.py
|
84 |
+
|
85 |
+
# pyenv
|
86 |
+
# For a library or package, you might want to ignore these files since the code is
|
87 |
+
# intended to run in multiple environments; otherwise, check them in:
|
88 |
+
# .python-version
|
89 |
+
|
90 |
+
# pipenv
|
91 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
92 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
93 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
94 |
+
# install all needed dependencies.
|
95 |
+
#Pipfile.lock
|
96 |
+
|
97 |
+
# UV
|
98 |
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
99 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
100 |
+
# commonly ignored for libraries.
|
101 |
+
#uv.lock
|
102 |
+
|
103 |
+
# poetry
|
104 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
105 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
106 |
+
# commonly ignored for libraries.
|
107 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
108 |
+
#poetry.lock
|
109 |
+
|
110 |
+
# pdm
|
111 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
112 |
+
#pdm.lock
|
113 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
114 |
+
# in version control.
|
115 |
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
116 |
+
.pdm.toml
|
117 |
+
.pdm-python
|
118 |
+
.pdm-build/
|
119 |
+
|
120 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
121 |
+
__pypackages__/
|
122 |
+
|
123 |
+
# Celery stuff
|
124 |
+
celerybeat-schedule
|
125 |
+
celerybeat.pid
|
126 |
+
|
127 |
+
# SageMath parsed files
|
128 |
+
*.sage.py
|
129 |
+
|
130 |
+
# Environments
|
131 |
+
.env
|
132 |
+
.venv
|
133 |
+
env/
|
134 |
+
venv/
|
135 |
+
ENV/
|
136 |
+
env.bak/
|
137 |
+
venv.bak/
|
138 |
+
|
139 |
+
# Spyder project settings
|
140 |
+
.spyderproject
|
141 |
+
.spyproject
|
142 |
+
|
143 |
+
# Rope project settings
|
144 |
+
.ropeproject
|
145 |
+
|
146 |
+
# mkdocs documentation
|
147 |
+
/site
|
148 |
+
|
149 |
+
# mypy
|
150 |
+
.mypy_cache/
|
151 |
+
.dmypy.json
|
152 |
+
dmypy.json
|
153 |
+
|
154 |
+
# Pyre type checker
|
155 |
+
.pyre/
|
156 |
+
|
157 |
+
# pytype static type analyzer
|
158 |
+
.pytype/
|
159 |
+
|
160 |
+
# Cython debug symbols
|
161 |
+
cython_debug/
|
162 |
+
|
163 |
+
# PyCharm
|
164 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
165 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
166 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
167 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
168 |
+
#.idea/
|
169 |
+
|
170 |
+
# Abstra
|
171 |
+
# Abstra is an AI-powered process automation framework.
|
172 |
+
# Ignore directories containing user credentials, local state, and settings.
|
173 |
+
# Learn more at https://abstra.io/docs
|
174 |
+
.abstra/
|
175 |
+
|
176 |
+
# Visual Studio Code
|
177 |
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
178 |
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
179 |
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
180 |
+
# you could uncomment the following to ignore the enitre vscode folder
|
181 |
+
# .vscode/
|
182 |
+
|
183 |
+
# Ruff stuff:
|
184 |
+
.ruff_cache/
|
185 |
+
|
186 |
+
# PyPI configuration file
|
187 |
+
.pypirc
|
188 |
+
|
189 |
+
# Cursor
|
190 |
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
191 |
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
192 |
+
# refer to https://docs.cursor.com/context/ignore-files
|
193 |
+
.cursorignore
|
194 |
+
.cursorindexingignore
|
LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
IT License
|
2 |
+
|
3 |
+
Copyright (c) 2025 Sarvesh Chaudhari
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
README.md
CHANGED
@@ -1,12 +1 @@
|
|
1 |
-
|
2 |
-
title: AppointmentApplication
|
3 |
-
emoji: 💬
|
4 |
-
colorFrom: yellow
|
5 |
-
colorTo: purple
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 5.0.1
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
---
|
11 |
-
|
12 |
-
An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
|
|
|
1 |
+
# appointmentSchedulingApp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
@@ -1,64 +1,91 @@
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
"""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
|
26 |
-
|
|
|
27 |
|
28 |
-
response = ""
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
-
|
40 |
-
|
|
|
|
|
41 |
|
|
|
|
|
|
|
42 |
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
|
|
|
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# main.py
|
2 |
+
|
3 |
import gradio as gr
|
4 |
+
from dotenv import load_dotenv
|
5 |
|
6 |
+
from database.db_handler import init_db
|
7 |
+
from langchain_logic.agent_setup import create_agent_executor
|
|
|
|
|
8 |
|
9 |
+
# --- Load Environment and Initialize ---
|
10 |
+
load_dotenv()
|
11 |
+
init_db()
|
12 |
+
agent_executor = create_agent_executor()
|
13 |
|
14 |
+
# --- Initial Bot Message ---
|
15 |
+
INITIAL_MESSAGE = """
|
16 |
+
Hey! I'm your appointment scheduling assistant. I can help you schedule, find, update, or delete appointments.
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
To schedule an appointment, I'll need the following details:
|
19 |
+
- **customer_name**: Customer's full name.
|
20 |
+
- **customer_phone**: Customer's contact phone number.
|
21 |
+
- **appointment_datetime**: The desired date and time in `YYYY-MM-DD HH:MM:SS` format.
|
22 |
+
- **service_type**: The reason for the visit (e.g., "Dental Checkup", "Haircut").
|
23 |
|
24 |
+
How can I help you today?
|
25 |
+
"""
|
26 |
|
|
|
27 |
|
28 |
+
# --- Gradio Chat Interface Logic ---
|
29 |
+
def chat_interface_fn(message, history):
|
30 |
+
"""
|
31 |
+
The function that the Gradio ChatInterface will call.
|
32 |
+
It processes the user's message, invokes the agent, and returns the response.
|
33 |
+
"""
|
34 |
+
# The 'history' from Gradio is a list of [user, bot] pairs.
|
35 |
+
# We convert it to the list-of-tuples format LangChain's agent expects.
|
36 |
+
chat_history_tuples = []
|
37 |
+
for user_msg, ai_msg in history:
|
38 |
+
# We only want to feed the actual conversational turns to the agent,
|
39 |
+
# not the initial greeting.
|
40 |
+
if ai_msg != INITIAL_MESSAGE:
|
41 |
+
chat_history_tuples.append(("human", user_msg))
|
42 |
+
chat_history_tuples.append(("ai", ai_msg))
|
43 |
|
44 |
+
response = agent_executor.invoke({
|
45 |
+
"input": message,
|
46 |
+
"chat_history": chat_history_tuples
|
47 |
+
})
|
48 |
|
49 |
+
# The ChatInterface expects a single string response from the function.
|
50 |
+
# It will automatically append the user's message and this response to the chatbot's history.
|
51 |
+
return response["output"]
|
52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
+
def greet():
|
55 |
+
"""
|
56 |
+
Function to provide the initial greeting.
|
57 |
+
It must return the data in the format the chatbot expects: a list of [user, bot] pairs.
|
58 |
+
"""
|
59 |
+
# FIX: Return the history in the correct format.
|
60 |
+
return [[None, INITIAL_MESSAGE]]
|
61 |
|
62 |
+
|
63 |
+
# --- Launch the Gradio App ---
|
64 |
if __name__ == "__main__":
|
65 |
+
print("Launching Gradio Appointment Bot...")
|
66 |
+
|
67 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Appointment Bot") as demo:
|
68 |
+
# Create a Chatbot component that will be populated on load.
|
69 |
+
chatbot = gr.Chatbot(label="Appointment Bot", elem_id="chatbot", height=600)
|
70 |
+
|
71 |
+
# Create the full ChatInterface.
|
72 |
+
chat_interface = gr.ChatInterface(
|
73 |
+
fn=chat_interface_fn,
|
74 |
+
chatbot=chatbot,
|
75 |
+
examples=[
|
76 |
+
["Find all appointments for 'John Doe'"],
|
77 |
+
["I'd like to book a 'Financial Consultation' for 2024-12-25 at 14:00:00. My name is Jane Doe and my number is 555-876-5432."],
|
78 |
+
["Please delete all 'Maintenance Check' appointments."],
|
79 |
+
["Update the phone number for Jane Doe to 555-999-0000"]
|
80 |
+
],
|
81 |
+
title="Conversational Appointment Scheduler"
|
82 |
+
)
|
83 |
+
|
84 |
+
# Use a 'load' event to populate the initial greeting using the greet function.
|
85 |
+
demo.load(
|
86 |
+
fn=greet,
|
87 |
+
inputs=None,
|
88 |
+
outputs=chatbot
|
89 |
+
)
|
90 |
+
|
91 |
+
demo.launch()
|
appointments.db
ADDED
Binary file (16.4 kB). View file
|
|
database/__init__.py
ADDED
File without changes
|
database/db_handler.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sqlite3
|
2 |
+
from typing import List, Dict, Any
|
3 |
+
|
4 |
+
DB_FILE = "appointments.db"
|
5 |
+
|
6 |
+
# ... (get_db_connection, init_db, add_appointment functions are unchanged) ...
|
7 |
+
|
8 |
+
def get_db_connection():
|
9 |
+
"""Establishes a connection to the database."""
|
10 |
+
conn = sqlite3.connect(DB_FILE)
|
11 |
+
conn.row_factory = sqlite3.Row # This allows accessing columns by name
|
12 |
+
return conn
|
13 |
+
|
14 |
+
|
15 |
+
def init_db():
|
16 |
+
"""Initializes the database and creates the appointments table."""
|
17 |
+
conn = get_db_connection()
|
18 |
+
cursor = conn.cursor()
|
19 |
+
cursor.execute("""
|
20 |
+
CREATE TABLE IF NOT EXISTS appointments (
|
21 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
22 |
+
customer_name TEXT NOT NULL,
|
23 |
+
customer_phone TEXT NOT NULL,
|
24 |
+
appointment_datetime TEXT NOT NULL UNIQUE,
|
25 |
+
service_type TEXT NOT NULL,
|
26 |
+
duration_minutes INTEGER NOT NULL DEFAULT 60,
|
27 |
+
status TEXT NOT NULL CHECK (status IN ('CONFIRMED', 'CANCELLED')) DEFAULT 'CONFIRMED',
|
28 |
+
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
29 |
+
)""")
|
30 |
+
conn.commit()
|
31 |
+
conn.close()
|
32 |
+
|
33 |
+
|
34 |
+
def add_appointment(name: str, phone: str, dt: str, service: str) -> Dict[str, Any]:
|
35 |
+
"""Adds a new appointment to the database."""
|
36 |
+
conn = get_db_connection()
|
37 |
+
cursor = conn.cursor()
|
38 |
+
try:
|
39 |
+
cursor.execute(
|
40 |
+
"INSERT INTO appointments (customer_name, customer_phone, appointment_datetime, service_type) VALUES (?, ?, ?, ?)",
|
41 |
+
(name, phone, dt, service)
|
42 |
+
)
|
43 |
+
conn.commit()
|
44 |
+
appointment_id = cursor.lastrowid
|
45 |
+
return {"status": "success", "id": appointment_id}
|
46 |
+
except sqlite3.IntegrityError:
|
47 |
+
return {"status": "error", "message": "This time slot is already booked."}
|
48 |
+
finally:
|
49 |
+
conn.close()
|
50 |
+
|
51 |
+
|
52 |
+
def search_appointments(criteria: str, value: str) -> List[Dict[str, Any]]:
|
53 |
+
"""Searches for appointments by customer_name, service_type, or date."""
|
54 |
+
conn = get_db_connection()
|
55 |
+
cursor = conn.cursor()
|
56 |
+
|
57 |
+
allowed_criteria = {
|
58 |
+
"customer_name": "customer_name",
|
59 |
+
"service_type": "service_type",
|
60 |
+
"date": "date(appointment_datetime)"
|
61 |
+
}
|
62 |
+
|
63 |
+
if criteria not in allowed_criteria:
|
64 |
+
return []
|
65 |
+
|
66 |
+
query = f"SELECT * FROM appointments WHERE {allowed_criteria[criteria]} = ? AND status = 'CONFIRMED'"
|
67 |
+
cursor.execute(query, (value,))
|
68 |
+
|
69 |
+
appointments = [dict(row) for row in cursor.fetchall()]
|
70 |
+
conn.close()
|
71 |
+
return appointments
|
72 |
+
|
73 |
+
# --- NEW FUNCTION ---
|
74 |
+
def get_all_appointments() -> List[Dict[str, Any]]:
|
75 |
+
"""Retrieves all confirmed appointments from the database."""
|
76 |
+
conn = get_db_connection()
|
77 |
+
cursor = conn.cursor()
|
78 |
+
# Order by date to make the list more useful
|
79 |
+
query = "SELECT * FROM appointments WHERE status = 'CONFIRMED' ORDER BY appointment_datetime"
|
80 |
+
cursor.execute(query)
|
81 |
+
appointments = [dict(row) for row in cursor.fetchall()]
|
82 |
+
conn.close()
|
83 |
+
return appointments
|
84 |
+
# --------------------
|
85 |
+
|
86 |
+
|
87 |
+
def delete_appointments(criteria: str, value: str) -> int:
|
88 |
+
# ... (function is unchanged) ...
|
89 |
+
conn = get_db_connection()
|
90 |
+
cursor = conn.cursor()
|
91 |
+
|
92 |
+
allowed_criteria = {
|
93 |
+
"customer_name": "customer_name",
|
94 |
+
"service_type": "service_type",
|
95 |
+
"date": "date(appointment_datetime)",
|
96 |
+
"id": "id"
|
97 |
+
}
|
98 |
+
if criteria not in allowed_criteria:
|
99 |
+
return 0
|
100 |
+
|
101 |
+
query = f"DELETE FROM appointments WHERE {allowed_criteria[criteria]} = ?"
|
102 |
+
cursor.execute(query, (value,))
|
103 |
+
deleted_count = cursor.rowcount
|
104 |
+
conn.commit()
|
105 |
+
conn.close()
|
106 |
+
return deleted_count
|
107 |
+
|
108 |
+
def update_appointment(identifier_value: str, field_to_update: str, new_value: str) -> int:
|
109 |
+
# ... (function is unchanged) ...
|
110 |
+
conn = get_db_connection()
|
111 |
+
cursor = conn.cursor()
|
112 |
+
|
113 |
+
allowed_fields = ["customer_phone", "appointment_datetime", "service_type"]
|
114 |
+
if field_to_update not in allowed_fields:
|
115 |
+
return 0
|
116 |
+
|
117 |
+
query = f"UPDATE appointments SET {field_to_update} = ? WHERE customer_name = ?"
|
118 |
+
|
119 |
+
cursor.execute(query, (new_value, identifier_value))
|
120 |
+
updated_count = cursor.rowcount
|
121 |
+
conn.commit()
|
122 |
+
conn.close()
|
123 |
+
return updated_count
|
identifier.sqlite
ADDED
File without changes
|
langchain_logic/__init__.py
ADDED
File without changes
|
langchain_logic/agent_setup.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
2 |
+
from langchain_core.prompts import ChatPromptTemplate
|
3 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
4 |
+
# Import the new tool
|
5 |
+
from langchain_logic.tools import schedule_appointment, search_for_appointments, delete_appointment_records, update_appointment_record, list_all_appointments
|
6 |
+
from datetime import datetime
|
7 |
+
|
8 |
+
def create_agent_executor():
|
9 |
+
"""Creates the LangChain agent and executor."""
|
10 |
+
# Add the new tool to the list
|
11 |
+
tools = [
|
12 |
+
schedule_appointment,
|
13 |
+
search_for_appointments,
|
14 |
+
list_all_appointments, # <-- ADDED HERE
|
15 |
+
delete_appointment_records,
|
16 |
+
update_appointment_record
|
17 |
+
]
|
18 |
+
|
19 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash-lite-preview-06-17", temperature=0)
|
20 |
+
|
21 |
+
# You can optionally update the prompt to mention the new capability
|
22 |
+
prompt = ChatPromptTemplate.from_messages([
|
23 |
+
("system", """You are an advanced, helpful appointment scheduling assistant.
|
24 |
+
|
25 |
+
Your tasks are to schedule, search, update, and delete appointments using the available tools.
|
26 |
+
|
27 |
+
**Core Instructions:**
|
28 |
+
1. **Be Conversational:** Always be polite and helpful.
|
29 |
+
2. **Gather Information:** If you don't have enough information for a tool, ask the user for it.
|
30 |
+
3. **Search:** You can search for appointments by `customer_name`, `service_type` (which the user might call 'title'), or a specific `date`. If the user asks for *all* appointments, use the `list_all_appointments` tool.
|
31 |
+
4. **Update:** To update an appointment, you must know the customer's name and what specific information to change (e.g., 'update the phone for John Doe to 555-1111').
|
32 |
+
5. **CRITICAL-SAFETY-RULE for Deletion:** Deleting by name, service, or date can remove MULTIPLE appointments. Before using the `delete_appointment_records` tool, you MUST first search for the appointments to see how many will be affected. Then, you MUST ask the user for explicit confirmation. For example: "I found 3 appointments for 'Dental Checkup'. Are you sure you want to delete all of them? Please reply with 'yes' to confirm or 'no' to cancel." Only proceed with deletion if they confirm with 'yes'.
|
33 |
+
6. **Current Date:** Today's date is {today}.
|
34 |
+
|
35 |
+
Begin the conversation by introducing yourself and what you can do.
|
36 |
+
""".format(today=datetime.now().strftime('%Y-%m-%d'))),
|
37 |
+
("placeholder", "{chat_history}"),
|
38 |
+
("human", "{input}"),
|
39 |
+
("placeholder", "{agent_scratchpad}"),
|
40 |
+
])
|
41 |
+
|
42 |
+
agent = create_tool_calling_agent(llm, tools, prompt)
|
43 |
+
agent_executor = AgentExecutor(
|
44 |
+
agent=agent,
|
45 |
+
tools=tools,
|
46 |
+
verbose=True, # For debugging
|
47 |
+
handle_parsing_errors=True
|
48 |
+
)
|
49 |
+
return agent_executor
|
langchain_logic/tools.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain_core.tools import tool
|
2 |
+
from pydantic.v1 import BaseModel, Field
|
3 |
+
from datetime import datetime
|
4 |
+
from database.db_handler import (
|
5 |
+
add_appointment,
|
6 |
+
search_appointments,
|
7 |
+
delete_appointments,
|
8 |
+
update_appointment,
|
9 |
+
get_all_appointments
|
10 |
+
)
|
11 |
+
|
12 |
+
# --- Pydantic Models for Tool Inputs ---
|
13 |
+
# (These are unchanged)
|
14 |
+
class ScheduleAppointmentInput(BaseModel):
|
15 |
+
customer_name: str = Field(description="The full name of the customer.")
|
16 |
+
customer_phone: str = Field(description="The contact phone number of the customer.")
|
17 |
+
appointment_datetime: str = Field(description="The date and time in 'YYYY-MM-DD HH:MM:SS' format.")
|
18 |
+
service_type: str = Field(description="The type of service, e.g., 'Dental Checkup', 'Haircut'.")
|
19 |
+
|
20 |
+
|
21 |
+
class SearchAppointmentInput(BaseModel):
|
22 |
+
criteria: str = Field(description="The field to search by: 'customer_name', 'service_type', or 'date'.")
|
23 |
+
value: str = Field(description="The value to search for. For date, use 'YYYY-MM-DD' format.")
|
24 |
+
|
25 |
+
|
26 |
+
class DeleteAppointmentInput(BaseModel):
|
27 |
+
criteria: str = Field(
|
28 |
+
description="The field to identify appointments to delete: 'customer_name', 'service_type', or 'date'.")
|
29 |
+
value: str = Field(description="The value to identify the appointments by.")
|
30 |
+
|
31 |
+
|
32 |
+
class UpdateAppointmentInput(BaseModel):
|
33 |
+
identifier_value: str = Field(description="The name of the customer whose appointment needs updating.")
|
34 |
+
field_to_update: str = Field(
|
35 |
+
description="The specific field to change, e.g., 'customer_phone', 'appointment_datetime'.")
|
36 |
+
new_value: str = Field(description="The new value for the specified field.")
|
37 |
+
|
38 |
+
|
39 |
+
# --- Tool Definitions ---
|
40 |
+
|
41 |
+
@tool(args_schema=ScheduleAppointmentInput)
|
42 |
+
def schedule_appointment(customer_name: str, customer_phone: str, appointment_datetime: str, service_type: str) -> str:
|
43 |
+
"""Schedules a new appointment.""" # <-- ADDED THIS DOCSTRING BACK
|
44 |
+
try:
|
45 |
+
datetime.strptime(appointment_datetime, '%Y-%m-%d %H:%M:%S')
|
46 |
+
except ValueError:
|
47 |
+
return "Error: Invalid datetime format. Please use 'YYYY-MM-DD HH:MM:SS'."
|
48 |
+
|
49 |
+
result = add_appointment(customer_name, customer_phone, appointment_datetime, service_type)
|
50 |
+
if result["status"] == "success":
|
51 |
+
return f"Success! Appointment for {customer_name} is scheduled. The appointment ID is {result['id']}."
|
52 |
+
else:
|
53 |
+
return f"Error: {result['message']}"
|
54 |
+
|
55 |
+
|
56 |
+
@tool(args_schema=SearchAppointmentInput)
|
57 |
+
def search_for_appointments(criteria: str, value: str) -> str:
|
58 |
+
"""Searches for existing appointments based on name, service type, or date.""" # <-- ADDED THIS DOCSTRING BACK
|
59 |
+
results = search_appointments(criteria, value)
|
60 |
+
if not results:
|
61 |
+
return f"No confirmed appointments found for {criteria} = {value}."
|
62 |
+
|
63 |
+
details = "\n".join([
|
64 |
+
f"- ID: {r['id']}, Name: {r['customer_name']}, DateTime: {r['appointment_datetime']}, Service: {r['service_type']}"
|
65 |
+
for r in results])
|
66 |
+
return f"Found the following appointments:\n{details}"
|
67 |
+
|
68 |
+
|
69 |
+
@tool
|
70 |
+
def list_all_appointments() -> str:
|
71 |
+
"""Lists all confirmed appointments currently in the system. Use this when the user asks to see all appointments without specifying any criteria."""
|
72 |
+
results = get_all_appointments()
|
73 |
+
if not results:
|
74 |
+
return "There are currently no confirmed appointments in the system."
|
75 |
+
|
76 |
+
details = "\n".join([
|
77 |
+
f"- ID: {r['id']}, Name: {r['customer_name']}, DateTime: {r['appointment_datetime']}, Service: {r['service_type']}"
|
78 |
+
for r in results
|
79 |
+
])
|
80 |
+
return f"Here are all the confirmed appointments:\n{details}"
|
81 |
+
|
82 |
+
|
83 |
+
@tool(args_schema=DeleteAppointmentInput)
|
84 |
+
def delete_appointment_records(criteria: str, value: str) -> str:
|
85 |
+
"""Deletes appointment records by name, service type, or date.""" # <-- ADDED THIS DOCSTRING BACK
|
86 |
+
count = delete_appointments(criteria, value)
|
87 |
+
if count == 0:
|
88 |
+
return f"No appointments found to delete for {criteria} = {value}."
|
89 |
+
else:
|
90 |
+
return f"Successfully deleted {count} appointment(s)."
|
91 |
+
|
92 |
+
|
93 |
+
@tool(args_schema=UpdateAppointmentInput)
|
94 |
+
def update_appointment_record(identifier_value: str, field_to_update: str, new_value: str) -> str:
|
95 |
+
"""Updates an appointment's information, like phone number or time.""" # <-- ADDED THIS DOCSTRING BACK
|
96 |
+
count = update_appointment(identifier_value, field_to_update, new_value)
|
97 |
+
if count == 0:
|
98 |
+
return f"Error: Could not find or update an appointment for customer '{identifier_value}'."
|
99 |
+
else:
|
100 |
+
return f"Successfully updated {count} appointment(s) for {identifier_value}."
|
requirements.txt
CHANGED
@@ -1 +1,6 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# requirements.txt
|
2 |
+
langchain
|
3 |
+
langchain-google-genai
|
4 |
+
google-generativeai
|
5 |
+
gradio
|
6 |
+
python-dotenv
|