bsmith3715 commited on
Commit
e232d87
·
verified ·
1 Parent(s): b2d84c4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from openai import AsyncOpenAI # importing openai for API usage
3
+ import chainlit as cl # importing chainlit for our app
4
+ from chainlit.prompt import Prompt, PromptMessage # importing prompt tools
5
+ from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+
10
+ # ChatOpenAI Templates
11
+ system_template = """You are a helpful assistant who always speaks in a pleasant tone!
12
+ """
13
+
14
+ user_template = """{input}
15
+ Think through your response step by step.
16
+ """
17
+
18
+
19
+ @cl.on_chat_start # marks a function that will be executed at the start of a user session
20
+ async def start_chat():
21
+ settings = {
22
+ "model": "gpt-3.5-turbo",
23
+ "temperature": 0,
24
+ "max_tokens": 500,
25
+ "top_p": 1,
26
+ "frequency_penalty": 0,
27
+ "presence_penalty": 0,
28
+ }
29
+
30
+ cl.user_session.set("settings", settings)
31
+
32
+
33
+ @cl.on_message # marks a function that should be run each time the chatbot receives a message from a user
34
+ async def main(message: cl.Message):
35
+ settings = cl.user_session.get("settings")
36
+
37
+ client = AsyncOpenAI()
38
+
39
+ print(message.content)
40
+
41
+ prompt = Prompt(
42
+ provider=ChatOpenAI.id,
43
+ messages=[
44
+ PromptMessage(
45
+ role="system",
46
+ template=system_template,
47
+ formatted=system_template,
48
+ ),
49
+ PromptMessage(
50
+ role="user",
51
+ template=user_template,
52
+ formatted=user_template.format(input=message.content),
53
+ ),
54
+ ],
55
+ inputs={"input": message.content},
56
+ settings=settings,
57
+ )
58
+
59
+ print([m.to_openai() for m in prompt.messages])
60
+
61
+ msg = cl.Message(content="")
62
+
63
+ # Call OpenAI
64
+ async for stream_resp in await client.chat.completions.create(
65
+ messages=[m.to_openai() for m in prompt.messages], stream=True, **settings
66
+ ):
67
+ token = stream_resp.choices[0].delta.content
68
+ if not token:
69
+ token = ""
70
+ await msg.stream_token(token)
71
+
72
+ # Update the prompt object with the completion
73
+ prompt.completion = msg.content
74
+ msg.prompt = prompt
75
+
76
+ # Send and close the message stream
77
+ await msg.send()