atolat30 commited on
Commit
1d4c95f
·
1 Parent(s): 057cab4

Refactor: Move ASPECT_INFO to prompt_manager.py and improve code organization

Browse files
Files changed (2) hide show
  1. app.py +82 -149
  2. prompt_manager.py +64 -36
app.py CHANGED
@@ -2,7 +2,7 @@
2
 
3
  # OpenAI Chat completion
4
  import os
5
- from openai import AsyncOpenAI # importing openai for API usage
6
  import chainlit as cl # importing chainlit for our app
7
  from chainlit.prompt import Prompt, PromptMessage # importing prompt tools
8
  from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools
@@ -10,169 +10,102 @@ from dotenv import load_dotenv
10
  from prompt_manager import PromptManager
11
  from logger_config import logger
12
 
 
13
  load_dotenv()
14
  logger.info("Environment variables loaded")
15
 
16
- # Initialize prompt manager
17
- prompt_manager = PromptManager()
18
 
19
- # Aspect descriptions and examples
20
- ASPECT_INFO = {
21
- "Concept Simplification": {
22
- "description": "Break down complex topics into simple, understandable terms",
23
- "examples": [
24
- "Explain quantum computing in simple terms",
25
- "How does blockchain work?",
26
- "What is machine learning?"
27
- ]
28
- },
29
- "Summarization": {
30
- "description": "Extract and present key information concisely",
31
- "examples": [
32
- "Summarize the key points of climate change",
33
- "Give me a brief overview of the internet's history",
34
- "What are the main ideas in this article?"
35
- ]
36
- },
37
- "Creativity": {
38
- "description": "Generate innovative ideas and unique perspectives",
39
- "examples": [
40
- "Generate ideas for a sustainable city",
41
- "How could we improve remote work?",
42
- "What are some creative solutions to reduce plastic waste?"
43
- ]
44
- },
45
- "Narrative Structure": {
46
- "description": "Organize information into compelling stories",
47
- "examples": [
48
- "Help me structure a story about time travel",
49
- "Organize the history of AI as a narrative",
50
- "How can I make this presentation more engaging?"
51
- ]
52
- },
53
- "Arithmetic Reasoning": {
54
- "description": "Solve mathematical problems step by step",
55
- "examples": [
56
- "Calculate compound interest on $1000 at 5% for 3 years",
57
- "If a train travels at 60 mph for 2.5 hours, how far does it go?",
58
- "What's the probability of getting three heads in a row?"
59
- ]
60
- },
61
- "Conversational Tone": {
62
- "description": "Engage in natural, friendly discussions",
63
- "examples": [
64
- "Tell me about your favorite book",
65
- "What's your opinion on artificial intelligence?",
66
- "How do you feel about remote work?"
67
- ]
68
- }
69
- }
70
 
71
  @cl.on_chat_start
72
- async def start_chat():
73
  logger.info("Starting new chat session")
74
- # Create aspect selection buttons with descriptions
75
- aspects = prompt_manager.get_aspect_names()
76
- actions = []
 
 
 
 
77
 
78
- for aspect in aspects:
79
- actions.append(
80
- cl.Action(
81
- name=aspect,
82
- value=aspect,
83
- label=aspect,
84
- description=prompt_manager.get_action_description(aspect)
85
- )
86
- )
87
 
88
- # Send welcome message with aspect selection
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  await cl.Message(
90
- content="Welcome! Please select an aspect for our conversation. Hover over each option to see examples and descriptions:",
91
- actions=actions
92
  ).send()
93
- logger.info("Welcome message sent with aspect selection buttons")
94
 
95
- @cl.action_callback("Concept Simplification")
96
- @cl.action_callback("Summarization")
97
- @cl.action_callback("Creativity")
98
- @cl.action_callback("Narrative Structure")
99
- @cl.action_callback("Arithmetic Reasoning")
100
- @cl.action_callback("Conversational Tone")
101
  async def on_action(action):
