atolat30 commited on
Commit
e473be1
·
1 Parent(s): 1ea771b

Refactor: Move configurations to JSON files and update to GPT-4o

Browse files
Files changed (7) hide show
  1. app.py +13 -4
  2. aspects.json +72 -0
  3. chainlit.md +2 -2
  4. config.json +11 -0
  5. config_manager.py +45 -0
  6. models.py +9 -0
  7. prompt_manager.py +28 -148
app.py CHANGED
@@ -8,6 +8,7 @@ from chainlit.prompt import Prompt, PromptMessage # importing prompt tools
8
  from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools
9
  from dotenv import load_dotenv
10
  from prompt_manager import PromptManager
 
11
  from logger_config import logger
12
 
13
  # Load environment variables
@@ -17,7 +18,8 @@ logger.info("Environment variables loaded")
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
@@ -50,12 +52,19 @@ async def main(message: cl.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
 
 
8
  from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools
9
  from dotenv import load_dotenv
10
  from prompt_manager import PromptManager
11
+ from config_manager import ConfigManager
12
  from logger_config import logger
13
 
14
  # Load environment variables
 
18
  # Initialize OpenAI client
19
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
20
 
21
+ # Initialize managers
22
+ config = ConfigManager()
23
  prompt_manager = PromptManager()
24
 
25
  @cl.on_chat_start
 
52
  ]
53
  logger.debug("Created messages for API call")
54
 
55
+ # Get model configuration
56
+ model_config = config.get_model_config()
57
+ logger.debug("Retrieved model configuration")
58
+
59
  # Send message to OpenAI
60
  response = client.chat.completions.create(
61
+ model=model_config["name"],
62
  messages=messages,
63
+ temperature=model_config["temperature"],
64
+ max_tokens=model_config["max_tokens"],
65
+ top_p=model_config["top_p"],
66
+ frequency_penalty=model_config["frequency_penalty"],
67
+ presence_penalty=model_config["presence_penalty"]
68
  )
69
  logger.info("Received response from OpenAI")
70
 
aspects.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "default": {
3
+ "description": "General purpose AI assistant with balanced capabilities",
4
+ "examples": [
5
+ "What can you help me with?",
6
+ "How do you work?",
7
+ "What are your capabilities?"
8
+ ],
9
+ "system_template": "You are a helpful AI assistant with expertise in various domains.\nYour goal is to provide clear, accurate, and helpful responses while maintaining a friendly tone.\nAdapt your communication style based on the user's needs and the complexity of the topic.",
10
+ "user_template": "{input}\nThink through your response step by step."
11
+ },
12
+ "Concept Simplification": {
13
+ "description": "Break down complex topics into simple, understandable terms",
14
+ "examples": [
15
+ "Explain quantum computing in simple terms",
16
+ "How does blockchain work?",
17
+ "What is machine learning?"
18
+ ],
19
+ "system_template": "You are an expert at breaking down complex concepts into simple, understandable terms.\nYour goal is to make difficult topics accessible while maintaining accuracy.\nAlways use clear examples and analogies to illustrate points.",
20
+ "user_template": "Please help me understand this concept: {input}\n- What are the key components?\n- Can you provide a simple analogy?\n- What are common misconceptions?"
21
+ },
22
+ "Summarization": {
23
+ "description": "Extract and present key information concisely",
24
+ "examples": [
25
+ "Summarize the key points of climate change",
26
+ "Give me a brief overview of the internet's history",
27
+ "What are the main ideas in this article?"
28
+ ],
29
+ "system_template": "You are a skilled summarizer who can extract key information and present it concisely.\nFocus on the most important points while maintaining context.\nStructure your summaries in a clear, logical manner.",
30
+ "user_template": "Please summarize this information: {input}\n- What are the main points?\n- What's the key takeaway?\n- What context is important to retain?"
31
+ },
32
+ "Creativity": {
33
+ "description": "Generate innovative ideas and unique perspectives",
34
+ "examples": [
35
+ "Generate ideas for a sustainable city",
36
+ "How could we improve remote work?",
37
+ "What are some creative solutions to reduce plastic waste?"
38
+ ],
39
+ "system_template": "You are a creative thinker who can generate innovative ideas and solutions.\nThink outside the box while staying relevant to the topic.\nEncourage creative exploration and unique perspectives.",
40
+ "user_template": "Let's explore this creatively: {input}\n- What are some unique perspectives?\n- How can we approach this differently?\n- What innovative solutions can we consider?"
41
+ },
42
+ "Narrative Structure": {
43
+ "description": "Organize information into compelling stories",
44
+ "examples": [
45
+ "Help me structure a story about time travel",
46
+ "Organize the history of AI as a narrative",
47
+ "How can I make this presentation more engaging?"
48
+ ],
49
+ "system_template": "You are an expert in storytelling and narrative organization.\nHelp structure information in a compelling, story-like format.\nFocus on flow, progression, and engagement in your responses.",
50
+ "user_template": "Help me structure this as a narrative: {input}\n- What's the main story arc?\n- How can we make it more engaging?\n- What elements would enhance the flow?"
51
+ },
52
+ "Arithmetic Reasoning": {
53
+ "description": "Solve mathematical problems step by step",
54
+ "examples": [
55
+ "Calculate compound interest on $1000 at 5% for 3 years",
56
+ "If a train travels at 60 mph for 2.5 hours, how far does it go?",
57
+ "What's the probability of getting three heads in a row?"
58
+ ],
59
+ "system_template": "You are a mathematical reasoning expert who can solve problems step by step.\nBreak down complex calculations into manageable parts.\nExplain your mathematical thinking clearly and thoroughly.",
60
+ "user_template": "Let's solve this step by step: {input}\n- What's the first step?\n- What formulas or methods should we use?\n- How can we verify the answer?"
61
+ },
62
+ "Conversational Tone": {
63
+ "description": "Engage in natural, friendly discussions",
64
+ "examples": [
65
+ "Tell me about your favorite book",
66
+ "What's your opinion on artificial intelligence?",
67
+ "How do you feel about remote work?"
68
+ ],
69
+ "system_template": "You are a friendly and engaging conversational partner.\nMaintain a natural, warm tone while being informative.\nAdapt your communication style to match the user's level of expertise.",
70
+ "user_template": "Let's discuss this: {input}\n- What's your perspective?\n- Can you explain this in simple terms?\n- How does this relate to everyday experience?"
71
+ }
72
+ }
chainlit.md CHANGED
@@ -1,7 +1,7 @@
1
  # 🤖 Welcome to the Chainlit GPT Assistant!
