Hansimov commited on
Commit
c32808f
1 Parent(s): 60bb91e

:bulb: [Test] Websocket API of create conversation

Browse files
apis/chat_api.py CHANGED
@@ -1,6 +1,7 @@
1
  import uvicorn
2
 
3
- from fastapi import FastAPI
 
4
  from pydantic import BaseModel, Field
5
  from conversations import ConversationSession
6
 
@@ -43,11 +44,26 @@ class ChatAPIApp:
43
  ]
44
  return self.available_models
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  def setup_routes(self):
47
- self.app.get(
48
- "/models",
49
- summary="Get available models",
50
- )(self.get_available_models)
51
 
52
 
53
  app = ChatAPIApp().app
 
1
  import uvicorn
2
 
3
+ from fastapi import FastAPI, APIRouter, WebSocket, WebSocketDisconnect
4
+ from fastapi.routing import APIRoute
5
  from pydantic import BaseModel, Field
6
  from conversations import ConversationSession
7
 
 
44
  ]
45
  return self.available_models
46
 
47
+ async def create_conversation_session(
48
+ self, websocket: WebSocket, conversation_style="precise"
49
+ ):
50
+ await websocket.accept()
51
+ conversation_session = ConversationSession(conversation_style)
52
+ conversation_session.open()
53
+ while True:
54
+ try:
55
+ data = await websocket.receive_text()
56
+ response = await conversation_session.chat(data)
57
+ await websocket.send_text(response)
58
+ except Exception as e:
59
+ print(e)
60
+ break
61
+
62
  def setup_routes(self):
63
+ self.router = APIRouter()
64
+ self.router.add_api_route("/models", self.get_available_models)
65
+ self.router.add_websocket_route("/create", self.create_conversation_session)
66
+ self.app.include_router(self.router)
67
 
68
 
69
  app = ChatAPIApp().app
conversations/conversation_session.py CHANGED
@@ -34,11 +34,11 @@ class ConversationSession:
34
  def close(self):
35
  self.event_loop.close()
36
 
37
- def chat(self, prompt):
38
  logger.success(f"\n[User]: ", end="")
39
  logger.mesg(f"{prompt}")
40
  logger.success(f"[Bing]:")
41
- self.event_loop.run_until_complete(self.connector.stream_chat(prompt=prompt))
42
 
43
 
44
  if __name__ == "__main__":
 
34
  def close(self):
35
  self.event_loop.close()
36
 
37
+ async def chat(self, prompt):
38
  logger.success(f"\n[User]: ", end="")
39
  logger.mesg(f"{prompt}")
40
  logger.success(f"[Bing]:")
41
+ return await self.connector.stream_chat(prompt=prompt)
42
 
43
 
44
  if __name__ == "__main__":
examples/chat_with_websocket.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import websockets
3
+
4
+
5
+ async def chat_with_websocket(url, message):
6
+ async with websockets.connect(url) as websocket:
7
+ await websocket.send(message)
8
+ response = await websocket.recv()
9
+ print(response)
10
+
11
+
12
+ server = "localhost"
13
+ port = 22222
14
+ ws_url = f"ws://{server}:{port}/create"
15
+
16
+ prompt = "Hello, who are you?"
17
+ event_loop = asyncio.get_event_loop()
18
+ event_loop.run_until_complete(chat_with_websocket(ws_url, prompt))
19
+ event_loop.close()