102
- # Store the selected aspect in the user session
103
- cl.user_session.set("selected_aspect", action.value)
104
- logger.info(f"User selected aspect: {action.value}")
 
 
 
 
 
 
105
 
106
- # Send confirmation message with examples
107
  await cl.Message(
108
- content=prompt_manager.get_confirmation_message(action.value)
109
  ).send()
110
- logger.debug(f"Confirmation message sent for aspect: {action.value}")
111
-
112
- @cl.on_message
113
- async def main(message: cl.Message):
114
- # Get the selected aspect from the session
115
- selected_aspect = cl.user_session.get("selected_aspect")
116
- logger.info(f"Processing message with aspect: {selected_aspect}")
117
- logger.debug(f"User message: {message.content}")
118
 
119
- settings = {
120
- "model": "gpt-4-turbo-preview", # Upgraded to GPT-4 Turbo
121
- "temperature": 0.7, # Balanced between creativity and consistency
122
- "max_tokens": 1000, # Increased for more detailed responses
123
- "top_p": 0.9, # Slightly reduced for more focused responses
124
- "frequency_penalty": 0.3, # Added to reduce repetition
125
- "presence_penalty": 0.3, # Added to encourage diverse topics
126
- }
127
- logger.debug(f"OpenAI settings: {settings}")
128
-
129
- client = AsyncOpenAI()
130
-
131
- # Get the appropriate templates for the selected aspect
132
- system_template, user_template = prompt_manager.get_templates(selected_aspect)
133
- logger.debug("Templates retrieved for message processing")
134
-
135
- prompt = Prompt(
136
- provider=ChatOpenAI.id,
137
- messages=[
138
- PromptMessage(
139
- role="system",
140
- template=system_template,
141
- formatted=system_template,
142
- ),
143
- PromptMessage(
144
- role="user",
145
- template=user_template,
146
- formatted=user_template.format(input=message.content),
147
- ),
148
- ],
149
- inputs={"input": message.content},
150
- settings=settings,
151
- )
152
- logger.debug("Prompt created for OpenAI API call")
153
-
154
- msg = cl.Message(content="")
155
- logger.info("Starting OpenAI API call")
156
 
157
- try:
158
- # Call OpenAI
159
- async for stream_resp in await client.chat.completions.create(
160
- messages=[m.to_openai() for m in prompt.messages], stream=True, **settings
161
- ):
162
- token = stream_resp.choices[0].delta.content
163
- if not token:
164
- token = ""
165
- await msg.stream_token(token)
166
-
167
- # Update the prompt object with the completion
168
- prompt.completion = msg.content
169
- msg.prompt = prompt
170
-
171
- # Send and close the message stream
172
- await msg.send()
173
- logger.info("Response successfully sent to user")
174
- except Exception as e:
175
- logger.error(f"Error during OpenAI API call: {str(e)}")
176
- await cl.Message(
177
- content="I apologize, but I encountered an error processing your request. Please try again."
178
- ).send()
 
2
 
3
  # OpenAI Chat completion
4
  import os
5
+ from openai import AsyncOpenAI, OpenAI # importing openai for API usage
6
  import chainlit as cl # importing chainlit for our app
7
  from chainlit.prompt import Prompt, PromptMessage # importing prompt tools
8
  from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools
 
10
  from prompt_manager import PromptManager
11
  from logger_config import logger
12
 
13
+ # Load environment variables
14
  load_dotenv()
15
  logger.info("Environment variables loaded")
16
 
17
+ # Initialize OpenAI client
18
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
19
 
20
+ # Initialize PromptManager
21
+ prompt_manager = PromptManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  @cl.on_chat_start
24
+ async def start():
25
  logger.info("Starting new chat session")
26
+ await cl.Message(
27
+ content="Welcome! I'm your AI assistant. How can I help you today?",
28
+ ).send()
29
+
30
+ @cl.on_message
31
+ async def main(message: cl.Message):
32
+ logger.info(f"Received message: {message.content}")
33
 
