File size: 23,500 Bytes
1a1ddbd
 
 
 
 
d8fea2b
1a1ddbd
dfae63c
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
 
 
 
 
 
 
 
09ca1a4
d8fea2b
09ca1a4
d8fea2b
7086345
 
 
 
 
d8fea2b
 
1a1ddbd
 
 
 
 
d8fea2b
 
 
 
 
 
 
 
 
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
 
 
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
 
 
 
d8fea2b
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
d8fea2b
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
 
1a1ddbd
 
 
 
 
 
 
d8fea2b
1a1ddbd
 
 
 
 
d8fea2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
 
 
d8fea2b
 
 
 
 
 
 
 
 
 
 
1a1ddbd
 
d8fea2b
 
 
 
 
 
 
 
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
d8fea2b
 
 
 
 
 
 
 
 
 
1a1ddbd
 
 
 
 
 
 
 
 
 
d8fea2b
1a1ddbd
 
 
 
 
 
 
 
7086345
1a1ddbd
 
 
 
ca72b2c
83c1547
1a1ddbd
83c1547
d8fea2b
 
 
7086345
 
1a1ddbd
60f479a
 
 
 
1a1ddbd
 
cf0838b
1a1ddbd
 
09ca1a4
 
 
 
d8fea2b
09ca1a4
bfb3e9d
09ca1a4
d8fea2b
1a1ddbd
09ca1a4
1a1ddbd
09ca1a4
 
1a1ddbd
 
 
09ca1a4
1a1ddbd
 
 
 
7086345
1a1ddbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
#try using existing logic, but add ctx/memory that llamindex allows

#do autonomous llamagents

from llama_index.core.tools import FunctionTool
from llama_index.llms.openai import OpenAI as LlamaOpenAI
from dotenv import load_dotenv
#from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
#from llama_index.llms.google_genai import GoogleGenAI
from llama_index.core.agent.workflow import AgentWorkflow, FunctionAgent, ReActAgent #can also import ReActAgent or FunctionAgent from this 
from llama_index.core.tools import FunctionTool
from llama_index.core.workflow import Context
import os
from functools import lru_cache
import asyncio
import requests
from llama_index.core.agent.workflow import (
    AgentInput,
    AgentOutput,
    ToolCall,
    ToolCallResult,
    AgentStream,
)
import openai
import tiktoken
import requests
import json
import gradio as gr
from openai import OpenAI 


#from llama_index.llms.google_gemini import GoogleGenAI
#from google.genai import types

load_dotenv()

#llm = OpenAI(model="gpt-4o-mini")
import google.generativeai as genai

genai.configure(api_key=os.getenv("GEMINI_API_KEY"))

#llmGeminiPro = GoogleGenAI(model="gemini-2.5-pro")
#print("llmGeminiPro loaded!")

#llmGeminiFlash = GoogleGenAI(model="gemini-2.5-flash")
#print("llmGeminiFlash loaded!")

llm = LlamaOpenAI(
    model="gpt-4o-mini",  # or "gpt-3.5-turbo"
    api_key=os.getenv('OPENAI_API_KEY'),  # You can also set this via the OPENAI_API_KEY environment variable
    streaming=True    
)

llmHigher = LlamaOpenAI(
    model="o3",
    api_key=os.getenv('OPENAI_API_KEY'),
    streaming=True
)

client = OpenAI(
    api_key=os.getenv('OPENAI_API_KEY'),
)

openai.api_key = os.getenv("OPENAI_API_KEY")
#use gemini

#set api_key in .env for gemini
#llmGemini = GoogleGenAI(model="gemini-2.5-pro")

#can use search as AI
#google_search_tool = types.Tool(
    #google_search=types.GoogleSearch()
#)#should be able to pass as tool?



@lru_cache(maxsize=1)
def get_chartmetric_access_token_cached() -> str | None:
    print("πŸ”‘ Fetching new Chartmetric token")
    return get_chartmetric_access_token_with_refresh()