2
 
3
  Hi there! 👋
4
- This chatbot is powered by **OpenAI GPT-4 Turbo** and built using **Chainlit** to provide real-time, interactive conversations with streaming responses.
5
 
6
  ## 🎯 Conversation Aspects
7
 
@@ -22,7 +22,7 @@ This chatbot offers multiple conversation aspects to tailor the interaction to y
22
 
23
  ## ⚙️ Technical Details
24
 
25
- - 🧠 **LLM:** OpenAI GPT-4 Turbo
26
  - 🛠️ **Framework:** Chainlit
27
  - 📝 **Features:** Comprehensive logging system, modular codebase
28
  - 🌐 **Deployed on:** Hugging Face Spaces
 
1
  # 🤖 Welcome to the Chainlit GPT Assistant!
2
 
3
  Hi there! 👋
4
+ This chatbot is powered by **OpenAI GPT-4o** and built using **Chainlit** to provide real-time, interactive conversations with streaming responses.
5
 
6
  ## 🎯 Conversation Aspects
7
 
 
22
 
23
  ## ⚙️ Technical Details
24
 
25
+ - 🧠 **LLM:** OpenAI GPT-4o
26
  - 🛠️ **Framework:** Chainlit
27
  - 📝 **Features:** Comprehensive logging system, modular codebase
28
  - 🌐 **Deployed on:** Hugging Face Spaces
config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "name": "gpt-4o",
4
+ "temperature": 0.7,
5
+ "max_tokens": 4000,
6
+ "top_p": 1.0,
7
+ "frequency_penalty": 0.0,
8
+ "presence_penalty": 0.0
9
+ },
10
+ "default_aspect": "default"
11
+ }
config_manager.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Dict, Any
3
+ from logger_config import logger
4
+
5
+ class ConfigManager:
6
+ _instance = None
7
+ _config = None
8
+
9
+ def __new__(cls):
10
+ if cls._instance is None:
11
+ cls._instance = super(ConfigManager, cls).__new__(cls)
12
+ return cls._instance
13
+
14
+ def __init__(self):
15
+ if self._config is None:
16
+ self._load_config()
17
+
18
+ def _load_config(self) -> None:
19
+ """Load configuration from JSON file."""
20
+ try:
21
+ with open('config.json', 'r') as f:
22
+ self._config = json.load(f)
23
+ logger.info("Configuration loaded successfully")
24
+ except Exception as e:
25
+ logger.error(f"Error loading configuration: {e}")
26
+ # Set default configuration
27
+ self._config = {
28
+ "model": {
29
+ "name": "gpt-4",
30
+ "temperature": 0.7,
31
+ "max_tokens": 2000,
32
+ "top_p": 1.0,
33
+ "frequency_penalty": 0.0,
34
+ "presence_penalty": 0.0
35
+ },
36
+ "default_aspect": "default"
37
+ }
38
+
39
+ def get_model_config(self) -> Dict[str, Any]:
40
+ """Get model configuration settings."""
41
+ return self._config.get("model", {})
42
+
43
+ def get_default_aspect(self) -> str:
44
+ """Get default aspect name."""
45
+ return self._config.get("default_aspect", "default")
models.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import List
3
+
4
+ @dataclass
5
+ class AspectInfo:
6
+ description: str
7
+ examples: List[str]
8
+ system_template: str
9
+ user_template: str
prompt_manager.py CHANGED
@@ -1,164 +1,44 @@
1
- from dataclasses import dataclass
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
60
- examples: List[str]
61
- system_template: str
62
- user_template: str
63
 