34
+ # Get the current aspect from the session
35
+ current_aspect = cl.user_session.get("current_aspect")
36
+ logger.debug(f"Current aspect: {current_aspect}")
 
 
 
 
 
 
37
 
38
+ # Get templates based on the current aspect
39
+ system_template, user_template = prompt_manager.get_templates(current_aspect)
40
+ logger.debug("Retrieved templates from PromptManager")
41
+
42
+ # Format the user message with the template
43
+ formatted_message = user_template.format(input=message.content)
44
+ logger.debug("Formatted user message with template")
45
+
46
+ # Create messages for the API call
47
+ messages = [
48
+ {"role": "system", "content": system_template},
49
+ {"role": "user", "content": formatted_message}
50
+ ]
51
+ logger.debug("Created messages for API call")
52
+
53
+ # Send message to OpenAI
54
+ response = client.chat.completions.create(
55
+ model="gpt-3.5-turbo",
56
+ messages=messages,
57
+ temperature=0.7,
58
+ max_tokens=1000
59
+ )
60
+ logger.info("Received response from OpenAI")
61
+
62
+ # Send response back to user
63
  await cl.Message(
64
+ content=response.choices[0].message.content
 
65
  ).send()
66
+ logger.debug("Sent response to user")
67
 
68
+ @cl.action_callback("select_aspect")
 
 
 
 
 
69
  async def on_action(action):
70
+ logger.info(f"Action selected: {action.value}")
71
+
72
+ # Store the selected aspect in the session
73
+ cl.user_session.set("current_aspect", action.value)
74
+ logger.debug(f"Stored aspect in session: {action.value}")
75
+
76
+ # Get confirmation message
77
+ confirmation = prompt_manager.get_confirmation_message(action.value)
78
+ logger.debug("Generated confirmation message")
79
 
80
+ # Send confirmation message
81
  await cl.Message(
82
+ content=confirmation
83
  ).send()
84
+ logger.debug("Sent confirmation message")
 
 
 
 
 
 
 
85
 
86
+ # Remove the action buttons
87
+ await action.remove()
88
+ logger.debug("Removed action buttons")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ @cl.on_chat_start
91
+ async def show_aspect_buttons():
92
+ logger.info("Showing aspect selection buttons")
93
+
94
+ # Create action buttons for each aspect
95
+ actions = [
96
+ cl.Action(
97
+ name=f"select_aspect",
98
+ value=aspect_name,
99
+ label=aspect_name,
100
+ description=prompt_manager.get_action_description(aspect_name)
101
+ )
102
+ for aspect_name in prompt_manager.get_aspect_names()
103
+ ]
104
+ logger.debug(f"Created {len(actions)} action buttons")
105
+
106
+ # Send message with action buttons
107
+ await cl.Message(
108
+ content="Select an aspect to customize my behavior:",
109
+ actions=actions
110
+ ).send()
111
+ logger.debug("Sent message with action buttons")
prompt_manager.py CHANGED
@@ -2,6 +2,58 @@ from dataclasses import dataclass
2
  from typing import Dict, List, Optional, Tuple
3
  from logger_config import logger
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  @dataclass
6
  class AspectInfo:
7
  description: str
@@ -30,12 +82,8 @@ Think through your response step by step."""
30
 
31
  self.aspects = {
32
  "Concept Simplification": AspectInfo(
33
- description="Break down complex topics into simple, understandable terms",
34
- examples=[
35
- "Explain quantum computing in simple terms",
36
- "How does blockchain work?",
37
- "What is machine learning?"
38
- ],
39
  system_template="""You are an expert at breaking down complex concepts into simple, understandable terms.
40
  Your goal is to make difficult topics accessible while maintaining accuracy.
