Skip to content

Commit c115864

Browse files
Merge pull request #175 from microsoft/tech-connect-sql
fix: Remove custom conversation cache from stream_openai_text_workshop
2 parents e4b544b + 1cc78e4 commit c115864

File tree

7 files changed

+50
-55
lines changed

7 files changed

+50
-55
lines changed

azure.yaml

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,13 @@ hooks:
1616
postprovision:
1717
windows:
1818
run: |
19-
Write-Host "Web app URL: "
20-
Write-Host "$env:WEB_APP_URL" -ForegroundColor Cyan
21-
2219
$isWorkshop = $env:IS_WORKSHOP
20+
$deployApp = $env:AZURE_ENV_DEPLOY_APP
21+
22+
if (-not ($isWorkshop -eq "true" -and $deployApp -ne "true")) {
23+
Write-Host "Web app URL: "
24+
Write-Host "$env:WEB_APP_URL" -ForegroundColor Cyan
25+
}
2326
if ($isWorkshop -eq "true") {
2427
Write-Host "`n=== Run each command one at a time, waiting for completion before proceeding ===" -ForegroundColor Yellow
2528
Write-Host "`n1. Setup Python environment:"
@@ -28,7 +31,12 @@ hooks:
2831
Write-Host " pip install uv && uv pip install -r scripts/requirements.txt" -ForegroundColor Cyan
2932
3033
Write-Host "`n2. Build solution (data processing and agent creation):"
31-
Write-Host " python scripts/00_build_solution.py --from 02" -ForegroundColor Cyan
34+
$azureEnvOnly = $env:AZURE_ENV_ONLY
35+
if ($azureEnvOnly -eq "true") {
36+
Write-Host " python scripts/00_build_solution.py --from 04" -ForegroundColor Cyan
37+
} else {
38+
Write-Host " python scripts/00_build_solution.py --from 02" -ForegroundColor Cyan
39+
}
3240
3341
Write-Host "`nFor full instructions, see: https://microsoft.github.io/agentic-applications-for-unified-data-foundation-solution-accelerator/01-deploy/03-configure/" -ForegroundColor Gray
3442
} else {
@@ -45,9 +53,11 @@ hooks:
4553
interactive: true
4654
posix:
4755
run: |
48-
echo "Web app URL: "
49-
echo $WEB_APP_URL
50-
echo ""
56+
if [ "$IS_WORKSHOP" != "true" ] || [ "$AZURE_ENV_DEPLOY_APP" = "true" ]; then
57+
echo "Web app URL: "
58+
echo $WEB_APP_URL
59+
echo ""
60+
fi
5161
5262
if [ "$IS_WORKSHOP" = "true" ]; then
5363
echo ""
@@ -60,7 +70,11 @@ hooks:
6070
6171
echo ""
6272
echo "2. Build solution (data processing and agent creation):"
63-
echo " python scripts/00_build_solution.py --from 02"
73+
if [ "$AZURE_ENV_ONLY" = "true" ]; then
74+
echo " python scripts/00_build_solution.py --from 04"
75+
else
76+
echo " python scripts/00_build_solution.py --from 02"
77+
fi
6478
6579
echo ""
6680
echo "For full instructions, see: https://microsoft.github.io/agentic-applications-for-unified-data-foundation-solution-accelerator/01-deploy/03-configure/"

scripts/01_generate_data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,7 @@ def create_pdf(title, sections, filename):
587587
python scripts/04_generate_agent_prompt.py
588588
python scripts/06_upload_to_search.py
589589
python scripts/07_create_foundry_agent.py
590-
python scripts/08_test_foundry_agent.py
590+
python scripts/08_test_agent.py
591591
""")
592592

593593
# ============================================================================

src/api/python/chat.py

Lines changed: 16 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,7 @@ async def stream_openai_text(conversation_id: str, query: str) -> StreamingRespo
235235
logger.info("No response received from OpenAI.")
236236
yield "I cannot answer this question with the current data. Please rephrase or add more details."
237237

238+
238239
async def stream_openai_text_workshop(conversation_id: str, query: str) -> StreamingResponse:
239240
"""
240241
Get a streaming text response from OpenAI with workshop mode using responses.create().
@@ -256,55 +257,45 @@ async def stream_openai_text_workshop(conversation_id: str, query: str) -> Strea
256257
credential=credential
257258
) as project_client:
258259