#@function_tool
def get_chartmetric_access_token_with_refresh() -> str or None:
    """
    Retrieves an access token from Chartmetric. You need to use this before you can use any other function involving chartmetric
    
    """
    #current_state = await ctx.get('state')


    refresh_token = 'izPNc1uMM7A13dvWGs0Gij3rfMTKV0K24ADFfcHviaOPWxc35ZsNuYqlQNb5BVyG'

    endpoint = 'https://api.chartmetric.com/api/token'
    headers = {
        'Content-Type': 'application/json'
    }
    payload = {
        'refreshtoken': refresh_token
    }

    try:
        response = requests.post(endpoint, headers=headers, json=payload)
        if not response.ok:
            raise Exception(f"Token request failed: {response.status_code} {response.reason}")
        
        data = response.json()
        print("Access token retrieved:", data.get('token'),{})

       #if "working_notes" not in current_state:
            #current_state["working_notes"] = {}
        
        access_token = data.get('token')# This is your bearer token for future API calls
        #current_state["working_notes"]["access_token"] = access_token

        #await ctx.set("state", current_state)
        return access_token

    except Exception as e:
        print("Error retrieving Chartmetric access token:", str(e))
        return None



#@function_tool
async def find_artist_id_for_artist(ctx: Context, artist_name: str) -> int:
    """
    Retrieves artist_id for the artist you want to search on the chartmetric system .

    
    """
    current_state = await ctx.store.get('state')
    print(f"value of current_state on load inside of find_artist_id_for_artist is: {current_state}")
 
    access_token = get_chartmetric_access_token_cached()

    url = f'https://api.chartmetric.com/api/search?q={artist_name}&type=artists'

    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    
    try: 
        response = requests.get(url, headers=headers)
        
        if not response.ok:
            raise Exception(f"artist_id request failed: {response.status_code} {response.reason}")

        data = response.json()
        print("Raw response data:", data)
        
        # Safely access first matched artist
        artists = data.get("obj", {}).get("artists", [])
        
        if not artists:
            print(f"No artists found matching '{artist_name}'.")
            return None
        
        artist_id = artists[0].get('id',{})

        # Update state and persist it
        if "working_notes" not in current_state:
            current_state["working_notes"] = {}

        current_state["working_notes"][f"artist_id_for_{artist_name}"] = artist_id
        await ctx.store.set("state", current_state)  # 🟒 Save the updated state
        print(f"🧠 Updated working_notes in find_artist_id_for_artist: {json.dumps(current_state['working_notes'], indent=2)}")


        return artist_id

    except Exception as e:
        print("Error retrieving Chartmetric artist_id:", str(e))
        return None

#@function_tool
async def get_similar_artists(ctx: Context, artist_id: int) -> dict:
    """
    Retrieve a list of similar artists from Chartmetric based on a given artist ID.

    Parameters:
    - artist_id (int): The Chartmetric artist ID.

    Returns:
    - dict: A dictionary of similar artists (up to 5).

    Notes:
    - Results are stored in working memory under "similar_artists".
    """
    current_state = await ctx.store.get('state')
    print(f"value of current_state on load inside of get_similar_artists is: {current_state}")

    access_token = get_chartmetric_access_token_cached()  # Assuming this is defined elsewhere
    print("access_token for get_similar_artists api call obatined!")

    url = f"https://api.chartmetric.com/api/artist/{artist_id}/relatedartists?limit=3"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    try:
        response = requests.get(url, headers=headers)
        if not response.ok:
            raise Exception(f"Related artists request failed: {response.status_code} {response.reason}")

        data = response.json()
        print("data returned from get_similar_artists is:", data)

        
        similar_artists = data.get('obj', {})

        if "working_notes" not in current_state:
            current_state["working_notes"] = {}
        
        current_state["working_notes"]["similar_artists"] = similar_artists
        await ctx.store.set('state', current_state)

        return similar_artists

    except Exception as e:
        print("Error retrieving similar artists:", str(e))
        return None