41
  Always use clear examples and analogies to illustrate points.""",
@@ -45,12 +93,8 @@ Always use clear examples and analogies to illustrate points.""",
45
  - What are common misconceptions?"""
46
  ),
47
  "Summarization": AspectInfo(
48
- description="Extract and present key information concisely",
49
- examples=[
50
- "Summarize the key points of climate change",
51
- "Give me a brief overview of the internet's history",
52
- "What are the main ideas in this article?"
53
- ],
54
  system_template="""You are a skilled summarizer who can extract key information and present it concisely.
55
  Focus on the most important points while maintaining context.
56
  Structure your summaries in a clear, logical manner.""",
@@ -60,12 +104,8 @@ Structure your summaries in a clear, logical manner.""",
60
  - What context is important to retain?"""
61
  ),
62
  "Creativity": AspectInfo(
63
- description="Generate innovative ideas and unique perspectives",
64
- examples=[
65
- "Generate ideas for a sustainable city",
66
- "How could we improve remote work?",
67
- "What are some creative solutions to reduce plastic waste?"
68
- ],
69
  system_template="""You are a creative thinker who can generate innovative ideas and solutions.
70
  Think outside the box while staying relevant to the topic.
71
  Encourage creative exploration and unique perspectives.""",
@@ -75,12 +115,8 @@ Encourage creative exploration and unique perspectives.""",
75
  - What innovative solutions can we consider?"""
76
  ),
77
  "Narrative Structure": AspectInfo(
78
- description="Organize information into compelling stories",
79
- examples=[
80
- "Help me structure a story about time travel",
81
- "Organize the history of AI as a narrative",
82
- "How can I make this presentation more engaging?"
83
- ],
84
  system_template="""You are an expert in storytelling and narrative organization.
85
  Help structure information in a compelling, story-like format.
86
  Focus on flow, progression, and engagement in your responses.""",
@@ -90,12 +126,8 @@ Focus on flow, progression, and engagement in your responses.""",
90
  - What elements would enhance the flow?"""
91
  ),
92
  "Arithmetic Reasoning": AspectInfo(
93
- description="Solve mathematical problems step by step",
94
- examples=[
95
- "Calculate compound interest on $1000 at 5% for 3 years",
96
- "If a train travels at 60 mph for 2.5 hours, how far does it go?",
97
- "What's the probability of getting three heads in a row?"
98
- ],
99
  system_template="""You are a mathematical reasoning expert who can solve problems step by step.
100
  Break down complex calculations into manageable parts.
101
  Explain your mathematical thinking clearly and thoroughly.""",
@@ -105,12 +137,8 @@ Explain your mathematical thinking clearly and thoroughly.""",
105
  - How can we verify the answer?"""
106
  ),
107
  "Conversational Tone": AspectInfo(
108
- description="Engage in natural, friendly discussions",
109
- examples=[
110
- "Tell me about your favorite book",
111
- "What's your opinion on artificial intelligence?",
112
- "How do you feel about remote work?"
113
- ],
114
  system_template="""You are a friendly and engaging conversational partner.
115
  Maintain a natural, warm tone while being informative.
116
  Adapt your communication style to match the user's level of expertise.""",
 
2
  from typing import Dict, List, Optional, Tuple
3
  from logger_config import logger
4
 
