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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import traceback
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
from langchain.chat_models import init_chat_model
|
| 8 |
+
from langchain.agents import create_agent
|
| 9 |
+
from langchain_community.utilities import SQLDatabase
|
| 10 |
+
from langchain_community.agent_toolkits import SQLDatabaseToolkit
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
DB_PATH = Path("database_") / "zain_customer_360_ai_demo.db"
|
| 14 |
+
MODEL_NAME = "gpt-4.1-mini"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
SYSTEM_PROMPT = """
|
| 18 |
+
You are a telecom business intelligence SQL agent for Zain Jordan.
|
| 19 |
+
|
| 20 |
+
You are connected to a SQLite Customer 360 database.
|
| 21 |
+
|
| 22 |
+
Rules:
|
| 23 |
+
- Use SELECT queries only.
|
| 24 |
+
- Never modify the database.
|
| 25 |
+
- Never use INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, CREATE, REPLACE, ATTACH, DETACH, or VACUUM.
|
| 26 |
+
- Inspect the database schema before writing SQL.
|
| 27 |
+
- Limit results to 10 rows unless the user asks otherwise.
|
| 28 |
+
- Use only relevant columns.
|
| 29 |
+
- Do not guess facts that are not in the database.
|
| 30 |
+
- Explain the result in simple business language.
|
| 31 |
+
|
| 32 |
+
Useful context:
|
| 33 |
+
- Churn analysis usually uses customers and customer_churn_scores.
|
| 34 |
+
- Revenue/value analysis usually uses customer_value_segments, invoices, payments, or transactions.
|
| 35 |
+
- Complaint analysis usually uses complaints and support_interactions.
|
| 36 |
+
- Campaign analysis usually uses campaigns and customer_campaign_responses.
|
| 37 |
+
- Network analysis usually uses network_towers and network_events.
|
| 38 |
+
|
| 39 |
+
Final answer format:
|
| 40 |
+
1. Direct Answer
|
| 41 |
+
2. Key Numbers
|
| 42 |
+
3. Business Interpretation
|
| 43 |
+
4. Recommended Next Action
|
| 44 |
+
""".strip()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
sql_agent = None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_sql_agent():
|
| 51 |
+
global sql_agent
|
| 52 |
+
|
| 53 |
+
if sql_agent is not None:
|
| 54 |
+
return sql_agent
|
| 55 |
+
|
| 56 |
+
api_key = os.environ.get("OPENAI_API_KEY")
|
| 57 |
+
|
| 58 |
+
if not api_key:
|
| 59 |
+
raise ValueError(
|
| 60 |
+
"OPENAI_API_KEY is missing. Add it in Hugging Face Space Settings → Variables and secrets → Secrets."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
if not DB_PATH.exists():
|
| 64 |
+
raise FileNotFoundError(
|
| 65 |
+
f"Database not found at: {DB_PATH}\n\n"
|
| 66 |
+
"Please create a folder named database_ and upload zain_customer_360_ai_demo.db inside it."
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
db_uri = f"sqlite:///{DB_PATH.resolve()}"
|
| 70 |
+
db = SQLDatabase.from_uri(db_uri)
|
| 71 |
+
|
| 72 |
+
llm = init_chat_model(
|
| 73 |
+
MODEL_NAME,
|
| 74 |
+
model_provider="openai"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
toolkit = SQLDatabaseToolkit(
|
| 78 |
+
db=db,
|
| 79 |
+
llm=llm
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
tools = toolkit.get_tools()
|
| 83 |
+
|
| 84 |
+
sql_agent = create_agent(
|
| 85 |
+
model=llm,
|
| 86 |
+
tools=tools,
|
| 87 |
+
system_prompt=SYSTEM_PROMPT
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
return sql_agent
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def run_sql_agent(question):
|
| 94 |
+
try:
|
| 95 |
+
if not question or not question.strip():
|
| 96 |
+
return "Please enter a business question."
|
| 97 |
+
|
| 98 |
+
agent = get_sql_agent()
|
| 99 |
+
|
| 100 |
+
result = agent.invoke({
|
| 101 |
+
"messages": [
|
| 102 |
+
{
|
| 103 |
+
"role": "user",
|
| 104 |
+
"content": question
|
| 105 |
+
}
|
| 106 |
+
]
|
| 107 |
+
})
|
| 108 |
+
|
| 109 |
+
final_message = result["messages"][-1]
|
| 110 |
+
|
| 111 |
+
if hasattr(final_message, "content"):
|
| 112 |
+
return final_message.content
|
| 113 |
+
|
| 114 |
+
return str(final_message)
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
return f"""
|
| 118 |
+
### Error
|
| 119 |
+
|
| 120 |
+
{str(e)}
|
| 121 |
+
|
| 122 |
+
### Traceback
|
| 123 |
+
|
| 124 |
+
```text
|
| 125 |
+
{traceback.format_exc()}
|
| 126 |
+
```
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
with gr.Blocks(title="Zain Jordan SQL Agent") as demo:
|
| 131 |
+
|
| 132 |
+
gr.Markdown("# Zain Jordan Customer 360 SQL Agent")
|
| 133 |
+
|
| 134 |
+
gr.Markdown("""
|
| 135 |
+
Ask business questions from the Zain Jordan Customer 360 SQLite database.
|
| 136 |
+
|
| 137 |
+
This app uses:
|
| 138 |
+
|
| 139 |
+
- SQLite database
|
| 140 |
+
- LangChain `SQLDatabase`
|
| 141 |
+
- LangChain `SQLDatabaseToolkit`
|
| 142 |
+
- OpenAI `gpt-4.1-mini`
|
| 143 |
+
- Gradio interface
|
| 144 |
+
|
| 145 |
+
Expected database location:
|
| 146 |
+
|
| 147 |
+
```text
|
| 148 |
+
database_/zain_customer_360_ai_demo.db
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Example questions:
|
| 152 |
+
|
| 153 |
+
- Which cities have the most high-risk churn customers?
|
| 154 |
+
- Which customer value segments have the highest average ARPU?
|
| 155 |
+
- What are the top complaint categories?
|
| 156 |
+
- Which campaigns had the highest conversion rate?
|
| 157 |
+
""")
|
| 158 |
+
|
| 159 |
+
question = gr.Textbox(
|
| 160 |
+
label="Ask a business question",
|
| 161 |
+
lines=4,
|
| 162 |
+
value="Which cities have the most high-risk churn customers? Show the top 10 cities.",
|
| 163 |
+
placeholder="Ask a question about churn, revenue, complaints, campaigns, customers, or network events."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
run_button = gr.Button("Run SQL Agent", variant="primary")
|
| 167 |
+
|
| 168 |
+
answer = gr.Markdown(label="Answer")
|
| 169 |
+
|
| 170 |
+
run_button.click(
|
| 171 |
+
fn=run_sql_agent,
|
| 172 |
+
inputs=question,
|
| 173 |
+
outputs=answer
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
pandas
|
| 3 |
+
sqlalchemy
|
| 4 |
+
langchain
|
| 5 |
+
langchain-openai
|
| 6 |
+
langchain-community
|
| 7 |
+
openai
|