64
  class PromptManager:
65
  def __init__(self):
66
  logger.info("Initializing PromptManager")
67
- # Default template for when no aspect is selected
68
- self.default_aspect = AspectInfo(
69
- description="General purpose AI assistant with balanced capabilities",
70
- examples=[
71
- "What can you help me with?",
72
- "How do you work?",
73
- "What are your capabilities?"
74
- ],
75
- system_template="""You are a helpful AI assistant with expertise in various domains.
76
- Your goal is to provide clear, accurate, and helpful responses while maintaining a friendly tone.
77
- Adapt your communication style based on the user's needs and the complexity of the topic.""",
78
- user_template="""{input}
79
- Think through your response step by step."""
80
- )
81
- logger.debug("Default aspect template created")
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.""",
90
- user_template="""Please help me understand this concept: {input}
91
- - What are the key components?
92
- - Can you provide a simple analogy?
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.""",
101
- user_template="""Please summarize this information: {input}
102
- - What are the main points?
103
- - What's the key takeaway?
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.""",
112
- user_template="""Let's explore this creatively: {input}
113
- - What are some unique perspectives?
114
- - How can we approach this differently?
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.""",
123
- user_template="""Help me structure this as a narrative: {input}
124
- - What's the main story arc?
125
- - How can we make it more engaging?
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.""",
134
- user_template="""Let's solve this step by step: {input}
135
- - What's the first step?
136
- - What formulas or methods should we use?
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.""",
145
- user_template="""Let's discuss this: {input}
146
- - What's your perspective?
147
- - Can you explain this in simple terms?
148
- - How does this relate to everyday experience?"""
149
- )
150
- }
151
  logger.info(f"Initialized {len(self.aspects)} aspects")
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  def get_aspect_names(self) -> List[str]:
154
  """Get list of available aspect names."""
155
  logger.debug("Getting aspect names")
156
- return list(self.aspects.keys())
157
 
158
  def get_aspect_info(self, aspect_name: str) -> AspectInfo:
159
  """Get information for a specific aspect."""
160
  logger.debug(f"Getting aspect info for: {aspect_name}")
161
- return self.aspects.get(aspect_name, self.default_aspect)
162
 
163
  def get_action_description(self, aspect_name: str) -> str:
164
  """Get formatted description for action button."""
@@ -183,8 +63,8 @@ Try asking something like:
183
  logger.debug(f"Getting templates for aspect: {aspect_name}")
184
  if aspect_name is None:
185
  logger.info("No aspect selected, using default template")
186
- info = self.default_aspect
187
  else:
188
  logger.info(f"Using templates for aspect: {aspect_name}")
189
- info = self.aspects.get(aspect_name, self.default_aspect)
190
  return info.system_template, info.user_template
 
1
+ import json
2
  from typing import Dict, List, Optional, Tuple
3
  from logger_config import logger
4
+ from models import AspectInfo
5
+ from config_manager import ConfigManager
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  class PromptManager:
8
  def __init__(self):
9
  logger.info("Initializing PromptManager")
10
+ self.config = ConfigManager()
11
+ self.aspects = self._load_aspects()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  logger.info(f"Initialized {len(self.aspects)} aspects")
13
 
14
+ def _load_aspects(self) -> Dict[str, AspectInfo]:
15
+ """Load aspects from JSON file."""
16
+ try:
17
+ with open('aspects.json', 'r') as f:
18
+ aspects_data = json.load(f)
19
+
20
+ aspects = {}
21
+ for name, data in aspects_data.items():
22
+ aspects[name] = AspectInfo(
23
+ description=data['description'],
24
+ examples=data['examples'],
25
+ system_template=data['system_template'],
26
+ user_template=data['user_template']
27
+ )
28
+ return aspects
29
+ except Exception as e:
30
+ logger.error(f"Error loading aspects: {e}")
31
+ return {}
32
+
33
  def get_aspect_names(self) -> List[str]:
34
  """Get list of available aspect names."""
35
  logger.debug("Getting aspect names")
36
+ return [name for name in self.aspects.keys() if name != 'default']
37
 
38
  def get_aspect_info(self, aspect_name: str) -> AspectInfo:
39
  """Get information for a specific aspect."""
40
  logger.debug(f"Getting aspect info for: {aspect_name}")
41
+ return self.aspects.get(aspect_name, self.aspects[self.config.get_default_aspect()])
42
 
43
  def get_action_description(self, aspect_name: str) -> str:
44
  """Get formatted description for action button."""
 
63
  logger.debug(f"Getting templates for aspect: {aspect_name}")
64
  if aspect_name is None:
65
  logger.info("No aspect selected, using default template")
66
+ info = self.aspects[self.config.get_default_aspect()]
67
  else:
68
  logger.info(f"Using templates for aspect: {aspect_name}")
69
+ info = self.aspects.get(aspect_name, self.aspects[self.config.get_default_aspect()])
70
  return info.system_template, info.user_template