5
+ # Aspect descriptions and examples
6
+ ASPECT_INFO = {
7
+ "Concept Simplification": {
8
+ "description": "Break down complex topics into simple, understandable terms",
9
+ "examples": [
10
+ "Explain quantum computing in simple terms",
11
+ "How does blockchain work?",
12
+ "What is machine learning?"
13
+ ]
14
+ },
15
+ "Summarization": {
16
+ "description": "Extract and present key information concisely",
17
+ "examples": [
18
+ "Summarize the key points of climate change",
19
+ "Give me a brief overview of the internet's history",
20
+ "What are the main ideas in this article?"
21
+ ]
22
+ },
23
+ "Creativity": {
24
+ "description": "Generate innovative ideas and unique perspectives",
25
+ "examples": [
26
+ "Generate ideas for a sustainable city",
27
+ "How could we improve remote work?",
28
+ "What are some creative solutions to reduce plastic waste?"
29
+ ]
30
+ },
31
+ "Narrative Structure": {
32
+ "description": "Organize information into compelling stories",
33
+ "examples": [
34
+ "Help me structure a story about time travel",
35
+ "Organize the history of AI as a narrative",
36
+ "How can I make this presentation more engaging?"
37
+ ]
38
+ },
39
+ "Arithmetic Reasoning": {
40
+ "description": "Solve mathematical problems step by step",
41
+ "examples": [
42
+ "Calculate compound interest on $1000 at 5% for 3 years",
43
+ "If a train travels at 60 mph for 2.5 hours, how far does it go?",
44
+ "What's the probability of getting three heads in a row?"
45
+ ]
46
+ },
47
+ "Conversational Tone": {
48
+ "description": "Engage in natural, friendly discussions",
49
+ "examples": [
50
+ "Tell me about your favorite book",
51
+ "What's your opinion on artificial intelligence?",
52
+ "How do you feel about remote work?"
53
+ ]
54
+ }
55
+ }
56
+
57
  @dataclass
58
  class AspectInfo:
59
  description: str
 
82
 
83
  self.aspects = {
84
  "Concept Simplification": AspectInfo(
85
+ description=ASPECT_INFO["Concept Simplification"]["description"],
86
+ examples=ASPECT_INFO["Concept Simplification"]["examples"],
 
 
 
 
87
  system_template="""You are an expert at breaking down complex concepts into simple, understandable terms.
88
  Your goal is to make difficult topics accessible while maintaining accuracy.
89
  Always use clear examples and analogies to illustrate points.""",
 
93
  - What are common misconceptions?"""
94
  ),
95
  "Summarization": AspectInfo(
96
+ description=ASPECT_INFO["Summarization"]["description"],
97
+ examples=ASPECT_INFO["Summarization"]["examples"],
 
 
 
 
98
  system_template="""You are a skilled summarizer who can extract key information and present it concisely.
99
  Focus on the most important points while maintaining context.
100
  Structure your summaries in a clear, logical manner.""",
 
104
  - What context is important to retain?"""
105
  ),
106
  "Creativity": AspectInfo(
107
+ description=ASPECT_INFO["Creativity"]["description"],
108
+ examples=ASPECT_INFO["Creativity"]["examples"],
 
 
 
 
109
  system_template="""You are a creative thinker who can generate innovative ideas and solutions.
110
  Think outside the box while staying relevant to the topic.
111
  Encourage creative exploration and unique perspectives.""",
 
115
  - What innovative solutions can we consider?"""
116
  ),
117
  "Narrative Structure": AspectInfo(
118
+ description=ASPECT_INFO["Narrative Structure"]["description"],
119
+ examples=ASPECT_INFO["Narrative Structure"]["examples"],
 
 
 
 
120
  system_template="""You are an expert in storytelling and narrative organization.
121
  Help structure information in a compelling, story-like format.
122
  Focus on flow, progression, and engagement in your responses.""",
 
126
  - What elements would enhance the flow?"""
127
  ),
128
  "Arithmetic Reasoning": AspectInfo(
129
+ description=ASPECT_INFO["Arithmetic Reasoning"]["description"],
130
+ examples=ASPECT_INFO["Arithmetic Reasoning"]["examples"],
 
 
 
 
131
  system_template="""You are a mathematical reasoning expert who can solve problems step by step.
132
  Break down complex calculations into manageable parts.
133
  Explain your mathematical thinking clearly and thoroughly.""",
 
137
  - How can we verify the answer?"""
138
  ),
139
  "Conversational Tone": AspectInfo(
140
+ description=ASPECT_INFO["Conversational Tone"]["description"],
141
+ examples=ASPECT_INFO["Conversational Tone"]["examples"],
 
 
 
 
142
  system_template="""You are a friendly and engaging conversational partner.
143
  Maintain a natural, warm tone while being informative.
144
  Adapt your communication style to match the user's level of expertise.""",