async def get_youtube_audience_data(ctx: Context, artist_id: str) -> dict:
    """
    Retrieve Youtube audience data for a given artist, using Chartmetric API.

    Parameters:
    - artist_id (int): The Chartmetric artist ID.

    Returns:
    - dict: A dictionary of similar artists (up to 5).

    Notes:
    - Results are saved in working memory.
    """
    current_state = await ctx.store.get('state')
    print(f"value of current_state on load inside of get_youtube_audience_data is: {current_state}")
    
    access_token = get_chartmetric_access_token_cached()


    print("πŸš€ Called get_Youtube with artist_id:", artist_id)
    print("πŸš€ Called get_Youtube with access_token:", access_token)


    url = f"https://api.chartmetric.com/api/artist/{artist_id}/youtube-audience-stats"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    response = requests.get(url, headers=headers)

    if not response.ok:
        if response.status_code == 404:
            print(f"⚠️ No YouTube data found for artist {artist_id}")
            return {}
        

    data = response.json()
    print(f"data from get_Youtube is: {data}")

    dataObj = data.get('obj',{})

    print("Info from get_tiktok_audience_data is:", dataObj)

    compressed_notable_followers = []
    for follower in dataObj["notable_subscribers"]:
        #pprint(f"follower in dataObj is: {follower}")

        new_data = {}
        
        new_data["custom_name"] = follower.get("custom_name", {})
        new_data["subscribers"] = follower["subscribers"] 
        new_data["engagements"] = follower["engagements"] 

        compressed_notable_followers.append(new_data)
    

    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,
      "subscribers": dataObj["subscribers"], "avg_likes_per_post": dataObj["avg_likes_per_post"], "avg_commments_per_post": dataObj["avg_commments_per_post"],
      "engagement_rate": dataObj["engagement_rate"]
    
     }

    if "working_notes" not in current_state:
        current_state["working_notes"] = {}
    
    youtube_audience_stats = dict_to_return
    print(f"youtube_audience_stats are: {youtube_audience_stats}")
    current_state["working_notes"][f"youtube_audience_data for artist {artist_id}"] = youtube_audience_stats
    await ctx.store.set('state', current_state)

    return { f"youtube_audience_data for artist {artist_id}": youtube_audience_stats}







async def get_tiktok_audience_data(ctx: Context, artist_id: str) -> dict:
    """
    Retrieve TikTok audience data for a given artist using Chartmetric API.

    Parameters:
    - artist_id (str): The Chartmetric artist ID.

    Returns:
    - dict: TikTok audience breakdown.

    Notes:
    - Results are saved in working memory.
    """
    current_state = await ctx.store.get('state')
    print(f"value of current_state on load inside of get_tiktok_audience_data is: {current_state}")

    access_token = get_chartmetric_access_token_cached()


    print("πŸš€ Called get_tiktok_audience_data with artist_id:", artist_id)
    print("πŸš€ Called get_tiktok_audience_data with access_token:", access_token)

    url = f"https://api.chartmetric.com/api/artist/{artist_id}/tiktok-audience-stats"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    response = requests.get(url, headers=headers)

    if not response.ok:
        raise Exception(f"API request failed: {response.status_code} {response.reason}")

    data = response.json()
    #print(f"data from get_tiktok_audience_data is: {data}")

    dataObj = data.get('obj',{})

    #print("Info from get_tiktok_audience_data is:", dataObj)

    compressed_notable_followers = []
    for follower in dataObj.get("notable_followers", []):
        #print(f"follower in dataObj is: {follower}")

        new_data = {}
        new_data["username"] = follower["username"]
        new_data["followers"] = follower["followers"] 
        new_data["engagement"] = follower["engagements"] 

        compressed_notable_followers.append(new_data)
    

    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,
      "followers": dataObj["followers"], "avg_likes_per_post": dataObj["avg_likes_per_post"], "avg_commments_per_post": dataObj["avg_commments_per_post"],
      "engagement_rate": dataObj["engagement_rate"]
    
     }
    if "working_notes" not in current_state:
        current_state["working_notes"] = {}
    
    tiktok_audience_stats = dict_to_return
    #print(f"tiktok_audience_data are: {tiktok_audience_stats}")
    current_state["working_notes"][f"tiktok_audience_data for artist {artist_id}"] = tiktok_audience_stats
    await ctx.store.set('state', current_state)

    return { f"tiktok_audience_data for artist {artist_id}": tiktok_audience_stats}

    #choose which parts to return






