|
1 |
| -from flask import Flask, request, jsonify |
| 1 | +from flask import Flask, request, jsonify, Response, stream_with_context |
2 | 2 | from pydantic import BaseModel, ValidationError
|
3 | 3 | from typing import List
|
4 |
| -from copilot import UserMessage, AssistantMessage, get_response |
| 4 | +from copilot import UserMessage, AssistantMessage, get_response, openai_client |
| 5 | +from streaming import get_streaming_response |
5 | 6 | from lib import AgentContext, PromptContext, ToolContext, ChatContext
|
6 | 7 | import os
|
7 | 8 | from functools import wraps
|
8 |
| -from copilot import copilot_instructions, copilot_instructions_edit_agent |
| 9 | +from copilot import copilot_instructions_edit_agent |
| 10 | +import json |
9 | 11 |
|
10 | 12 | class ApiRequest(BaseModel):
|
11 | 13 | messages: List[UserMessage | AssistantMessage]
|
@@ -46,24 +48,37 @@ def decorated(*args, **kwargs):
|
46 | 48 | def health():
|
47 | 49 | return jsonify({'status': 'ok'})
|
48 | 50 |
|
49 |
| -@app.route('/chat', methods=['POST']) |
| 51 | +@app.route('/chat_stream', methods=['POST']) |
50 | 52 | @require_api_key
|
51 |
| -def chat(): |
| 53 | +def chat_stream(): |
52 | 54 | try:
|
53 | 55 | request_data = ApiRequest(**request.json)
|
54 |
| - print(f"received /chat request: {request_data}") |
| 56 | + print(f"received /chat_stream request: {request_data}") |
55 | 57 | validate_request(request_data)
|
56 | 58 |
|
57 |
| - response = get_response( |
58 |
| - messages=request_data.messages, |
59 |
| - workflow_schema=request_data.workflow_schema, |
60 |
| - current_workflow_config=request_data.current_workflow_config, |
61 |
| - context=request_data.context, |
62 |
| - copilot_instructions=copilot_instructions |
| 59 | + def generate(): |
| 60 | + stream = get_streaming_response( |
| 61 | + messages=request_data.messages, |
| 62 | + workflow_schema=request_data.workflow_schema, |
| 63 | + current_workflow_config=request_data.current_workflow_config, |
| 64 | + context=request_data.context |
| 65 | + ) |
| 66 | + |
| 67 | + for chunk in stream: |
| 68 | + if chunk.choices[0].delta.content: |
| 69 | + content = chunk.choices[0].delta.content |
| 70 | + yield f"data: {json.dumps({'content': content})}\n\n" |
| 71 | + |
| 72 | + yield "event: done\ndata: {}\n\n" |
| 73 | + |
| 74 | + return Response( |
| 75 | + stream_with_context(generate()), |
| 76 | + mimetype='text/event-stream', |
| 77 | + headers={ |
| 78 | + 'Cache-Control': 'no-cache', |
| 79 | + 'X-Accel-Buffering': 'no' |
| 80 | + } |
63 | 81 | )
|
64 |
| - api_response = ApiResponse(response=response).model_dump() |
65 |
| - print(f"sending /chat response: {api_response}") |
66 |
| - return jsonify(api_response) |
67 | 82 |
|
68 | 83 | except ValidationError as ve:
|
69 | 84 | print(ve)
|
|
0 commit comments