spotify-analytics-core 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- spotify_analytics_core-0.1.0.dist-info/METADATA +35 -0
- spotify_analytics_core-0.1.0.dist-info/RECORD +36 -0
- spotify_analytics_core-0.1.0.dist-info/WHEEL +4 -0
- spotify_analytics_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- spotify_core/__init__.py +0 -0
- spotify_core/agent/__init__.py +0 -0
- spotify_core/agent/graph.py +26 -0
- spotify_core/agent/nodes.py +131 -0
- spotify_core/agent/playback_tools.py +22 -0
- spotify_core/agent/prompts.py +33 -0
- spotify_core/agent/resources.py +27 -0
- spotify_core/agent/schemas.py +57 -0
- spotify_core/agent/state.py +14 -0
- spotify_core/agent/tools.py +311 -0
- spotify_core/config.py +65 -0
- spotify_core/db/__init__.py +1 -0
- spotify_core/db/errors.py +18 -0
- spotify_core/db/migrations.py +137 -0
- spotify_core/db/pipeline.py +426 -0
- spotify_core/db/queries.py +480 -0
- spotify_core/db/schema.py +48 -0
- spotify_core/env_file.py +86 -0
- spotify_core/logging.py +80 -0
- spotify_core/memory/__init__.py +4 -0
- spotify_core/memory/checkpointer.py +18 -0
- spotify_core/memory/store.py +37 -0
- spotify_core/paths.py +59 -0
- spotify_core/setup.py +117 -0
- spotify_core/spotify_client/__init__.py +13 -0
- spotify_core/spotify_client/auth.py +178 -0
- spotify_core/spotify_client/client.py +548 -0
- spotify_core/spotify_client/errors.py +25 -0
- spotify_core/spotify_client/pkce.py +46 -0
- spotify_core/spotify_client/token_store.py +187 -0
- spotify_core/spotify_utils/__init__.py +3 -0
- spotify_core/spotify_utils/spotify_facade.py +232 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: spotify-analytics-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Core analytics, agent, and Spotify client library for the Spotify AI Analytics project.
|
|
5
|
+
Project-URL: Homepage, https://github.com/wcnoname5/spotify-ai-analytics
|
|
6
|
+
Project-URL: Repository, https://github.com/wcnoname5/spotify-ai-analytics
|
|
7
|
+
Project-URL: Issues, https://github.com/wcnoname5/spotify-ai-analytics/issues
|
|
8
|
+
Author: WC Chang
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: analytics,listening-history,mcp,spotify
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Requires-Dist: cryptography>=42.0
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Requires-Dist: langgraph-checkpoint-sqlite>=3.0.3
|
|
22
|
+
Requires-Dist: platformdirs>=4.0
|
|
23
|
+
Requires-Dist: pydantic-settings>=2.0
|
|
24
|
+
Requires-Dist: pydantic>=2.0
|
|
25
|
+
Requires-Dist: python-dotenv>=1.0
|
|
26
|
+
Provides-Extra: agent
|
|
27
|
+
Requires-Dist: langchain-core>=1.0; extra == 'agent'
|
|
28
|
+
Requires-Dist: langchain-google-genai>=4.0; extra == 'agent'
|
|
29
|
+
Requires-Dist: langchain-openai>=1.0; extra == 'agent'
|
|
30
|
+
Requires-Dist: langgraph>=1.0; extra == 'agent'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# spotify-analytics-core
|
|
34
|
+
|
|
35
|
+
Core analytics, agent, database, and Spotify client library for Spotify AI Analytics.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
spotify_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
spotify_core/config.py,sha256=seifcK5xXvM3V0QJq8ecn8qIqEtwMl3G4wgKlyaVMKk,2546
|
|
3
|
+
spotify_core/env_file.py,sha256=bC1mr31EO2S6sI17w3MAQD3X7RpZVRJ2eAWjxtgiblY,2878
|
|
4
|
+
spotify_core/logging.py,sha256=mrte60h6ra9psMkMVHEFsrJuP_2X_1jCMegsUxWdorg,2499
|
|
5
|
+
spotify_core/paths.py,sha256=KjouqkOIbqIeYjDbPJJ1Gcox9rVB03GxspMXqbL-lUA,1590
|
|
6
|
+
spotify_core/setup.py,sha256=QP9padSIATZSXe2Oye_K0SyO4pkJzABXLFuT6wmgLCk,4566
|
|
7
|
+
spotify_core/agent/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
spotify_core/agent/graph.py,sha256=WvgbwNEG006SeGQgZPOcfDzV4AK-V_4cXMdKbVhmrrA,1222
|
|
9
|
+
spotify_core/agent/nodes.py,sha256=o0srMp3ZPvoVCpgF5-8lQf-uL4Gb3Hz8Zk9yNjiQx8w,6585
|
|
10
|
+
spotify_core/agent/playback_tools.py,sha256=vtxB2dMPyVgFuaoD-zDxlijZP7Rdzu3LThiAhvmc75A,746
|
|
11
|
+
spotify_core/agent/prompts.py,sha256=az4b_llzVh8wk5PDgR1CMG2t8aM6IFZvnZP8rH_k5ng,2105
|
|
12
|
+
spotify_core/agent/resources.py,sha256=rzOkkFSxKJMZA3D65wC5gzFCskWM2m6KY33DkCM4ueU,1087
|
|
13
|
+
spotify_core/agent/schemas.py,sha256=F7LdAZGu1N8umdYX4PgQpDSNyOLckVcQ_-UNDzYWDhE,2732
|
|
14
|
+
spotify_core/agent/state.py,sha256=ahXcbqaBY5iP34rEaUbjtPlsKHjrE05zY_Ac20jr2vY,632
|
|
15
|
+
spotify_core/agent/tools.py,sha256=-lh39ln5tG9w_iP87Da8faSreA-9GzpbNO2k7M31i6U,11973
|
|
16
|
+
spotify_core/db/__init__.py,sha256=2wKS-0KhjioLAhBYUWTniTXOPA18n6tp0SvRM0lZJGY,47
|
|
17
|
+
spotify_core/db/errors.py,sha256=Kawc5r7GVE2TlrNj0Yr5kjJyJJDgNpQVtuw2SkiJApg,640
|
|
18
|
+
spotify_core/db/migrations.py,sha256=_4Ff8-CzMZCMIJgFpzpJzYk-CfP-Glg5tt6P_DYEjJI,5167
|
|
19
|
+
spotify_core/db/pipeline.py,sha256=oL8J_4VpeXvU2jB292poU30kSrkF8uDjhoppMadsiyc,17728
|
|
20
|
+
spotify_core/db/queries.py,sha256=Mw0Pf3QzvkjWfR7QjCAux_Mrmu7h5fbpEr2SQR254nM,17887
|
|
21
|
+
spotify_core/db/schema.py,sha256=5JuGXxqeEtVjKKoftayE4Fwpp9OySbFHnvNEI4x6wrg,1483
|
|
22
|
+
spotify_core/memory/__init__.py,sha256=isy_D7NZhGQ9W7QT_JjOdxWReqLRiFt_zXhuJpa712M,159
|
|
23
|
+
spotify_core/memory/checkpointer.py,sha256=X78RTuZ2Q7kEWWflMmKRFKndmCTIuBeKLMo60Qp-XE4,555
|
|
24
|
+
spotify_core/memory/store.py,sha256=beJXU8lCu3dw6pxVOGrG12t-COT7Ynjd4eue91X6Tas,1060
|
|
25
|
+
spotify_core/spotify_client/__init__.py,sha256=1f7y7Gh0HkpGG0jYwyD0nUQRu7gShBv1his2Bm7DPzc,257
|
|
26
|
+
spotify_core/spotify_client/auth.py,sha256=m_azR8_Lv0gt41y2EZlVGNRJIaOYo1a9GF3sBQy4jtg,5885
|
|
27
|
+
spotify_core/spotify_client/client.py,sha256=wyfJEy94ZkTHJqQ2ZIW5ivPzAXV_WxJBxfF7py0HsWQ,20293
|
|
28
|
+
spotify_core/spotify_client/errors.py,sha256=A4gd34DgoHiKqUp2t9enqRiLqJuYPbIMebE0s08dGA4,794
|
|
29
|
+
spotify_core/spotify_client/pkce.py,sha256=EWEtHfyiU2cVc7OKCGguKXEQCiiCccR688VCzceaKyg,1497
|
|
30
|
+
spotify_core/spotify_client/token_store.py,sha256=Oq9KpjxpGyZC2YiMKvEnG0S0T-Y3FGiW_vUZkCfNRfw,5887
|
|
31
|
+
spotify_core/spotify_utils/__init__.py,sha256=CW5_s5oDFvpIDUot31qTxv-s5aXs0U4sZFeaMWQl5Go,79
|
|
32
|
+
spotify_core/spotify_utils/spotify_facade.py,sha256=mKxFD5tBGfM9gfTVyWG8DPdzUVQAg9_Y8iPseNSD3Ko,9280
|
|
33
|
+
spotify_analytics_core-0.1.0.dist-info/METADATA,sha256=C-g-3QivlgkgFUIVDV_Jjxh7uBQ36CcbLrOfeIY30EM,1444
|
|
34
|
+
spotify_analytics_core-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
35
|
+
spotify_analytics_core-0.1.0.dist-info/licenses/LICENSE,sha256=8OYV8_GXjvn_R1sxgJXYpbhLWc_b6Q33dRIwu54gBwM,1065
|
|
36
|
+
spotify_analytics_core-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 WC Chang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
spotify_core/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from langgraph.graph import StateGraph, END
|
|
3
|
+
from .state import AgentState
|
|
4
|
+
from .nodes import make_nodes
|
|
5
|
+
|
|
6
|
+
def build_app(llm, tools_list: list, checkpointer=None, store=None):
|
|
7
|
+
"""Build and compile the LangGraph workflow.
|
|
8
|
+
|
|
9
|
+
Args:
|
|
10
|
+
llm: LangChain LLM instance (ChatOpenAI or ChatGoogleGenerativeAI)
|
|
11
|
+
tools_list: List of LangChain tools from initialize_tools()
|
|
12
|
+
checkpointer: Optional SqliteSaver for short-term per-thread memory.
|
|
13
|
+
store: Optional SqliteStore for long-term cross-session memory.
|
|
14
|
+
"""
|
|
15
|
+
tool_executor = {t.name: t for t in tools_list}
|
|
16
|
+
intent_parser, data_fetch, analyst_node, should_continue = make_nodes(llm, tools_list, tool_executor)
|
|
17
|
+
|
|
18
|
+
workflow = StateGraph(AgentState)
|
|
19
|
+
workflow.add_node("IntentParser", intent_parser)
|
|
20
|
+
workflow.add_node("ToolExecute", data_fetch)
|
|
21
|
+
workflow.add_node("Analyst", analyst_node)
|
|
22
|
+
workflow.set_entry_point("IntentParser")
|
|
23
|
+
workflow.add_conditional_edges("IntentParser", should_continue, {"continue": "ToolExecute", "end": "Analyst"})
|
|
24
|
+
workflow.add_edge("ToolExecute", "Analyst")
|
|
25
|
+
workflow.add_edge("Analyst", END)
|
|
26
|
+
return workflow.compile(checkpointer=checkpointer, store=store)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Dict, Any, List
|
|
5
|
+
from langchain_core.messages import ToolMessage, AIMessage
|
|
6
|
+
|
|
7
|
+
from .state import AgentState
|
|
8
|
+
from .schemas import IntentPlan, ToolPlan
|
|
9
|
+
from .prompts import INTENT_PARSER_SYSTEM_PROMPT
|
|
10
|
+
|
|
11
|
+
def make_nodes(llm, tools_list: list, tool_executor: dict):
|
|
12
|
+
"""Factory that returns graph node functions bound to the given resources via closure."""
|
|
13
|
+
|
|
14
|
+
def intent_parser(state: AgentState) -> Dict[str, Any]:
|
|
15
|
+
"""Parse the user's intent and generate a strategic execution plan."""
|
|
16
|
+
logger = logging.getLogger(f'{__name__}.intent_parser')
|
|
17
|
+
logger.info(f"Planning for input: {state['input']}")
|
|
18
|
+
|
|
19
|
+
if llm is None:
|
|
20
|
+
error_msg = "AI model not initialized. Please check your API key."
|
|
21
|
+
return {"intent": "other", "messages": [AIMessage(content=error_msg)], "final_response": error_msg}
|
|
22
|
+
|
|
23
|
+
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
24
|
+
full_system_prompt = INTENT_PARSER_SYSTEM_PROMPT + f"\n\nCurrent date and time: {now}."
|
|
25
|
+
plan = llm.with_structured_output(IntentPlan).invoke([
|
|
26
|
+
{"role": "system", "content": full_system_prompt},
|
|
27
|
+
{"role": "user", "content": state["input"]}
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
if not plan:
|
|
31
|
+
raise ValueError("Failed to parse intent plan.")
|
|
32
|
+
|
|
33
|
+
logger.info(f"Intent parsed: {plan.intent_type} | Tools: {[tp.tool_name for tp in plan.tool_plan]}")
|
|
34
|
+
return {"intent": plan.intent_type, "plan": plan, "messages": [AIMessage(content=f"Strategy: {plan.reasoning}")]}
|
|
35
|
+
|
|
36
|
+
def data_fetch(state: AgentState) -> Dict[str, Any]:
|
|
37
|
+
"""Execute tools based on the plan."""
|
|
38
|
+
logger = logging.getLogger(f'{__name__}.data_fetch')
|
|
39
|
+
plan = state.get("plan")
|
|
40
|
+
if not plan or not plan.tool_plan:
|
|
41
|
+
return {"messages": []}
|
|
42
|
+
|
|
43
|
+
planned_tool_names = [tp.tool_name for tp in plan.tool_plan]
|
|
44
|
+
available_tools = [t for t in tools_list if t.name in planned_tool_names]
|
|
45
|
+
if not available_tools:
|
|
46
|
+
return {"messages": [AIMessage(content="Planned tools are unavailable.")]}
|
|
47
|
+
|
|
48
|
+
llm_with_tools = llm.bind_tools(available_tools)
|
|
49
|
+
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
50
|
+
response = llm_with_tools.invoke([
|
|
51
|
+
{"role": "system", "content": f"You are a Spotify Tool Specialist. Context: {plan.reasoning}. Time: {now}. Only call provided tools."},
|
|
52
|
+
{"role": "user", "content": state["input"]}
|
|
53
|
+
])
|
|
54
|
+
|
|
55
|
+
results, tool_messages = [], []
|
|
56
|
+
if hasattr(response, 'tool_calls') and response.tool_calls:
|
|
57
|
+
tool_messages.append(response)
|
|
58
|
+
for i, tool_call in enumerate(response.tool_calls):
|
|
59
|
+
tool_name = tool_call["name"]
|
|
60
|
+
if tool_name not in planned_tool_names:
|
|
61
|
+
logger.warning(f"Hallucinated tool call: {tool_name}")
|
|
62
|
+
continue
|
|
63
|
+
tool_obj = tool_executor.get(tool_name)
|
|
64
|
+
if tool_obj is None:
|
|
65
|
+
logger.error(f"Tool '{tool_name}' in plan but not in executor. Skipping.")
|
|
66
|
+
continue
|
|
67
|
+
call_id = tool_call.get("id", f"call_{i}")
|
|
68
|
+
retrieved_data, last_error = None, None
|
|
69
|
+
for attempt in range(3):
|
|
70
|
+
try:
|
|
71
|
+
retrieved_data = tool_obj.invoke(tool_call["args"])
|
|
72
|
+
break
|
|
73
|
+
except Exception as e:
|
|
74
|
+
last_error = str(e)
|
|
75
|
+
if attempt == 2:
|
|
76
|
+
retrieved_data = f"Error after 3 attempts: {last_error}"
|
|
77
|
+
obs_str = str(retrieved_data)
|
|
78
|
+
if len(obs_str) > 1000:
|
|
79
|
+
obs_str = obs_str[:1000] + "... [truncated]"
|
|
80
|
+
tool_messages.append(ToolMessage(content=obs_str, name=tool_name, tool_call_id=call_id))
|
|
81
|
+
results.append(retrieved_data)
|
|
82
|
+
logger.info(f"Tool {tool_name}: success={last_error is None}")
|
|
83
|
+
return {"messages": tool_messages, "tool_results": results}
|
|
84
|
+
|
|
85
|
+
def analyst_node(state: AgentState) -> Dict[str, Any]:
|
|
86
|
+
"""Synthesize the final response."""
|
|
87
|
+
logger = logging.getLogger(f'{__name__}.analyst_node')
|
|
88
|
+
if state.get("final_response"):
|
|
89
|
+
return {"final_response": state["final_response"]}
|
|
90
|
+
|
|
91
|
+
intent = state.get("intent", "other")
|
|
92
|
+
plan = state.get("plan")
|
|
93
|
+
|
|
94
|
+
system_prompts = {
|
|
95
|
+
"factual_query": "You are a Spotify analytics assistant. Be direct, use bullet points.",
|
|
96
|
+
"insight_analysis": f"You are a Spotify music critic. Tell a story. Focus: {plan.analysis_focus if plan else ''}",
|
|
97
|
+
"recommendation": "You are a Spotify recommendation expert. Suggest music based on listening history.",
|
|
98
|
+
}
|
|
99
|
+
system_prompt = system_prompts.get(intent, "You are a Spotify analytics assistant.")
|
|
100
|
+
|
|
101
|
+
tool_messages = [m for m in state.get("messages", []) if isinstance(m, ToolMessage)]
|
|
102
|
+
|
|
103
|
+
if intent == "other" and (not plan or not plan.tool_plan):
|
|
104
|
+
response_content = plan.reasoning if plan else "I'm a Spotify analytics assistant and can't help with that."
|
|
105
|
+
else:
|
|
106
|
+
data_str = ""
|
|
107
|
+
if tool_messages:
|
|
108
|
+
tool_results = state.get("tool_results", [])
|
|
109
|
+
for i, msg in enumerate(tool_messages):
|
|
110
|
+
result = tool_results[i] if i < len(tool_results) else msg.content
|
|
111
|
+
formatted = json.dumps(result, indent=2) if isinstance(result, (list, dict)) else str(result)
|
|
112
|
+
data_str += f"### Tool: {getattr(msg, 'name', f'Tool_{i}')}\n{formatted}\n\n"
|
|
113
|
+
|
|
114
|
+
messages = [{"role": "system", "content": system_prompt}]
|
|
115
|
+
if data_str:
|
|
116
|
+
messages.append({"role": "user", "content": f"Spotify data:\n<data>\n{data_str}\n</data>"})
|
|
117
|
+
messages.append({"role": "user", "content": f"Address my request: {state['input']}"})
|
|
118
|
+
response_content = llm.invoke(messages).content
|
|
119
|
+
|
|
120
|
+
logger.info(f"[Monitoring] Node: analyst_node | Intent: {intent} | Tools Used: {len(tool_messages) > 0}")
|
|
121
|
+
logger.info(f"Final response length: {len(response_content)}")
|
|
122
|
+
return {"final_response": response_content}
|
|
123
|
+
|
|
124
|
+
def should_continue(state: AgentState) -> str:
|
|
125
|
+
"""Route: continue to ToolExecute or go to Analyst."""
|
|
126
|
+
plan = state.get("plan")
|
|
127
|
+
if plan and plan.tool_plan:
|
|
128
|
+
return "continue"
|
|
129
|
+
return "end"
|
|
130
|
+
|
|
131
|
+
return intent_parser, data_fetch, analyst_node, should_continue
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""LangChain-wrapped playback tools for agent integration."""
|
|
2
|
+
from langchain_core.tools import tool
|
|
3
|
+
|
|
4
|
+
from ..spotify_utils.spotify_facade import SpotifyToolFacade
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AgentPlaybackTools(SpotifyToolFacade):
|
|
8
|
+
"""SpotifyPlaybackTools with LangChain tool wrapping for agent integration."""
|
|
9
|
+
|
|
10
|
+
def get_tools(self) -> list:
|
|
11
|
+
"""Return all playback/sync methods as LangChain tools."""
|
|
12
|
+
return [
|
|
13
|
+
tool(self.get_now_playing),
|
|
14
|
+
tool(self.get_devices),
|
|
15
|
+
tool(self.play_track),
|
|
16
|
+
tool(self.pause),
|
|
17
|
+
tool(self.skip),
|
|
18
|
+
tool(self.set_volume),
|
|
19
|
+
tool(self.add_to_queue),
|
|
20
|
+
tool(self.create_playlist),
|
|
21
|
+
tool(self.sync_recent_history),
|
|
22
|
+
]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
INTENT_PARSER_SYSTEM_PROMPT = """
|
|
2
|
+
You are a Spotify Data Assistant Orchestrator.
|
|
3
|
+
Your job is to:
|
|
4
|
+
1. Understand the user's request.
|
|
5
|
+
2. Select the most appropriate tools from the list below to fetch necessary data.
|
|
6
|
+
3. Classify the user's intent to guide the downstream analyst.
|
|
7
|
+
|
|
8
|
+
### Available Tools:
|
|
9
|
+
- **get_summary_stats**: Get overall listening summary (total records, time, date range).
|
|
10
|
+
- **get_top_artists**: Get top artists by listening time. Supports date range and limit.
|
|
11
|
+
- **get_top_tracks**: Get top tracks by play count. Supports artist filter, date range, and limit.
|
|
12
|
+
- **free_query**: Execute complex filtering on raw data (e.g., filter by specific day, hour, or multiple fields).
|
|
13
|
+
- **free_aggregate**: Perform custom aggregations (e.g., grouping by month, track, or artist with custom metrics).
|
|
14
|
+
3. Classify the user's intent to guide the downstream analyst.
|
|
15
|
+
|
|
16
|
+
### Tool Selection Guidelines:
|
|
17
|
+
- **ALWAYS prioritize specific tools** (`get_top_artists`, `get_summary_stats`) over generic ones.
|
|
18
|
+
- Use `free_query` or `free_aggregate` ONLY when the request involves complex filtering that standard tools cannot handle.
|
|
19
|
+
- If the user asks for "Recommendations", you usually need to fetch their `get_top_artists` and `get_top_tracks` first as a baseline.
|
|
20
|
+
- You only need to provide the `tool_name` and `reasoning`. Downstream execution logic will handle the specific arguments.
|
|
21
|
+
|
|
22
|
+
### Intent Classification Guidelines:
|
|
23
|
+
- **factual_query**: The user wants raw numbers, lists, or specific facts. (e.g., "Count of my tracks", "Top 5 songs")
|
|
24
|
+
- **insight_analysis**: The user asks about habits, trends, or "Why/How". (e.g., "Am I listening to sadder music?", "Compare my listening between 2023 and 2024")
|
|
25
|
+
- **recommendation**: The user explicitly asks for new music suggestions.
|
|
26
|
+
- **other**: Greetings or questions unrelated to Spotify data.
|
|
27
|
+
|
|
28
|
+
### Output Format:
|
|
29
|
+
You must call the relevant tools (if any) AND return the intent classification structure.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
# TODO: Implement dynamic injection of tool docstrings into INTENT_PARSER_SYSTEM_PROMPT
|
|
33
|
+
# for better maintainability and accuracy as tool schemas evolve.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Pure resource factory. No Streamlit dependency."""
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Optional, Tuple
|
|
4
|
+
from langchain_openai import ChatOpenAI
|
|
5
|
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
|
6
|
+
from spotify_dataloader import SpotifyDataLoader
|
|
7
|
+
from .tools import initialize_tools
|
|
8
|
+
from ..config import settings
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
def build_llm(provider: str, api_key: str):
|
|
13
|
+
"""Build LLM instance from provider name and API key."""
|
|
14
|
+
if provider.lower() == "gemini":
|
|
15
|
+
return ChatGoogleGenerativeAI(model=settings.gemini_model, google_api_key=api_key, temperature=0)
|
|
16
|
+
return ChatOpenAI(model=settings.openai_model, api_key=api_key, temperature=0)
|
|
17
|
+
|
|
18
|
+
def build_resources(provider: str, api_key: str, loader: Optional[SpotifyDataLoader] = None):
|
|
19
|
+
"""Build LLM, tools list, and tool executor dict.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
(llm, tools_list, tool_executor) tuple
|
|
23
|
+
"""
|
|
24
|
+
llm = build_llm(provider, api_key)
|
|
25
|
+
tools_list = initialize_tools(loader=loader)
|
|
26
|
+
tool_executor = {t.name: t for t in tools_list}
|
|
27
|
+
return llm, tools_list, tool_executor
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import pydantic
|
|
2
|
+
from typing import List, Optional, Any, Dict, Literal
|
|
3
|
+
from pydantic import Field
|
|
4
|
+
|
|
5
|
+
class ToolPlan(pydantic.BaseModel):
|
|
6
|
+
"""Plan for a single tool execution."""
|
|
7
|
+
tool_name: Literal[
|
|
8
|
+
"get_summary_stats",
|
|
9
|
+
"get_top_artists",
|
|
10
|
+
"get_top_tracks",
|
|
11
|
+
"free_query",
|
|
12
|
+
"free_aggregate"
|
|
13
|
+
] = Field(
|
|
14
|
+
...,
|
|
15
|
+
description="Name of the tool to be executed"
|
|
16
|
+
)
|
|
17
|
+
reasoning: str = Field(
|
|
18
|
+
default="",
|
|
19
|
+
description="Reasoning for why this tool is selected"
|
|
20
|
+
)
|
|
21
|
+
args: Optional[Dict[str, Any]] = Field(
|
|
22
|
+
default_factory=dict,
|
|
23
|
+
description="Arguments for the tool (Optional, will be refined by downstream node)"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
class IntentPlan(pydantic.BaseModel):
|
|
27
|
+
"""Execution plan generated by the Planner node."""
|
|
28
|
+
intent_type: Literal["factual_query", "insight_analysis", "recommendation", "other"] = Field(
|
|
29
|
+
...,
|
|
30
|
+
description="The category of the user's request."
|
|
31
|
+
)
|
|
32
|
+
reasoning: str = Field(..., description="Brief reason why this intent was chosen.")
|
|
33
|
+
analysis_focus: str = Field(
|
|
34
|
+
default="",
|
|
35
|
+
description="If intent is analysis, what specific patterns should be looked at?"
|
|
36
|
+
)
|
|
37
|
+
tool_plan: List[ToolPlan] = Field(
|
|
38
|
+
default_factory=list,
|
|
39
|
+
description="Planned tools to execute in order"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
class ToolFreeQueryArgs(pydantic.BaseModel):
|
|
43
|
+
"""Arguments for the free_query tool."""
|
|
44
|
+
where: Optional[str] = pydantic.Field(None, description="Polars filter expression as a string, e.g., \"pl.col('artist') == 'Taylor Swift'\"")
|
|
45
|
+
select: Optional[List[str]] = pydantic.Field(None, description="List of column names to include")
|
|
46
|
+
limit: Optional[int] = pydantic.Field(None, description="Maximum number of rows to return")
|
|
47
|
+
sort_by: Optional[str] = pydantic.Field(None, description="Column name to sort by")
|
|
48
|
+
descending: bool = pydantic.Field(True, description="Whether to sort in descending order")
|
|
49
|
+
|
|
50
|
+
class ToolFreeAggrgateArgs(pydantic.BaseModel):
|
|
51
|
+
"""Arguments for the free_aggregate tool."""
|
|
52
|
+
group_by: List[str] = pydantic.Field(..., description="List of column names to group by")
|
|
53
|
+
metrics: Dict[str, Any] = pydantic.Field(..., description="Dictionary mapping columns to aggregation functions (sum, mean, count, n_unique). Value can be a string or a (function, alias) tuple.")
|
|
54
|
+
where: Optional[str] = pydantic.Field(None, description="Polars filter expression as a string")
|
|
55
|
+
sort_by: Optional[str] = pydantic.Field(None, description="Column name to sort by")
|
|
56
|
+
descending: bool = pydantic.Field(True, description="Whether to sort in descending order")
|
|
57
|
+
limit: Optional[int] = pydantic.Field(None, description="Maximum number of rows to return")
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import operator
|
|
2
|
+
from typing import TypedDict, List, Literal, Annotated, Sequence, Optional, Any
|
|
3
|
+
from langchain_core.messages import BaseMessage
|
|
4
|
+
from .schemas import IntentPlan
|
|
5
|
+
|
|
6
|
+
class AgentState(TypedDict):
|
|
7
|
+
input: str
|
|
8
|
+
messages: Annotated[Sequence[BaseMessage], operator.add]
|
|
9
|
+
intent: Optional[Literal['factual_query', 'insight_analysis', 'recommendation', 'other',
|
|
10
|
+
'playback_control', 'playlist_create', 'sync_history']]
|
|
11
|
+
plan: Optional[IntentPlan]
|
|
12
|
+
tool_results: List[Optional[Any]] # e.g., the queries and their results
|
|
13
|
+
final_response: Optional[str]
|
|
14
|
+
retry_count: Optional[int]
|