Derfel2025 commited on
Commit
f3f2686
·
1 Parent(s): 07daf79

initial commit

Browse files
Files changed (4) hide show
  1. .env +1 -0
  2. app.py +1077 -0
  3. helper_function.py +167 -0
  4. requirements.txt +9 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ OPENAI_API_KEY=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
app.py ADDED
@@ -0,0 +1,1077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #try using existing logic, but add ctx/memory that llamindex allows
2
+
3
+ #do autonomous llamagents
4
+
5
+ from llama_index.core.tools import FunctionTool
6
+ from llama_index.llms.openai import OpenAI as LlamaOpenAI
7
+ from dotenv import load_dotenv
8
+ from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
9
+ from llama_index.llms.google_genai import GoogleGenAI
10
+ from llama_index.core.agent.workflow import AgentWorkflow, FunctionAgent, ReActAgent #can also import ReActAgent or FunctionAgent from this
11
+ from llama_index.core.tools import FunctionTool
12
+ from llama_index.core.workflow import Context
13
+ import os
14
+ from functools import lru_cache
15
+ import asyncio
16
+ import requests
17
+ from llama_index.core.agent.workflow import (
18
+ AgentInput,
19
+ AgentOutput,
20
+ ToolCall,
21
+ ToolCallResult,
22
+ AgentStream,
23
+ )
24
+ import openai
25
+ import tiktoken
26
+ import requests
27
+ import json
28
+ import gradio as gr
29
+ from openai import OpenAI
30
+ from testDynamic import generate_questions_dynamic
31
+
32
+
33
+ #from llama_index.llms.google_gemini import GoogleGenAI
34
+ #from google.genai import types
35
+
36
+ load_dotenv()
37
+
38
+ #llm = OpenAI(model="gpt-4o-mini")
39
+ import google.generativeai as genai
40
+
41
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
42
+
43
+ llmGeminiPro = GoogleGenAI(model="gemini-2.5-pro")
44
+ print("llmGeminiPro loaded!")
45
+
46
+ llmGeminiFlash = GoogleGenAI(model="gemini-2.5-flash")
47
+ print("llmGeminiFlash loaded!")
48
+
49
+ llm = LlamaOpenAI(
50
+ model="gpt-4o-mini", # or "gpt-3.5-turbo"
51
+ api_key=os.getenv('OPENAI_API_KEY'), # You can also set this via the OPENAI_API_KEY environment variable
52
+ streaming=True
53
+ )
54
+
55
+ llmHigher = LlamaOpenAI(
56
+ model="o3",
57
+ api_key=os.getenv('OPENAI_API_KEY'),
58
+ streaming=True
59
+ )
60
+
61
+ client = OpenAI(
62
+ api_key=os.getenv('OPENAI_API_KEY'),
63
+ )
64
+
65
+ openai.api_key = os.getenv("OPENAI_API_KEY")
66
+ #use gemini
67
+
68
+ #set api_key in .env for gemini
69
+ #llmGemini = GoogleGenAI(model="gemini-2.5-pro")
70
+
71
+ #can use search as AI
72
+ #google_search_tool = types.Tool(
73
+ #google_search=types.GoogleSearch()
74
+ #)#should be able to pass as tool?
75
+
76
+
77
+
78
+ @lru_cache(maxsize=1)
79
+ def get_chartmetric_access_token_cached() -> str | None:
80
+ print("🔑 Fetching new Chartmetric token")
81
+ return get_chartmetric_access_token_with_refresh()
82
+
83
+ #@function_tool
84
+ def get_chartmetric_access_token_with_refresh() -> str or None:
85
+ """
86
+ Retrieves an access token from Chartmetric. You need to use this before you can use any other function involving chartmetric
87
+
88
+ """
89
+ #current_state = await ctx.get('state')
90
+
91
+
92
+ refresh_token = 'izPNc1uMM7A13dvWGs0Gij3rfMTKV0K24ADFfcHviaOPWxc35ZsNuYqlQNb5BVyG'
93
+
94
+ endpoint = 'https://api.chartmetric.com/api/token'
95
+ headers = {
96
+ 'Content-Type': 'application/json'
97
+ }
98
+ payload = {
99
+ 'refreshtoken': refresh_token
100
+ }
101
+
102
+ try:
103
+ response = requests.post(endpoint, headers=headers, json=payload)
104
+ if not response.ok:
105
+ raise Exception(f"Token request failed: {response.status_code} {response.reason}")
106
+
107
+ data = response.json()
108
+ print("Access token retrieved:", data.get('token'),{})
109
+
110
+ #if "working_notes" not in current_state:
111
+ #current_state["working_notes"] = {}
112
+
113
+ access_token = data.get('token')# This is your bearer token for future API calls
114
+ #current_state["working_notes"]["access_token"] = access_token
115
+
116
+ #await ctx.set("state", current_state)
117
+ return access_token
118
+
119
+ except Exception as e:
120
+ print("Error retrieving Chartmetric access token:", str(e))
121
+ return None
122
+
123
+
124
+
125
+ #@function_tool
126
+ async def find_artist_id_for_artist(ctx: Context, artist_name: str) -> int:
127
+ """
128
+ Retrieves artist_id for the artist you want to search on the chartmetric system .
129
+
130
+
131
+ """
132
+ current_state = await ctx.store.get('state')
133
+ print(f"value of current_state on load inside of find_artist_id_for_artist is: {current_state}")
134
+
135
+ access_token = get_chartmetric_access_token_cached()
136
+
137
+ url = f'https://api.chartmetric.com/api/search?q={artist_name}&type=artists'
138
+
139
+ headers = {
140
+ "Authorization": f"Bearer {access_token}"
141
+ }
142
+
143
+ try:
144
+ response = requests.get(url, headers=headers)
145
+
146
+ if not response.ok:
147
+ raise Exception(f"artist_id request failed: {response.status_code} {response.reason}")
148
+
149
+ data = response.json()
150
+ print("Raw response data:", data)
151
+
152
+ # Safely access first matched artist
153
+ artists = data.get("obj", {}).get("artists", [])
154
+
155
+ if not artists:
156
+ print(f"No artists found matching '{artist_name}'.")
157
+ return None
158
+
159
+ artist_id = artists[0].get('id',{})
160
+
161
+ # Update state and persist it
162
+ if "working_notes" not in current_state:
163
+ current_state["working_notes"] = {}
164
+
165
+ current_state["working_notes"][f"artist_id_for_{artist_name}"] = artist_id
166
+ await ctx.store.set("state", current_state) # 🟢 Save the updated state
167
+ print(f"🧠 Updated working_notes in find_artist_id_for_artist: {json.dumps(current_state['working_notes'], indent=2)}")
168
+
169
+
170
+ return artist_id
171
+
172
+ except Exception as e:
173
+ print("Error retrieving Chartmetric artist_id:", str(e))
174
+ return None
175
+
176
+ #@function_tool
177
+ async def get_similar_artists(ctx: Context, artist_id: int) -> dict:
178
+ """
179
+ Retrieve a list of similar artists from Chartmetric based on a given artist ID.
180
+
181
+ Parameters:
182
+ - artist_id (int): The Chartmetric artist ID.
183
+
184
+ Returns:
185
+ - dict: A dictionary of similar artists (up to 5).
186
+
187
+ Notes:
188
+ - Results are stored in working memory under "similar_artists".
189
+ """
190
+ current_state = await ctx.store.get('state')
191
+ print(f"value of current_state on load inside of get_similar_artists is: {current_state}")
192
+
193
+ access_token = get_chartmetric_access_token_cached() # Assuming this is defined elsewhere
194
+ print("access_token for get_similar_artists api call obatined!")
195
+
196
+ url = f"https://api.chartmetric.com/api/artist/{artist_id}/relatedartists?limit=3"
197
+ headers = {
198
+ "Authorization": f"Bearer {access_token}"
199
+ }
200
+
201
+ try:
202
+ response = requests.get(url, headers=headers)
203
+ if not response.ok:
204
+ raise Exception(f"Related artists request failed: {response.status_code} {response.reason}")
205
+
206
+ data = response.json()
207
+ print("data returned from get_similar_artists is:", data)
208
+
209
+
210
+ similar_artists = data.get('obj', {})
211
+
212
+ if "working_notes" not in current_state:
213
+ current_state["working_notes"] = {}
214
+
215
+ current_state["working_notes"]["similar_artists"] = similar_artists
216
+ await ctx.store.set('state', current_state)
217
+
218
+ return similar_artists
219
+
220
+ except Exception as e:
221
+ print("Error retrieving similar artists:", str(e))
222
+ return None
223
+
224
+
225
+ async def get_youtube_audience_data(ctx: Context, artist_id: str) -> dict:
226
+ """
227
+ Retrieve Youtube audience data for a given artist, using Chartmetric API.
228
+
229
+ Parameters:
230
+ - artist_id (int): The Chartmetric artist ID.
231
+
232
+ Returns:
233
+ - dict: A dictionary of similar artists (up to 5).
234
+
235
+ Notes:
236
+ - Results are saved in working memory.
237
+ """
238
+ current_state = await ctx.store.get('state')
239
+ print(f"value of current_state on load inside of get_youtube_audience_data is: {current_state}")
240
+
241
+ access_token = get_chartmetric_access_token_cached()
242
+
243
+
244
+ print("🚀 Called get_Youtube with artist_id:", artist_id)
245
+ print("🚀 Called get_Youtube with access_token:", access_token)
246
+
247
+
248
+ url = f"https://api.chartmetric.com/api/artist/{artist_id}/youtube-audience-stats"
249
+ headers = {
250
+ "Authorization": f"Bearer {access_token}"
251
+ }
252
+
253
+ response = requests.get(url, headers=headers)
254
+
255
+ if not response.ok:
256
+ if response.status_code == 404:
257
+ print(f"⚠️ No YouTube data found for artist {artist_id}")
258
+ return {}
259
+
260
+
261
+ data = response.json()
262
+ print(f"data from get_Youtube is: {data}")
263
+
264
+ dataObj = data.get('obj',{})
265
+
266
+ print("Info from get_tiktok_audience_data is:", dataObj)
267
+
268
+ compressed_notable_followers = []
269
+ for follower in dataObj["notable_subscribers"]:
270
+ #pprint(f"follower in dataObj is: {follower}")
271
+
272
+ new_data = {}
273
+
274
+ new_data["custom_name"] = follower.get("custom_name", {})
275
+ new_data["subscribers"] = follower["subscribers"]
276
+ new_data["engagements"] = follower["engagements"]
277
+
278
+ compressed_notable_followers.append(new_data)
279
+
280
+
281
+ dict_to_return = {"top_countries": dataObj["top_countries"], "audience_gender_by_age": dataObj["audience_genders_per_age"], "audience_genders": dataObj["audience_genders"], "top_followers": compressed_notable_followers,
282
+ "subscribers": dataObj["subscribers"], "avg_likes_per_post": dataObj["avg_likes_per_post"], "avg_commments_per_post": dataObj["avg_commments_per_post"],
283
+ "engagement_rate": dataObj["engagement_rate"]
284
+
285
+ }
286
+
287
+ if "working_notes" not in current_state:
288
+ current_state["working_notes"] = {}
289
+
290
+ youtube_audience_stats = dict_to_return
291
+ print(f"youtube_audience_stats are: {youtube_audience_stats}")
292
+ current_state["working_notes"][f"youtube_audience_data for artist {artist_id}"] = youtube_audience_stats
293
+ await ctx.store.set('state', current_state)
294
+
295
+ return { f"youtube_audience_data for artist {artist_id}": youtube_audience_stats}
296
+
297
+
298
+
299
+
300
+
301
+
302
+
303
+ async def get_tiktok_audience_data(ctx: Context, artist_id: str) -> dict:
304
+ """
305
+ Retrieve TikTok audience data for a given artist using Chartmetric API.
306
+
307
+ Parameters:
308
+ - artist_id (str): The Chartmetric artist ID.
309
+
310
+ Returns:
311
+ - dict: TikTok audience breakdown.
312
+
313
+ Notes:
314
+ - Results are saved in working memory.
315
+ """
316
+ current_state = await ctx.store.get('state')
317
+ print(f"value of current_state on load inside of get_tiktok_audience_data is: {current_state}")
318
+
319
+ access_token = get_chartmetric_access_token_cached()
320
+
321
+
322
+ print("🚀 Called get_tiktok_audience_data with artist_id:", artist_id)
323
+ print("🚀 Called get_tiktok_audience_data with access_token:", access_token)
324
+
325
+ url = f"https://api.chartmetric.com/api/artist/{artist_id}/tiktok-audience-stats"
326
+ headers = {
327
+ "Authorization": f"Bearer {access_token}"
328
+ }
329
+
330
+ response = requests.get(url, headers=headers)
331
+
332
+ if not response.ok:
333
+ raise Exception(f"API request failed: {response.status_code} {response.reason}")
334
+
335
+ data = response.json()
336
+ #print(f"data from get_tiktok_audience_data is: {data}")
337
+
338
+ dataObj = data.get('obj',{})
339
+
340
+ #print("Info from get_tiktok_audience_data is:", dataObj)
341
+
342
+ compressed_notable_followers = []
343
+ for follower in dataObj.get("notable_followers", []):
344
+ #print(f"follower in dataObj is: {follower}")
345
+
346
+ new_data = {}
347
+ new_data["username"] = follower["username"]
348
+ new_data["followers"] = follower["followers"]
349
+ new_data["engagement"] = follower["engagements"]
350
+
351
+ compressed_notable_followers.append(new_data)
352
+
353
+
354
+ dict_to_return = {"top_countries": dataObj["top_countries"], "audience_gender_by_age": dataObj["audience_genders_per_age"], "audience_genders": dataObj["audience_genders"], "top_followers": compressed_notable_followers,
355
+ "followers": dataObj["followers"], "avg_likes_per_post": dataObj["avg_likes_per_post"], "avg_commments_per_post": dataObj["avg_commments_per_post"],
356
+ "engagement_rate": dataObj["engagement_rate"]
357
+
358
+ }
359
+ if "working_notes" not in current_state:
360
+ current_state["working_notes"] = {}
361
+
362
+ tiktok_audience_stats = dict_to_return
363
+ #print(f"tiktok_audience_data are: {tiktok_audience_stats}")
364
+ current_state["working_notes"][f"tiktok_audience_data for artist {artist_id}"] = tiktok_audience_stats
365
+ await ctx.store.set('state', current_state)
366
+
367
+ return { f"tiktok_audience_data for artist {artist_id}": tiktok_audience_stats}
368
+
369
+ #choose which parts to return
370
+
371
+
372
+
373
+
374
+
375
+
376
+ #@function_tool
377
+ async def get_instagram_audience_data(ctx: Context, artist_id: str) -> dict:
378
+ """
379
+ Retrieve Instagram audience statistics for a given artist using Chartmetric.
380
+
381
+ Parameters:
382
+ - artist_id (str): The Chartmetric artist ID.
383
+
384
+ Returns:
385
+ - dict: Instagram audience breakdown.
386
+
387
+ Notes:
388
+ - Results are saved in working memory.
389
+ """
390
+ #perhaps just have it get access_token inside here
391
+ #access_token = get_chartmetric_access_token_with_refresh()
392
+
393
+ current_state = await ctx.store.get('state')
394
+ print(f"value of current_state on load inside of get_instagram_audience_stats is: {current_state}")
395
+
396
+ access_token = get_chartmetric_access_token_cached()
397
+
398
+
399
+ print("🚀 Called get_instagram_audience_stats with artist_id:", artist_id)
400
+ print("🚀 Called get_instagram_audience_stats with access_token:", access_token)
401
+
402
+ url = f"https://api.chartmetric.com/api/artist/{artist_id}/instagram-audience-stats"
403
+ headers = {
404
+ "Authorization": f"Bearer {access_token}"
405
+ }
406
+
407
+ response = requests.get(url, headers=headers)
408
+
409
+ if not response.ok:
410
+ raise Exception(f"API request failed: {response.status_code} {response.reason}")
411
+
412
+ data = response.json()
413
+ #print(f"data from api call is: {data}")
414
+ #print("Info from platform Instagram is:", data.get("obj"))
415
+
416
+
417
+ if "working_notes" not in current_state:
418
+ current_state["working_notes"] = {}
419
+
420
+ instagram_audience_stats = data.get('obj', {})
421
+ current_state["working_notes"][f"instagram_audience_data for artist {artist_id}"] = instagram_audience_stats
422
+ await ctx.store.set('state', current_state)
423
+
424
+ return { f"instagram_audience_data for artist {artist_id}": instagram_audience_stats}
425
+
426
+
427
+
428
+ async def get_charts(ctx: Context, artist_id: int, chart_type: str) -> dict:
429
+ """
430
+ Retrieve chart data for a given artist using Chartmetric API.
431
+
432
+ Parameters:
433
+ - artist_id (str): The Chartmetric artist ID.
434
+ - chart_type: The platform chart and sub-choice. Choose one from:
435
+ [
436
+ "spotify_viral_daily", "spotify_viral_weekly", "spotify_top_daily", "spotify_top_weekly",
437
+ "applemusic_top", "applemusic_daily", "applemusic_albums",
438
+ "itunes_top", "itunes_albums",
439
+ "shazam", "beatport",
440
+ "youtube", "youtube_tracks", "youtube_videos", "youtube_trends",
441
+ "amazon"
442
+ ]
443
+
444
+ Returns:
445
+ - dict: Chart entries containing album name, rank, and peak info.
446
+
447
+ Notes:
448
+ - Results are saved in working memory.
449
+ """
450
+
451
+ valid_chart_types = [
452
+ "spotify_viral_daily", "spotify_viral_weekly", "spotify_top_daily", "spotify_top_weekly",
453
+ "applemusic_top", "applemusic_daily", "applemusic_albums",
454
+ "itunes_top", "itunes_albums", "shazam", "beatport",
455
+ "youtube", "youtube_tracks", "youtube_videos", "youtube_trends", "amazon"
456
+ ]
457
+
458
+ if chart_type not in valid_chart_types:
459
+ raise ValueError(f"Invalid chart_type '{chart_type}'. Must be one of: {valid_chart_types}")
460
+
461
+ current_state = await ctx.store.get('state')
462
+ print(f"value of current_state on load inside of get_chart is: {current_state}")
463
+
464
+ #https://api.chartmetric.com/api/artist/:id/:type/charts
465
+
466
+ access_token = get_chartmetric_access_token_cached()
467
+
468
+
469
+ print("🚀 Called get_charts with artist_id:", artist_id)
470
+ print("🚀 Called get_charts with access_token:", access_token)
471
+
472
+ ##shoukd make dates of the chart dynamic later
473
+ ##need to give chart options in function description clearly
474
+
475
+ url = f"https://api.chartmetric.com/api/artist/{artist_id}/{chart_type}/charts?since=2025-03-01&until=2025-07-04"
476
+ headers = {
477
+ "Authorization": f"Bearer {access_token}"
478
+ }
479
+
480
+ response = requests.get(url, headers=headers)
481
+
482
+ if not response.ok:
483
+ print(f"❌ Request failed with status {response.status_code}: {response.text}")
484
+ return {}
485
+
486
+
487
+ data = response.json()
488
+ #print(f"data from get_charts is: {data}")
489
+ print("🚀 data call to get_charts successfully made!")
490
+
491
+ dataObj = data.get('obj',{})
492
+ #print(f"dataObj is {dataObj}")
493
+ dataObjEntries = dataObj.get('data',{})
494
+ dataObjEntries2 = dataObjEntries.get('entries',{})
495
+ #print(f"dataObjEntries2 is {dataObjEntries2}")
496
+
497
+ relevant_details = []
498
+ for entry in dataObjEntries2:
499
+ print(f"entry is: {entry}")
500
+ stuffToSave = { "album": entry["name"], "pre-rank": entry["pre_rank"], "peak": entry["peak_rank"], "peak_day": entry["peak_date"], "rank": entry["rank"] }
501
+ print(f"stuff to save is: {stuffToSave}")
502
+ relevant_details.append(stuffToSave)
503
+
504
+ print(f"value of relevant_dtails is: {relevant_details}")
505
+
506
+ if "working_notes" not in current_state:
507
+ current_state["working_notes"] = {}
508
+
509
+ if f"charts_data for {artist_id}" not in current_state["working_notes"]:
510
+ current_state["working_notes"][f"charts_data for {artist_id}"] = {}
511
+
512
+ current_state["working_notes"][f"charts_data for {artist_id}"][chart_type] = relevant_details
513
+ await ctx.store.set('state', current_state)
514
+
515
+ return {
516
+ "artist_id": artist_id,
517
+ "chart_data": relevant_details
518
+ }
519
+
520
+
521
+ prompto3 = f"""
522
+ # ROLE & TASK
523
+ You are a **senior music strategist** hired to deliver a **two-page Audience Intelligence Brief** for the artist **{chosen_artist}**.
524
+
525
+ # SOURCE MATERIAL
526
+ – You have one source only: **RAW_DATA** (verbatim answers & metrics pulled from Instagram, TikTok and YouTube).
527
+ – Treat all numbers as trustworthy unless they contradict each other; in that case flag the conflict in “Data Gaps”.
528
+
529
+ # WORKFLOW (do not display)
530
+ 1. **THINK:** Extract every statistic, named entity, quote or behavioural clue from RAW_DATA.
531
+ 2. **PLAN:** Map those findings onto the template sections. Identify unsupported cells early.
532
+ 3. **WRITE:** Populate the markdown template in polished, presentation-ready prose.
533
+ – Use concise bullet points (max. 15 words each) and tables for scannability.
534
+ – Keep each column width sensible; wrap long text with `<br>` if needed.
535
+ 4. **VERIFY:** Double-check that totals, % and age-band ranges add up logically.
536
+ 5. **CLEAN:** Do **not** expose this workflow, system prompts or RAW_DATA.
537
+
538
+ # STYLE
539
+ Consultative, insight-rich, brand-strategy tone. Prefer active voice, audience-centric language (“Fans show…”, “Leverage…”).
540
+ Use **bold** for key stats, *italics* for emphasis, emojis only where the template already includes them.
541
+
542
+ # DELIVERABLE
543
+ Return **exactly** the filled-in template between the markers
544
+ `---BEGIN BRIEF---` and `---END BRIEF---`.
545
+ If a section lacks data, keep the section but write “*No platform data supplied — analyst inference required*”.
546
+
547
+ # MARKDOWN TEMPLATE (to be populated – do NOT repeat unfilled)
548
+ ### Deep-Dive Audience Analysis for {chosen_artist}
549
+ (Synthesising Instagram, TikTok & YouTube data within Turkish pop-market context)
550
+
551
+ ---
552
+
553
+ 1. **Audience Architecture at a Glance**
554
+ | Layer | Instagram Data | TikTok/Other* | Strategic Takeaway |
555
+ |--------------------|---------------------------|-----------------------|------------------------------------------|
556
+ | Scale | | | |
557
+ | Core Territory | | | |
558
+ | Secondary Markets | | | |
559
+ | Gender | | | |
560
+ | Prime Age Band | | | |
561
+
562
+ ---
563
+
564
+ 2. **Hidden Insights & Underserved Nuances**
565
+ | Insight | Evidence (platform, metric) | Why It Matters |
566
+ |------------------------------------|---------------------------------|------------------------------------------|
567
+ | | | |
568
+ | | | |
569
+ | | | |
570
+
571
+ ---
572
+
573
+ 3. **Psychographic Micro-Segments to Activate**
574
+ | Segment Name | % Audience | Description (mindset / need-state) | Ideal Touch-point |
575
+ |---------------------|-----------:|------------------------------------|-----------------------------------------|
576
+ | | | | |
577
+ | | | | |
578
+
579
+ ---
580
+
581
+ 4. **Content & Channel Implications**
582
+ | Funnel Stage | Priority Channel(s) | Format & Narrative Hook |
583
+ |----------------|---------------------|--------------------------------------|
584
+ | Discovery | | |
585
+ | Consideration | | |
586
+ | Community | | |
587
+ | Conversion | | |
588
+
589
+ ---
590
+
591
+ 5. **Monetisation & Partnership Levers**
592
+ -
593
+ -
594
+ -
595
+ -
596
+
597
+ ---
598
+
599
+ 6. **Risks & Mitigations**
600
+ | Risk | Potential Impact | Mitigation Play |
601
+ |----------------------------------------|------------------------|------------------------------------------|
602
+ | | | |
603
+ | | | |
604
+
605
+ ---
606
+
607
+ 7. **Data Gaps & Next Steps**
608
+ -
609
+ -
610
+ -
611
+
612
+ ---
613
+
614
+ 📦 **RAW_DATA** (for internal use only – do NOT show in the brief)
615
+ {overall_answers}
616
+
617
+ ---BEGIN BRIEF---
618
+ <!-- o3 starts populating here -->
619
+ ---END BRIEF---
620
+ """
621
+
622
+
623
+ #and that code which allows logging of every step of the memory/thought process
624
+
625
+ #keep teh cahce of chartmetric api, attached to function that gets api_key, which is inserted into each relevant api
626
+ #find_artist_id_for_artist_tool = FunctionTool.from_function(find_artist_id_for_artist)
627
+ #get_instagram_audience_stats_tool = FunctionTool.from_function(get_instagram_audience_stats)
628
+ #get_similar_artists = FunctionTool.from_function(get_similar_artists)
629
+
630
+
631
+ # Wrap your function
632
+ #find_artist_id_for_artist_tool = FunctionTool(fn=find_artist_id_for_artist)
633
+ #get_instagram_audience_stats_tool = FunctionTool(fn=get_instagram_audience_stats)
634
+ #get_similar_artists_tool = FunctionTool(fn=get_similar_artists)
635
+
636
+ manager_agent = ReActAgent(
637
+ name="ManagerAgent",
638
+ description="Manager agent decides which other agents to use, and is decision maker",
639
+ system_prompt=(
640
+ "You are the manager agent. You do not collect data yourself. You delegate tasks to other agents.\n\n"
641
+ "Your responsibilities are:\n"
642
+ "- Receive the user’s question\n"
643
+ "- Decide whether StreamingChartAgent or SocialMediaDataAgent or SimilarityAgent (or two or all) should handle the request\n"
644
+ "+ If the question is about social media audience data (TikTok, Instagram, YouTube), use SocialMediaDataAgent."
645
+ "+ If the question is about chart positions, chart history, or streaming rankings, use StreamingChartAgent."
646
+ "- Wait for their responses and evaluate whether the question has been sufficiently answered\n"
647
+ ),
648
+ llm=llm,
649
+ can_handoff_to=["SocialMediaDataAgent", "SimilarityAgent", "StreamingChartAgent"]
650
+ )
651
+
652
+ streaming_chart_agent = ReActAgent(
653
+ name="StreamingChartAgent",
654
+ description="agent to retrieve streaming chart data for the artist being researched",
655
+ system_prompt=("You are a research agent that retrieves streaming chart information about an artist"),
656
+ llm=llm,
657
+ tools=[get_charts, find_artist_id_for_artist],
658
+ can_handoff_to=["ManagerAgent", "SimilarityAgent", "SocialMediaDataAgent"]
659
+ )
660
+
661
+
662
+ social_media_data_agent = ReActAgent(#try with Function Agents first, change to ReAct agents if needed/performance is poor.
663
+ name="SocialMediaDataAgent",
664
+ description="agent to source data about artists from social media data, using chartmetric api",
665
+ system_prompt=(
666
+ "You are a research agent that uses social media data to analyze artist audiences via Chartmetric.\n"
667
+ "- Always use **both** Instagram and TikTok and Youtube data as your default behavior when analyzing artists.\n"
668
+ "- Do NOT choose one over the other unless explicitly told to focus on one.\n"
669
+ "- Always call 'get_instagram_audience_stats' AND 'get_tiktok_audience_data' AND 'get_youtube_audience_data' when gathering audience data.\n"
670
+ "- Do NOT assume artist names. Only use 'find_artist_id_for_artist' with real artist names provided by the user.\n"
671
+ "- If the user needs information about similar artists, HAND OFF to the SimilarityAgent — do NOT attempt it yourself.\n"
672
+ "- Your tools are only for Instagram and TikTok and Youtube data.\n"
673
+ )
674
+ ,
675
+ llm=llmHigher,
676
+ tools=[get_instagram_audience_data, find_artist_id_for_artist, get_tiktok_audience_data, get_youtube_audience_data],
677
+ can_handoff_to=["ManagerAgent", "SimilarityAgent", "StreamingChartAgent"]#allow it to handoff to all other agents
678
+ )
679
+
680
+ streaming_chart_agent = ReActAgent(
681
+ name="StreamingChartAgent",
682
+ description="agent to retrieve streaming chart data for the artist being researched",
683
+ system_prompt=("You are a research agent that retrieves streaming chart information about an artist"),
684
+ llm=llm,
685
+ tools=[get_charts, find_artist_id_for_artist],
686
+ can_handoff_to=["ManagerAgent", "SimilarityAgent", "SocialMediaDataAgent"]
687
+ )
688
+
689
+ similarity_agent = ReActAgent(
690
+ name="SimilarityAgent",
691
+ description="agent to find similar artists to the artist being research, using chartmetric api",
692
+ system_prompt=("You are a research agent that looks for similar artists to the artist you are researching, in order to understand how the artist can copy the growth of similar artists who are larger."
693
+ "you can handoff to SocialMediaDataAgent, in order to find information about the followers of similar artists"
694
+ ),
695
+ llm=llm,
696
+ tools=[get_similar_artists, find_artist_id_for_artist],
697
+ can_handoff_to=["ManagerAgent", "SocialMediaDataAgent", "StreamingChartAgent"]
698
+ )
699
+
700
+
701
+
702
+
703
+
704
+
705
+
706
+ async def main(chosen_artist, purpose_outline):
707
+ #response = await workflow.run(user_msg="What is Bertie Blackman's Chartmetric artist ID?"
708
+ #, ctx=ctx) python llamaOaAgent.py
709
+ #chosen_artist = "Kenan Doğulu"
710
+
711
+ #llm call to generate dynamic questions, and prompt
712
+ questions_to_ask = generate_questions_dynamic(chosen_artist, purpose_outline)
713
+
714
+ overall_answers = ""
715
+ overall_answers2 = {}
716
+
717
+ all_states = {}
718
+
719
+ for (index, user_msg) in enumerate(questions_to_ask):
720
+
721
+ print(f"starting questions {index + 1}")
722
+
723
+ overall_answers2[index] = {"Thoughts": "", "Answer": ""}
724
+
725
+ #create/re-create workflow with new question as user_msg
726
+ workflow = AgentWorkflow(
727
+ agents=[similarity_agent, social_media_data_agent, manager_agent, streaming_chart_agent],
728
+ root_agent=manager_agent.name,
729
+ initial_state={"working_notes": {}, "user question": user_msg, "users language": "English"}
730
+ )
731
+
732
+ # run the workflow with context
733
+ ctx = Context(workflow)
734
+
735
+
736
+
737
+
738
+ handler = workflow.run(user_msg=user_msg, ctx=ctx)
739
+ current_agent = None
740
+ current_tool_calls = ""
741
+
742
+
743
+
744
+ async for event in handler.stream_events():
745
+ if (
746
+ hasattr(event, "current_agent_name")
747
+ and event.current_agent_name != current_agent
748
+ ):
749
+ current_agent = event.current_agent_name
750
+ print(f"\n{'='*50}")
751
+ print(f"🤖 Agent: {current_agent}")
752
+ print(f"{'='*50}\n")
753
+
754
+ elif isinstance(event, AgentOutput):
755
+ content = event.response.content.strip()
756
+ print("📤 Output:", content)
757
+
758
+ # New logic: extract Thought and Answer from any position
759
+ clean_answer_combined = ""
760
+ thought, answer = None, None
761
+
762
+ if "Thought:" in content:
763
+ if "Answer:" in content:
764
+ thought = content.split("Thought:")[1].split("Answer:")[0].strip()
765
+
766
+ else:
767
+ thought = content.split("Thought:")[1].strip()
768
+ overall_answers2[index]["Thoughts"] += "\n" + thought
769
+ clean_answer_combined += f"🧠 Thought: {thought}\n"
770
+
771
+ if "Answer:" in content:
772
+ answer = content.split("Answer:")[-1].strip()
773
+ overall_answers2[index]["Answer"] = answer
774
+ clean_answer_combined += f"✅ Answer: {answer}\n"
775
+
776
+ if clean_answer_combined:
777
+ question_header = f"\n### Q{index + 1}: {user_msg}\n"
778
+ overall_answers += question_header + clean_answer_combined + "\n"
779
+
780
+ # If either Thought or Answer was captured, append to overall_answers
781
+
782
+ if event.tool_calls:
783
+ print(
784
+ "🛠️ Planning to use tools:",
785
+ [call.tool_name for call in event.tool_calls],
786
+ )
787
+ elif isinstance(event, ToolCallResult):
788
+ print(f"🔧 Tool Result ({event.tool_name}):")
789
+ print(f" Arguments: {event.tool_kwargs}")
790
+ print(f" Output: {event.tool_output}")
791
+ elif isinstance(event, ToolCall):
792
+ print(f"🔨 Calling Tool: {event.tool_name}")
793
+ print(f" With arguments: {event.tool_kwargs}")
794
+
795
+ state = await ctx.store.get("state")
796
+ all_states[f"Q{index+1}"] = {
797
+ "question": user_msg,
798
+ "state": state
799
+ }
800
+
801
+ print(f"overall_answers is: {overall_answers}")
802
+
803
+ #final_state = await ctx.store.get("state")
804
+
805
+ with open(f"ctx_memory_all_answersDynamic.json", "w") as f:
806
+ json.dump(all_states, f, indent=2)
807
+
808
+ #can then keep just the last thought of each question index
809
+
810
+ def count_tokens(text, model="gpt-4o"):
811
+ encoding = tiktoken.encoding_for_model(model)
812
+ return len(encoding.encode(text))
813
+
814
+ total_tokens = count_tokens(overall_answers)
815
+ print(f"Total tokens of overall_answers: {total_tokens}")
816
+
817
+
818
+ # Build a single string
819
+ flattened = "\n\n".join(
820
+ f"Q{idx + 1}: {qa['Thoughts']}\n{qa['Answer']}"
821
+ for idx, qa in overall_answers2.items()
822
+ )
823
+
824
+ total_tokens2 = count_tokens(flattened)
825
+ print(f"Total tokens of overall_answers2: {total_tokens2}")
826
+
827
+ with open(f"overall_answersGemini.txt","w", encoding="utf-8") as file:
828
+ file.write(overall_answers)
829
+
830
+ with open(f"overall_answers2Gemini.txt","w", encoding="utf-8") as file:
831
+ json.dump(overall_answers2, file, ensure_ascii=False, indent=2)
832
+
833
+
834
+
835
+ #now send overall_answers to LLM
836
+
837
+
838
+
839
+
840
+ prompto3ChrisChart = f"""🎯 MEGA AUDIENCE INSIGHT & GROWTH PROMPT
841
+ Prompt Title: Deep Audience Intelligence & Growth Blueprint for [ARTIST_NAME]
842
+
843
+ System Role (Set Once):
844
+ You are a senior music data strategist trained in multi-platform audience intelligence, behavioral segmentation, and growth marketing. You operate like a hybrid of a data analyst, music marketer, and product strategist. Your job is to extract unique insights, detect overlooked opportunities, and build a data-driven growth plan for the artist based on a rich dataset of streaming, chart, and social data.
845
+
846
+ 🔍 INPUT DATA:
847
+ Structured streaming data (Spotify, Apple Music, iTunes, Shazam) with rank movement, peak days, velocity, and decay.
848
+
849
+ Social media + CRM metrics (TikTok, IG, YouTube, Reels, Stories, Email, Merch, Tour Sales, etc.).
850
+
851
+ Any artist metadata you can derive (track names, album release cycles, remix info, sentiment cues, genre tags, collaborators).
852
+
853
+ 🧠 TASK
854
+ Split your approach into three distinct cognitive layers, executed in sequence:
855
+
856
+ ✅ LAYER 1: ANALYTICAL DEEP DIVE
857
+ Understand the data in its rawest form.
858
+
859
+ Detect patterns in streaming velocity, seasonal performance, and Shazam conversion.
860
+
861
+ Surface anomalies — outlier peaks, remix vs original inconsistencies, platform skews.
862
+
863
+ Build segmentations across:
864
+
865
+ Demographics (inferred via geo and platform)
866
+
867
+ Behavioral (engagement, replay rate, completion, skip/save behavior)
868
+
869
+ Content type affinity (e.g., club mix vs acoustic vs emotional lyrics)
870
+
871
+ Identify:
872
+
873
+ Top 3–5 most influential formats (content, platform, track type)
874
+
875
+ 2–3 examples of platform crossover lags (e.g., Shazam peak → Spotify delay)
876
+
877
+ Fanbase decay curves (where and when attention drops off)
878
+
879
+ 🧠 LAYER 2: STRATEGIC REASONING
880
+ Generate hypotheses and opportunity clusters.
881
+
882
+ Audience Gaps:
883
+
884
+ Where is the artist underperforming?
885
+
886
+ What similar audiences (adjacent genres, demos, cities) are reachable?
887
+
888
+ Cluster Fans into Personas based on behavior + geo:
889
+ Example labels:
890
+
891
+ “Shazam-driven club-goers in Southern Europe”
892
+
893
+ “Loyal iTunes buyers over 40 in Central Asia”
894
+
895
+ “Spotify Weekly repeaters with remix preference in Berlin”
896
+
897
+ For each persona cluster, answer:
898
+
899
+ What drives their behavior?
900
+
901
+ Where can we find more like them?
902
+
903
+ Which platform(s) matter most?
904
+
905
+ Propose 3–4 testable hypotheses about:
906
+
907
+ Timing strategies
908
+
909
+ Collaboration types
910
+
911
+ Format performance
912
+
913
+ Messaging tones (e.g. romantic, nostalgic, rebellious)
914
+
915
+ 🚀 LAYER 3: GROWTH & CAMPAIGN STRATEGY
916
+ Turn intelligence into a tactical plan.
917
+
918
+ Recommend:
919
+
920
+ 3 platform strategies, tailored to audience types (e.g. TikTok + Reels = Hook virality vs Apple = intimacy/purchase)
921
+
922
+ 3 content types likely to resonate with segments (e.g. stripped vocals for Gen Z on IG vs remix packs for DJs)
923
+
924
+ 2 partnership ideas — either influencer-led, playlist curators, or collab artists with overlapping fanbases
925
+
926
+ Suggest distribution timing:
927
+
928
+ What day, week, and month clusters have historically driven best results?
929
+
930
+ Layer this with social engagement cycles.
931
+
932
+ Design 1 bold, data-informed “Big Bet” campaign:
933
+
934
+ Could be a geo-targeted drop, genre mashup collab, remix competition, or a multi-platform narrative series.
935
+
936
+ 🧪 OUTPUT FORMAT:
937
+ markdown
938
+ Copy
939
+ Edit
940
+ # Artist Audience Intelligence & Growth Blueprint: [Artist Name]
941
+
942
+ ## 1. Overview
943
+ Short summary of overall patterns, growth arcs, and platform behaviors.
944
+
945
+ ## 2. Key Segments
946
+ - Persona 1: “...” → Description, platforms, geo, behavior
947
+ - Persona 2: ...
948
+ - Persona 3: ...
949
+
950
+ ## 3. Strategic Observations
951
+ - Opportunity gaps
952
+ - Surprising over/under performance
953
+ - Hypotheses
954
+
955
+ ## 4. Marketing Recommendations
956
+ ### A. Platform Strategy
957
+ [List of 3, each with logic and examples]
958
+
959
+ ### B. Content Types to Emphasize
960
+ [List of 3, with reasoning per segment]
961
+
962
+ ### C. Influencer/Partnership Strategy
963
+ [2 ideas with audience alignment logic]
964
+
965
+ ## 5. Big Bet Growth Campaign
966
+ Title + concept + rationale
967
+
968
+ Your data is {overall_answers}
969
+ """
970
+
971
+
972
+
973
+
974
+
975
+
976
+ ##cut down Thought input, so only last one returned with Answer from
977
+
978
+
979
+ #count tokens anyway, for later usage:
980
+ total_tokens = count_tokens(purpose_outline)
981
+ print(f"Total tokens of prompt: {total_tokens}")
982
+
983
+ max_tokens = 16384 - total_tokens - 200
984
+
985
+ final_prompt = purpose_outline + f"""Your sole data source should be: {overall_answers}""" + f"""The artist is: {chosen_artist}"""
986
+
987
+ response = client.responses.create(
988
+ model="o3",
989
+ input=[
990
+ {
991
+ "role": "developer",
992
+ "content": [
993
+ {
994
+ "type": "input_text",
995
+ "text": (
996
+ "You are a precise music industry data analyst. "
997
+ "Be structured, factual, and preserve all stats given."
998
+ )
999
+ }
1000
+ ]
1001
+ },
1002
+ {
1003
+ "role": "user",
1004
+ "content": [
1005
+ {
1006
+ "type": "input_text",
1007
+ "text": final_prompt
1008
+ }
1009
+ ]
1010
+ }
1011
+ ],
1012
+ text={
1013
+ "format": {
1014
+ "type": "text"
1015
+ }
1016
+ },
1017
+ reasoning={
1018
+ "effort": "medium",
1019
+ "summary": "auto"
1020
+ },
1021
+ tools=[],
1022
+ store=True
1023
+ )
1024
+
1025
+
1026
+ print(response.output_text)
1027
+ two_pager_document = response.output_text
1028
+
1029
+
1030
+ #Gemini version
1031
+ #enai.configure(api_key="AIzaSyBtpgpnI_kzxPfvlqoDbaYwlOPdxI89qNI")
1032
+ #model = genai.GenerativeModel("models/gemini-2.5-pro")
1033
+
1034
+ # Generate content
1035
+ #responseGemini = model.generate_content(f"You are a precise music industry data analyst. Be structured, factual, and preserve all stats given. use: {final_prompt}")
1036
+ #two_pager_gemini = responseGemini.text
1037
+
1038
+
1039
+ #print(responseGemini.text)
1040
+
1041
+
1042
+ #for question in formal_questions:
1043
+ #print(f"overall_answer2 is {overall_answers2}")
1044
+
1045
+ with open(f"{chosen_artist}DynamicQuestionsOpenAI.txt","w", encoding="utf-8") as file:
1046
+ file.write(two_pager_document)
1047
+
1048
+ return two_pager_document
1049
+
1050
+
1051
+ demo = gr.Interface(
1052
+ fn=main,
1053
+ inputs=["text", "text"],
1054
+ outputs="text",
1055
+ title="artist report generator - dynamic questions",
1056
+ description="generate report for artist"
1057
+ )
1058
+
1059
+ demo.launch(share=True)
1060
+
1061
+ #if __name__ == "__main__":
1062
+ #response = asyncio.run(main())
1063
+ #then pass to llm to assemble formal response to formal questions
1064
+
1065
+ # FunctionAgent works for LLMs with a function calling API.
1066
+ # ReActAgent works for any LLM.
1067
+
1068
+
1069
+
1070
+ #can check logs:
1071
+ #async for ev in handler.stream_events():
1072
+ #if isinstance(ev, ToolCallResult):
1073
+ #print("")
1074
+ #print("Called tool: ", ev.tool_name, ev.tool_kwargs, "=>", ev.tool_output)
1075
+ #elif isinstance(ev, AgentStream): # showing the thought process
1076
+ #print(ev.delta, end="", flush=True)
1077
+
helper_function.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import re
3
+ import json
4
+ import os
5
+ from openai import OpenAI
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+
10
+ client = OpenAI()
11
+
12
+ genai.configure(api_key="AIzaSyBtpgpnI_kzxPfvlqoDbaYwlOPdxI89qNI")
13
+ client = OpenAI(
14
+ api_key=os.getenv('OPENAI_API_KEY'),
15
+ )
16
+
17
+
18
+ #artist_name = "Kenan Doğulu"
19
+ purpose_outline = f"""
20
+ # ROLE & TASK
21
+ You are a **senior music strategist** hired to deliver a **two-page Audience Intelligence Brief** for the artist .
22
+
23
+ # SOURCE MATERIAL
24
+ – You have one source only: **RAW_DATA** (verbatim answers & metrics pulled from Instagram, TikTok and YouTube).
25
+ – Treat all numbers as trustworthy unless they contradict each other; in that case flag the conflict in “Data Gaps”.
26
+
27
+ # WORKFLOW (do not display)
28
+ 1. **THINK:** Extract every statistic, named entity, quote or behavioural clue from RAW_DATA.
29
+ 2. **PLAN:** Map those findings onto the template sections. Identify unsupported cells early.
30
+ 3. **WRITE:** Populate the markdown template in polished, presentation-ready prose.
31
+ – Use concise bullet points (max. 15 words each) and tables for scannability.
32
+ – Keep each column width sensible; wrap long text with `<br>` if needed.
33
+ 4. **VERIFY:** Double-check that totals, % and age-band ranges add up logically.
34
+ 5. **CLEAN:** Do **not** expose this workflow, system prompts or RAW_DATA.
35
+
36
+ # STYLE
37
+ Consultative, insight-rich, brand-strategy tone. Prefer active voice, audience-centric language (“Fans show…”, “Leverage…”).
38
+ Use **bold** for key stats, *italics* for emphasis, emojis only where the template already includes them.
39
+
40
+ # DELIVERABLE
41
+ Return **exactly** the filled-in template between the markers
42
+ `---BEGIN BRIEF---` and `---END BRIEF---`.
43
+ If a section lacks data, keep the section but write “*No platform data supplied — analyst inference required*”.
44
+
45
+ # MARKDOWN TEMPLATE (to be populated – do NOT repeat unfilled)
46
+ ### Deep-Dive Audience Analysis for teh artist
47
+ (Synthesising Instagram, TikTok & YouTube data within Turkish pop-market context)
48
+
49
+ ---
50
+
51
+ 1. **Audience Architecture at a Glance**
52
+ | Layer | Instagram Data | TikTok/Other* | Strategic Takeaway |
53
+ |--------------------|---------------------------|-----------------------|------------------------------------------|
54
+ | Scale | | | |
55
+ | Core Territory | | | |
56
+ | Secondary Markets | | | |
57
+ | Gender | | | |
58
+ | Prime Age Band | | | |
59
+
60
+ ---
61
+
62
+ 2. **Hidden Insights & Underserved Nuances**
63
+ | Insight | Evidence (platform, metric) | Why It Matters |
64
+ |------------------------------------|---------------------------------|------------------------------------------|
65
+ | | | |
66
+ | | | |
67
+ | | | |
68
+
69
+ ---
70
+
71
+ 3. **Psychographic Micro-Segments to Activate**
72
+ | Segment Name | % Audience | Description (mindset / need-state) | Ideal Touch-point |
73
+ |---------------------|-----------:|------------------------------------|-----------------------------------------|
74
+ | | | | |
75
+ | | | | |
76
+
77
+ ---
78
+
79
+ 4. **Content & Channel Implications**
80
+ | Funnel Stage | Priority Channel(s) | Format & Narrative Hook |
81
+ |----------------|---------------------|--------------------------------------|
82
+ | Discovery | | |
83
+ | Consideration | | |
84
+ | Community | | |
85
+ | Conversion | | |
86
+
87
+ ---
88
+
89
+ 5. **Monetisation & Partnership Levers**
90
+ -
91
+ -
92
+ -
93
+ -
94
+
95
+ ---
96
+
97
+ 6. **Risks & Mitigations**
98
+ | Risk | Potential Impact | Mitigation Play |
99
+ |----------------------------------------|------------------------|------------------------------------------|
100
+ | | | |
101
+ | | | |
102
+
103
+ ---
104
+
105
+ 7. **Data Gaps & Next Steps**
106
+ -
107
+ -
108
+ -
109
+
110
+ ---
111
+
112
+
113
+
114
+ ---BEGIN BRIEF---
115
+ <!-- o3 starts populating here -->
116
+ ---END BRIEF---
117
+ """
118
+
119
+ #llm call to generate list of questions and prompt
120
+ #do so seperrekt
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+ def generate_questions_dynamic(artist_name, prompt):
129
+ #model = genai.GenerativeModel("models/gemini-2.5-pro")
130
+ message = f"""Using the purpose_outline passed to you, you need to generate a series of questions of as many questions as you think are neccessary to fulfill the outline.
131
+
132
+
133
+ The following tools are available to answer the questions you generate: get_tiktok_audience_data, get_instagram_audience_data, get_youtube_audience_data, get_similar_artists, get_charts.
134
+ You should generate questions that can axctually be answered with the tools available to you.
135
+
136
+ You should return the questions in the format: ["question 1", "question 2", "question 3"]. NO NUMBERS, STRICTLY THAT SCHEMA. No more than 10, no less than 7 questions.
137
+
138
+ Context:
139
+ The artist is: {artist_name}
140
+ The purpose_outline is: {prompt}
141
+
142
+ """ # Generate content
143
+ #response_gemini = model.generate_content(message)
144
+ response = client.responses.create(
145
+ model="gpt-4o",
146
+ input=[
147
+ {"role": "system", "content": "You are a helpful assistant."},
148
+ {"role": "user", "content": message}
149
+ ],
150
+ temperature=0.7
151
+ )
152
+
153
+
154
+
155
+ questions = response.output_text
156
+ print(f"response_gemini is: {questions}")
157
+ questions_to_ask = questions
158
+ print(f"questions_to_ask are: {questions_to_ask}")
159
+
160
+ stripped_questions_to_ask = re.sub(r"^```json\s*|\s*```$", "", questions_to_ask.strip())
161
+ print(f"post-stripping: {stripped_questions_to_ask}")
162
+
163
+ questions_to_ask_cleaned = json.loads(stripped_questions_to_ask)
164
+ print(f"questions_to_ask_cleaned is: {questions_to_ask_cleaned}")
165
+ return questions_to_ask_cleaned
166
+
167
+ #generate_questions_dynamic("Kenan Doğulu", purpose_outline)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ llama-index-core==0.13.0
2
+ llama-index-llms-openai==0.5.0
3
+ openai==1.81.0
4
+ tiktoken
5
+ python-dotenv
6
+ requests
7
+ gradio
8
+ transformers
9
+ google-generativeai