#@function_tool
async def get_instagram_audience_data(ctx: Context, artist_id: str) -> dict:
    """
    Retrieve Instagram audience statistics for a given artist using Chartmetric.

    Parameters:
    - artist_id (str): The Chartmetric artist ID.

    Returns:
    - dict: Instagram audience breakdown.

    Notes:
    - Results are saved in working memory.
    """
    #perhaps just have it get access_token inside here
    #access_token = get_chartmetric_access_token_with_refresh()

    current_state = await ctx.store.get('state')
    print(f"value of current_state on load inside of get_instagram_audience_stats is: {current_state}")

    access_token = get_chartmetric_access_token_cached()


    print("πŸš€ Called get_instagram_audience_stats with artist_id:", artist_id)
    print("πŸš€ Called get_instagram_audience_stats with access_token:", access_token)
    
    url = f"https://api.chartmetric.com/api/artist/{artist_id}/instagram-audience-stats"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    response = requests.get(url, headers=headers)

    if not response.ok:
        raise Exception(f"API request failed: {response.status_code} {response.reason}")

    data = response.json()
    #print(f"data from api call is: {data}")
    #print("Info from platform Instagram is:", data.get("obj"))
    

    if "working_notes" not in current_state:
        current_state["working_notes"] = {}
    
    instagram_audience_stats = data.get('obj', {})
    current_state["working_notes"][f"instagram_audience_data for artist {artist_id}"] = instagram_audience_stats
    await ctx.store.set('state', current_state)

    return { f"instagram_audience_data for artist {artist_id}": instagram_audience_stats}



async def get_charts(ctx: Context, artist_id: int, chart_type: str) -> dict:
    """
    Retrieve chart data for a given artist using Chartmetric API.

    Parameters:
    - artist_id (str): The Chartmetric artist ID.
    - chart_type: The platform chart and sub-choice. Choose one from:
        [
            "spotify_viral_daily", "spotify_viral_weekly", "spotify_top_daily", "spotify_top_weekly",
            "applemusic_top", "applemusic_daily", "applemusic_albums",
            "itunes_top", "itunes_albums",
            "shazam", "beatport",
            "youtube", "youtube_tracks", "youtube_videos", "youtube_trends",
            "amazon"
        ]

    Returns:
    - dict: Chart entries containing album name, rank, and peak info.

    Notes:
    - Results are saved in working memory.
    """

    valid_chart_types = [
    "spotify_viral_daily", "spotify_viral_weekly", "spotify_top_daily", "spotify_top_weekly",
    "applemusic_top", "applemusic_daily", "applemusic_albums",
    "itunes_top", "itunes_albums", "shazam", "beatport",
    "youtube", "youtube_tracks", "youtube_videos", "youtube_trends", "amazon"
    ]
    
    if chart_type not in valid_chart_types:
        raise ValueError(f"Invalid chart_type '{chart_type}'. Must be one of: {valid_chart_types}")

    current_state = await ctx.store.get('state')
    print(f"value of current_state on load inside of get_chart is: {current_state}")

    #https://api.chartmetric.com/api/artist/:id/:type/charts

    access_token = get_chartmetric_access_token_cached()


    print("πŸš€ Called get_charts with artist_id:", artist_id)
    print("πŸš€ Called get_charts with access_token:", access_token)

    ##shoukd make dates of the chart dynamic later
    ##need to give chart options in function description clearly

    url = f"https://api.chartmetric.com/api/artist/{artist_id}/{chart_type}/charts?since=2025-03-01&until=2025-07-04"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    response = requests.get(url, headers=headers)

    if not response.ok:
        print(f"❌ Request failed with status {response.status_code}: {response.text}")
        return {}
        

    data = response.json()
    #print(f"data from get_charts is: {data}")
    print("πŸš€ data call to get_charts successfully made!")

    dataObj = data.get('obj',{})
    #print(f"dataObj is {dataObj}")
    dataObjEntries = dataObj.get('data',{})
    dataObjEntries2 = dataObjEntries.get('entries',{})
    #print(f"dataObjEntries2 is {dataObjEntries2}")
    
    relevant_details = []
    for entry in dataObjEntries2:
        print(f"entry is: {entry}")
        stuffToSave = { "album": entry["name"], "pre-rank": entry["pre_rank"], "peak": entry["peak_rank"], "peak_day": entry["peak_date"], "rank": entry["rank"] }
        print(f"stuff to save is: {stuffToSave}")
        relevant_details.append(stuffToSave)
    
    print(f"value of relevant_dtails is: {relevant_details}")

    if "working_notes" not in current_state:
        current_state["working_notes"] = {}
    
    if f"charts_data for {artist_id}" not in current_state["working_notes"]:
        current_state["working_notes"][f"charts_data for {artist_id}"] = {}
    
    current_state["working_notes"][f"charts_data for {artist_id}"][chart_type] = relevant_details
    await ctx.store.set('state', current_state)

    return {
    "artist_id": artist_id,
    "chart_data": relevant_details
}