259-
cache = get_thread_cache()
260-
conv_id = cache.get(conversation_id, None)
261-
262260
# Get database connection based on AZURE_ENV_ONLY flag
263261
from history_sql import SqlQueryTool, get_azure_sql_connection, get_fabric_db_connection
264-
262+
265263
if AZURE_ENV_ONLY:
266264
logger.info("Workshop mode: Using Azure SQL Database")
267265
db_connection = await get_azure_sql_connection()
268266
else:
269267
logger.info("Workshop mode: Using Fabric Lakehouse SQL")
270268
db_connection = await get_fabric_db_connection()
271-
269+
272270
if not db_connection:
273271
logger.error("Failed to establish database connection")
274272
raise Exception("Database connection failed")
275-
273+
276274
custom_tool = SqlQueryTool(pyodbc_conn=db_connection)
277275

278276
openai_client = project_client.get_openai_client()
279-
280-
# Create or retrieve conversation
281-
if not conv_id:
282-
conv = await openai_client.conversations.create()
283-
conv_id = conv.id
284-
cache[conversation_id] = conv_id
285277

286278
# Initial request to the agent
287279
response = await openai_client.responses.create(
288-
conversation=conv_id,
289280
input=query,
290281
extra_body={"agent": {"name": os.getenv("AGENT_NAME_CHAT"), "type": "agent_reference"}}
291282
)
292-
283+
293284
# Process response - handle function calls and search
294285
max_iterations = 10
295286
iteration = 0
296-
287+
297288
while iteration < max_iterations:
298289
iteration += 1
299-
290+
300291
# Check for function calls and tool uses in output
301292
function_calls = []
302293
text_output = ""
303294
search_results = []
304-
295+
305296
for item in response.output:
306297
item_type = getattr(item, 'type', None)
307-
298+
308299
if item_type == 'function_call':
309300
function_calls.append(item)
310301
elif item_type == 'message':
@@ -332,22 +323,22 @@ async def stream_openai_text_workshop(conversation_id: str, query: str) -> Strea
332323
# Handle search tool output (result)
333324
elif item_type == 'azure_ai_search_call_output':
334325
logger.info("AI Search completed")
335-
326+
336327
# If no function calls, we're done
337328
if not function_calls:
338329
if text_output:
339330
complete_response += text_output
340331
yield text_output
341332
break
342-
333+
343334
# Handle function calls
344335
tool_outputs = []
345336
for fc in function_calls:
346337
func_name = fc.name
347338
func_args = json.loads(fc.arguments)
348-
339+
349340
logger.info("Calling function: %s", func_name)
350-
341+
351342
if func_name == "execute_sql":
352343
sql_query = func_args.get("sql_query", "")
353344
logger.info("Executing SQL query: %s", sql_query[:100])
@@ -363,13 +354,13 @@ async def stream_openai_text_workshop(conversation_id: str, query: str) -> Strea
363354
else:
364355
result_str = f"Unknown function: {func_name}"
365356
logger.warning("Unknown function called: %s", func_name)
366-
357+
367358
tool_outputs.append({
368359
"type": "function_call_output",
369360
"call_id": fc.call_id,
370361
"output": result_str
371362
})
372-
363+
373364
# Submit tool outputs and get next response
374365
# Note: Don't include 'conversation' when using 'previous_response_id'
375366
response = await openai_client.responses.create(
@@ -379,19 +370,14 @@ async def stream_openai_text_workshop(conversation_id: str, query: str) -> Strea
379370
"previous_response_id": response.id
380371
}
381372
)
382-
373+
383374
if iteration >= max_iterations:
384375
logger.warning("Max iterations reached in workshop mode")
385376
yield "\n\n(Response processing reached maximum iterations)"
386377

