-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_app.py
More file actions
135 lines (112 loc) · 4.94 KB
/
Copy pathfunction_app.py
File metadata and controls
135 lines (112 loc) · 4.94 KB
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
import azure.functions as func
import datetime
import json
import logging
import os
import pyodbc
import azure.functions as func
from collections import defaultdict
import openai
app = func.FunctionApp()
@app.route(route="HttpClockTrigger", auth_level=func.AuthLevel.ANONYMOUS)
def HttpClockTrigger(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
openai.api_key = os.getenv("OPENAI_API_KEY")
# Step 1: Get database connection
server = os.getenv("SQL_SERVER")
database = os.getenv("SQL_DATABASE")
username = os.getenv("SQL_USERNAME")
password = os.getenv("SQL_PASSWORD")
driver = '{ODBC Driver 18 for SQL Server}' # Or 'ODBC Driver 17 for SQL Server'
try:
connection_string = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;'
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
#cursor.execute("SELECT TOP 5 * FROM Employees")
#rows = cursor.fetchall()
cursor.execute("""
SELECT
e.EmployeeID, e.Name, e.Department, e.Role, e.Email,
p.ProjectID, p.ProjectName, p.Status AS ProjectStatus,
t.TaskID, t.Title AS TaskTitle, t.Status AS TaskStatus, t.DueDate, t.Priority,
i.IssueID, i.Title AS IssueTitle, i.Severity
FROM Employees e
LEFT JOIN Tasks t ON e.EmployeeID = t.AssignedTo
LEFT JOIN Projects p ON t.ProjectID = p.ProjectID
LEFT JOIN Issues i ON t.TaskID = i.TaskID
""")
# Step 2: Build employee documents
employees = defaultdict(lambda: {
"projects": [],
"tasks": [],
"issues": [],
"full_text": ""
})
for row in cursor.fetchall():
emp = employees[row.EmployeeID]
emp["id"] = row.EmployeeID
emp["name"] = row.Name
emp["department"] = row.Department
emp["role"] = row.Role
emp["email"] = row.Email
# Avoid duplicates
if row.ProjectID and not any(p["project_id"] == row.ProjectID for p in emp["projects"]):
emp["projects"].append({
"project_id": row.ProjectID,
"name": row.ProjectName,
"status": row.ProjectStatus
})
if row.TaskID and not any(t["task_id"] == row.TaskID for t in emp["tasks"]):
emp["tasks"].append({
"task_id": row.TaskID,
"title": row.TaskTitle,
"status": row.TaskStatus,
"priority": row.Priority,
"due_date": str(row.DueDate) if row.DueDate else None
})
if row.IssueID and not any(i["issue_id"] == row.IssueID for i in emp["issues"]):
emp["issues"].append({
"issue_id": row.IssueID,
"title": row.IssueTitle,
"severity": row.Severity
})
# Build full_text
emp["full_text"] += f"{row.Name} works in {row.Department} as {row.Role}. "
if row.ProjectName:
emp["full_text"] += f"Working on project {row.ProjectName}. "
if row.TaskTitle:
emp["full_text"] += f"Task assigned: {row.TaskTitle}. "
if row.IssueTitle:
emp["full_text"] += f"Issue reported: {row.IssueTitle}. "
#Step 3: Generate embeddings
for emp in employees.values():
response = openai.Embedding.create(
input=emp["full_text"],
model="text-embedding-ada-002"
)
emp["embedding"] = response["data"][0]["embedding"]
cosmos_client = CosmosClient(os.getenv("COSMOS_ENDPOINT"), credential=os.getenv("COSMOS_KEY"))
db = cosmos_client.get_database_client("genai-rag-db")
container = db.get_container_client("documents")
for emp in employees.values():
container.upsert_item(emp)
return func.HttpResponse(f"Query result:\n{emp}", status_code=200)
#output = "\n".join([str(row) for row in rows])
#return func.HttpResponse(f"Query result:\n{output}", status_code=200)
except Exception as e:
return func.HttpResponse(f"Database connection failed:\n{str(e)}", status_code=500)
#name = req.params.get('name')
#if not name:
# try:
# req_body = req.get_json()
# except ValueError:
# pass
# else:
# name = req_body.get('name')
#if name:
# return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
#else:
# return func.HttpResponse(
# "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
# status_code=200
# )