#and that code which allows logging of every step of the memory/thought process

#keep teh cahce of chartmetric api, attached to function that gets api_key, which is inserted into each relevant api
#find_artist_id_for_artist_tool = FunctionTool.from_function(find_artist_id_for_artist)
#get_instagram_audience_stats_tool = FunctionTool.from_function(get_instagram_audience_stats)
#get_similar_artists = FunctionTool.from_function(get_similar_artists)


# Wrap your function
#find_artist_id_for_artist_tool = FunctionTool(fn=find_artist_id_for_artist)
#get_instagram_audience_stats_tool = FunctionTool(fn=get_instagram_audience_stats)
#get_similar_artists_tool = FunctionTool(fn=get_similar_artists)

manager_agent = ReActAgent(
    name="ManagerAgent",
    description="Manager agent decides which other agents to use, and is decision maker",
    system_prompt=(
    "You are the manager agent. You do not collect data yourself. You delegate tasks to other agents.\n\n"
    "Your responsibilities are:\n"
    "- Receive the user’s question\n"
    "- Decide whether StreamingChartAgent or SocialMediaDataAgent or SimilarityAgent (or two or all) should handle the request\n"
    "+ If the question is about social media audience data (TikTok, Instagram, YouTube), use SocialMediaDataAgent."
"+ If the question is about chart positions, chart history, or streaming rankings, use StreamingChartAgent."
    "- Wait for their responses and evaluate whether the question has been sufficiently answered\n"
),
    llm=llm,
    can_handoff_to=["SocialMediaDataAgent", "SimilarityAgent", "StreamingChartAgent"]
)

streaming_chart_agent = ReActAgent(
    name="StreamingChartAgent",
    description="agent to retrieve streaming chart data for the artist being researched",
    system_prompt=("You are a research agent that retrieves streaming chart information about an artist"),
    llm=llm,
    tools=[get_charts, find_artist_id_for_artist],
    can_handoff_to=["ManagerAgent", "SimilarityAgent", "SocialMediaDataAgent"]
)


