akhatr-phyniks commited on
Commit
f9703fd
·
verified ·
1 Parent(s): b5198f9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import gradio as gr
4
+ from openai import OpenAI
5
+ from langfuse import Langfuse
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables from .env file if it exists
9
+ load_dotenv()
10
+
11
+ # Initialize OpenAI client with error handling
12
+ try:
13
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
14
+ except Exception as e:
15
+ print(f"Warning: OpenAI client initialization failed: {e}")
16
+ client = None
17
+
18
+ # Initialize Langfuse client with error handling
19
+ try:
20
+ langfuse = Langfuse(
21
+ public_key=os.getenv("LANGFUSE_PUBLIC_KEY"),
22
+ secret_key=os.getenv("LANGFUSE_SECRET_KEY"),
23
+ )
24
+ except Exception as e:
25
+ print(f"Warning: Langfuse client initialization failed: {e}")
26
+ langfuse = None
27
+
28
+ def create_chat_interface():
29
+ # Initialize session state
30
+ session_id = str(uuid.uuid4())
31
+
32
+ # Create a new trace for this session if Langfuse is available
33
+ trace = None
34
+ if langfuse:
35
+ try:
36
+ trace = langfuse.trace(
37
+ id=session_id,
38
+ name="chat_session",
39
+ metadata={"session_id": session_id}
40
+ )
41
+ except Exception as e:
42
+ print(f"Warning: Failed to create Langfuse trace: {e}")
43
+
44
+ def respond(message, chat_history):
45
+ if not message:
46
+ return chat_history, ""
47
+
48
+ # Track user message if Langfuse is available
49
+ span = None
50
+ if trace:
51
+ try:
52
+ span = trace.span(
53
+ name="user_message",
54
+ input={"message": message}
55
+ )
56
+ except Exception as e:
57
+ print(f"Warning: Failed to create Langfuse span: {e}")
58
+
59
+ try:
60
+ if not client:
61
+ return chat_history + [(message, "Error: OpenAI client not initialized. Please check your API key.")], ""
62
+
63
+ # Format chat history for OpenAI
64
+ messages = [
65
+ {"role": "system", "content": """
66
+ You are GREG LOGAN — brand strategist, provocateur, and author of *Creating a Blockbuster Brand*.
67
+
68
+ Your mission: WRITE WITH ZERO FLUFF.
69
+ Every sentence punches. Every insight cuts. Every word earns its place.
70
+
71
+ Tone of Voice:
72
+ - Direct. Punchy. Provocative.
73
+ - High emotional clarity. No hedging.
74
+ - You speak in contrasts and stings. You don't explain — you land.
75
+
76
+ You are allergic to:
77
+ - Clichés and motivational filler
78
+ - Weak qualifiers ("just", "maybe", "sort of", "pretty good")
79
+ - Corporate-speak or thought-leader sludge
80
+ - Passive voice and over-explaining
81
+ - Warm intros, nice outros, or trying to sound "helpful"
82
+
83
+ You are obsessed with:
84
+ - Making bold, counterintuitive points
85
+ - Creating "A vs B" contrast frames to spark clarity
86
+ - Short, high-impact sentence structure
87
+ - Emotionally resonant insight rooted in real systems
88
+ - Writing like a challenger brand, never a cheerleader
89
+
90
+ Ground Rules:
91
+ - You are NOT a coach. You are a strategic weapon.
92
+ - Lead with TRUTH, not encouragement.
93
+ - One idea per sentence. Two max.
94
+ - Speak in absolutes. No hedging.
95
+ - Cut anything that doesn't hit.
96
+
97
+ Output Formats:
98
+ - Social posts (hooks, carousels, threads)
99
+ - Email subject lines and body copy
100
+ - Sales page headlines and system copy
101
+ - Positioning statements and product narratives
102
+ - Influencer kit intros and brand voice scripts
103
+ - Short-form video scripts and outlines
104
+
105
+ Style Examples:
106
+ > Builders win.
107
+ > They don't wait for trends. They architect them.
108
+ > And while the rest are stuck playing catch-up, they attract what everyone else is chasing.
109
+
110
+ > Branding isn't about logos. It's about leverage.
111
+ > Get the system right, and the visuals become obvious.
112
+ > Miss the system, and you'll be rebranding every 18 months.
113
+
114
+ > Your audience isn't confused.
115
+ > They're bored.
116
+ > Clarity isn't the goal. Emotional sharpness is.
117
+
118
+ You are here to provoke, clarify, and reposition.
119
+ Write like the stakes are real. Because they are.
120
+ """}
121
+ ]
122
+
123
+ # Add chat history
124
+ for user_msg, assistant_msg in chat_history:
125
+ messages.append({"role": "user", "content": user_msg})
126
+ messages.append({"role": "assistant", "content": assistant_msg})
127
+
128
+ # Add current message
129
+ messages.append({"role": "user", "content": message})
130
+
131
+ # Get response from OpenAI
132
+ response = client.chat.completions.create(
133
+ model="gpt-3.5-turbo",
134
+ messages=messages
135
+ )
136
+
137
+ assistant_message = response.choices[0].message.content
138
+
139
+ # Track assistant response if Langfuse is available
140
+ if span:
141
+ try:
142
+ span.end(
143
+ output={"response": assistant_message},
144
+ metadata={
145
+ "model": "gpt-3.5-turbo",
146
+ "tokens": response.usage.total_tokens
147
+ }
148
+ )
149
+ except Exception as e:
150
+ print(f"Warning: Failed to end Langfuse span: {e}")
151
+
152
+ chat_history.append((message, assistant_message))
153
+ return chat_history, ""
154
+
155
+ except Exception as e:
156
+ # End span with error if Langfuse is available
157
+ if span:
158
+ try:
159
+ span.end(
160
+ output={"error": str(e)},
161
+ level="ERROR"
162
+ )
163
+ except Exception as span_error:
164
+ print(f"Warning: Failed to end Langfuse span with error: {span_error}")
165
+
166
+ error_message = f"Error: {str(e)}"
167
+ return chat_history + [(message, error_message)], ""
168
+
169
+ # Create Gradio interface
170
+ with gr.Blocks() as demo:
171
+ gr.Markdown("# Greg Logan AI - Brand Strategy Assistant")
172
+ gr.Markdown("Get direct, punchy, and provocative brand strategy insights from Greg Logan's perspective.")
173
+
174
+ chatbot = gr.Chatbot(height=600)
175
+ with gr.Row():
176
+ msg = gr.Textbox(
177
+ show_label=False,
178
+ placeholder="Enter your message here...",
179
+ container=False
180
+ )
181
+ submit = gr.Button("Send")
182
+
183
+ submit.click(respond, [msg, chatbot], [chatbot, msg])
184
+ msg.submit(respond, [msg, chatbot], [chatbot, msg])
185
+
186
+ return demo
187
+
188
+ # Create and launch the interface
189
+ demo = create_chat_interface()
190
+ demo.launch()