387378
except Exception as e:
388379
complete_response = str(e)
389380
logger.error("Error in stream_openai_text_workshop: %s", e)
390-
cache = get_thread_cache()
391-
conv_id = cache.pop(conversation_id, None)
392-
if conv_id is not None:
393-
corrupt_key = f"{conversation_id}_corrupt_{random.randint(1000, 9999)}"
394-
cache[corrupt_key] = conv_id
395381
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Error streaming OpenAI text") from e
396382

397383
finally:

src/api/python/history.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -650,7 +650,7 @@ async def get_conversation_messages(user_id: str, conversation_id: str):
650650
else:
651651
message_content = content
652652
citations = ""
653-
653+
654654
messages.append({
655655
"id": msg["id"],
656656
"role": msg["role"],
@@ -862,7 +862,7 @@ async def delete_conversation_route(request: Request, id: str = Query(...)):
862862
authenticated_user = get_authenticated_user_details(
863863
request_headers=request.headers)
864864
user_id = authenticated_user["user_principal_id"]
865-
865+
866866
conversation_id = id
867867
if not conversation_id:
868868
track_event_if_configured("DeleteConversationValidationError", {

src/api/python/history_sql.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def track_event_if_configured(event_name: str, event_data: dict):
7979
async def get_azure_sql_connection():
8080
"""
8181
Get a connection to Azure SQL Server using DefaultAzureCredential.
82-
82+
8383
Returns:
8484
Connection: Database connection object for Azure SQL.
8585
"""
@@ -88,19 +88,19 @@ async def get_azure_sql_connection():
8888
driver18 = "ODBC Driver 18 for SQL Server"
8989
driver17 = "ODBC Driver 17 for SQL Server"
9090
api_uid = os.getenv("API_UID", "")
91-
91+
9292
credential = await get_azure_credential_async(client_id=api_uid)
9393
token = await credential.get_token("https://database.windows.net/.default")
9494
await credential.close()
95-
95+
9696
token_bytes = token.token.encode("utf-16-LE")
9797
token_struct = struct.pack(
9898
f"<I{len(token_bytes)}s",
9999
len(token_bytes),
100100
token_bytes
101101
)
102102
SQL_COPT_SS_ACCESS_TOKEN = 1256
103-
103+
104104
try:
105105
connection_string = f"DRIVER={{{driver18}}};SERVER={sql_server};DATABASE={sql_database};"
106106
conn = pyodbc.connect(connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct})
@@ -176,15 +176,15 @@ async def get_fabric_db_connection():
176176
async def get_db_connection():
177177
"""
178178
Get a database connection based on deployment mode.
179-
179+
180180
When IS_WORKSHOP is true, uses Azure SQL Server.
181181
When IS_WORKSHOP is false or not set, uses Fabric SQL.
182182
183183
Returns:
184184
Connection: Database connection object, or None if connection fails.
185185
"""
186186
is_workshop = os.getenv("IS_WORKSHOP", "false").lower() == "true"
187-
187+
188188
if is_workshop:
189189
logging.info("Workshop deployment mode: Using Azure SQL Server")
190190
return await get_azure_sql_connection()

workshop/docs/01-deploy/04-run-scenario.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ This uses the `data/default` folder and runs all setup steps:
3939
------------------------------------------------------------
4040
[OK] Pipeline completed successfully!
4141
42-
Next: python scripts/08_test_foundry_agent.py
42+
Next: python scripts/08_test_agent.py
4343
4444
```
4545

@@ -57,7 +57,7 @@ Support group by in GQL.
5757
## Test the Agent
5858

5959
```bash
60-
python scripts/08_test_foundry_agent.py
60+
python scripts/08_test_agent.py
6161
```
6262

6363

workshop/docs/02-customize/03-demo.md

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,7 @@
55
After generation completes, test the agent:
66

77
```bash
8-
python scripts/08_test_foundry_agent.py
9-
```
10-
11-
No Fabric license? Run the following command:
12-
```bash
13-
python scripts/08_test_foundry_agent.py --foundry-only
8+
python scripts/08_test_agent.py
149
```
1510

1611
## Use the Generated Sample Questions

0 commit comments

Comments
 (0)