social_media_data_agent = ReActAgent(#try with Function Agents first, change to ReAct agents if needed/performance is poor.
    name="SocialMediaDataAgent",
    description="agent to source data about artists from social media data, using chartmetric api",
    system_prompt=(
    "You are a research agent that uses social media data to analyze artist audiences via Chartmetric.\n"
    "- Always use **both** Instagram and TikTok and Youtube data as your default behavior when analyzing artists.\n"
    "- Do NOT choose one over the other unless explicitly told to focus on one.\n"
    "- Always call 'get_instagram_audience_stats' AND 'get_tiktok_audience_data' AND 'get_youtube_audience_data' when gathering audience data.\n"
    "- Do NOT assume artist names. Only use 'find_artist_id_for_artist' with real artist names provided by the user.\n"
    "- If the user needs information about similar artists, HAND OFF to the SimilarityAgent β€” do NOT attempt it yourself.\n"
    "- Your tools are only for Instagram and TikTok and Youtube data.\n"
)
,
    llm=llmHigher,
    tools=[get_instagram_audience_data, find_artist_id_for_artist, get_tiktok_audience_data, get_youtube_audience_data],
    can_handoff_to=["ManagerAgent", "SimilarityAgent", "StreamingChartAgent"]#allow it to handoff to all other agents
)

streaming_chart_agent = ReActAgent(
    name="StreamingChartAgent",
    description="agent to retrieve streaming chart data for the artist being researched",
    system_prompt=("You are a research agent that retrieves streaming chart information about an artist"),
    llm=llm,
    tools=[get_charts, find_artist_id_for_artist],
    can_handoff_to=["ManagerAgent", "SimilarityAgent", "SocialMediaDataAgent"]
)

similarity_agent = ReActAgent(
    name="SimilarityAgent",
    description="agent to find similar artists to the artist being research, using chartmetric api",
    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."
    "you can handoff to SocialMediaDataAgent, in order to find information about the followers of similar artists"
    ),
    llm=llm,
    tools=[get_similar_artists, find_artist_id_for_artist],
    can_handoff_to=["ManagerAgent", "SocialMediaDataAgent", "StreamingChartAgent"]
)







async def main(chosen_artist, prompt):
    #response = await workflow.run(user_msg="What is Bertie Blackman's Chartmetric artist ID?"
#, ctx=ctx) python llamaOaAgent.py
    #chosen_artist = "Kenan Doğulu"

    with open(r"overall_answersGemini.txt", "r", encoding="utf-8") as file:
        contents = file.read()
    
    overall_answers = contents



    final_prompt = prompt + f"This report is about artist {chosen_artist}" + f"your sole data source is: {overall_answers}"
    ##that should ensure that whatever prompt is entered, the correct artist and data source is still passed down.

    def count_tokens(text, model="gpt-4o"):
        encoding = tiktoken.encoding_for_model(model)
        return len(encoding.encode(text))


    #count tokens anyway, for later usage:
    total_tokens = count_tokens(final_prompt)
    print(f"Total tokens of prompt: {total_tokens}")

    
    
    
    model = genai.GenerativeModel("models/gemini-2.5-pro")

# Generate content
    responseGemini = model.generate_content(f"You are a precise music industry data analyst. Be structured, factual, and preserve all stats given. use: {final_prompt}")
    two_pager_gemini = responseGemini.text


    print(responseGemini.text)

  
   
    

    
    return two_pager_gemini


demo = gr.Interface(
    fn=main,
    inputs=["text", "text"], #one for artist_name, other for prompt
    outputs="text",
    title="artist report generator",
    description="generate report for artist"
)

demo.launch(share=True)

#if __name__ == "__main__":
    #response = asyncio.run(main())
    #then pass to llm to assemble formal response to formal questions

# FunctionAgent works for LLMs with a function calling API.
# ReActAgent works for any LLM.



#can check logs:
#async for ev in handler.stream_events():
    #if isinstance(ev, ToolCallResult):
        #print("")
        #print("Called tool: ", ev.tool_name, ev.tool_kwargs, "=>", ev.tool_output)
    #elif isinstance(ev, AgentStream):  # showing the thought process
        #print(ev.delta, end="", flush=True)