sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/coordinator_agent.py
from agno.team.team import Team from agno.agent import Agent, RunResponse from agno.models.together import Together from agents.facial_expression_agent import facial_expression_agent from agents.voice_analysis_agent import voice_analysis_agent from agents.content_analysis_agent import content_analysis_agent from agents.feedback_agent import feedback_agent import os from pydantic import BaseModel, Field # Structured response class CoordinatorResponse(BaseModel): facial_expression_response: str = Field(..., description="Response from facial expression agent") voice_analysis_response: str = Field(..., description="Response from voice analysis agent") content_analysis_response: str = Field(..., description="Response from content analysis agent") feedback_response: str = Field(..., description="Response from feedback agent") strengths: list[str] = Field(..., description="List of speaker's strengths") weaknesses: list[str] = Field(..., description="List of speaker's weaknesses") suggestions: list[str] = Field(..., description="List of suggestions for speaker to improve") # Initialize a team of agents coordinator_agent = Team( name="coordinator-agent", mode="coordinate", model=Together(id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY")), members=[facial_expression_agent, voice_analysis_agent, content_analysis_agent, feedback_agent], description="You are a public speaking coach who helps individuals improve their presentation skills through feedback and analysis.", instructions=[ "You will be provided with a video file of a person speaking in a public setting.", "You will analyze the speaker's facial expressions, voice modulation, and content delivery to provide constructive feedback.", "Ask the facial expression agent to analyze the video file to detect emotions and engagement.", "Ask the voice analysis agent to analyze the audio file to detect speech rate, pitch variation, and volume consistency.", "Ask the content analysis agent to analyze the transcript given by voice analysis agent for structure, clarity, and filler words.", "Ask the feedback agent to evaluate the analysis results from the facial expression agent, voice analysis agent, and content analysis agent to provide feedback on the overall effectiveness of the presentation, highlighting strengths and areas for improvement.", "Your response MUST include the exact responses from the facial expression agent, voice analysis agent, content analysis agent, and feedback agent.", "Additionally, your response MUST provide lists of the speaker's strengths, weaknesses, and suggestions for improvement based on all the responses and feedback provided by the feedback agent.", "Important: You MUST directly address the speaker while providing strengths, weaknesses, and suggestions for improvement in a clear and constructive manner.", "The response MUST be in the following strict JSON format:", "{", '"facial_expression_response": [facial_expression_agent_response],', '"voice_analysis_response": [voice_analysis_agent_response],', '"content_analysis_response": [content_analysis_agent_response],', '"feedback_response": [feedback_agent_response]', '"strengths": [speaker_strengths_list],', '"weaknesses": [speaker_weaknesses_list],', '"suggestions": [suggestions_for_improvement_list]', "}", "The response MUST be in strict JSON format with keys and values in double quotes.", "The values in the JSON response MUST NOT be null or empty.", "The final response MUST not include any other text or anything else other than the JSON response.", "The final response MUST not include any backslashes in the JSON response.", "The final response MUST be a valid JSON object and MUST not have any unterminated strings in the JSON response." ], add_datetime_to_instructions=True, add_member_tools_to_system_message=False, # This can be tried to make the agent more consistently get the transfer tool call correct enable_agentic_context=True, # Allow the agent to maintain a shared context and send that to members. share_member_interactions=True, # Share all member responses with subsequent member requests. show_members_responses=True, response_model=CoordinatorResponse, use_json_mode=True, markdown=True, show_tool_calls=True, debug_mode=True ) # # Example usage # video = "../../videos/my_video.mp4" # prompt = f"Analyze facial expressions, voice modulation, and content delivery in the following video: {video} and provide constructive feedback." # coordinator_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = coordinator_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/coordinator_agent.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/facial_expression_agent.py
from agno.agent import Agent, RunResponse from agno.models.together import Together from agents.tools.facial_expression_tool import analyze_facial_expressions as facial_expression_tool from agno.utils.pprint import pprint_run_response from dotenv import load_dotenv import os load_dotenv() # Define the facial expression agent facial_expression_agent = Agent( name="facial-expression-agent", model=Together(id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY")), tools=[facial_expression_tool], description= ''' You are a facial expression agent that will analyze facial expressions in videos to detect emotions and engagement. You will return the emotion timeline and engagement metrics. ''', instructions=[ "You will be provided with a video file of a person speaking in a public setting.", "Your task is to analyze the facial expressions in the video to detect emotions and engagement.", "You will analyze the video frame by frame to detect and classify facial expressions such as happiness, sadness, anger, surprise, and neutrality.", "You will also analyze the engagement metrics such as eye contact count and smile count", "The response MUST be in the following JSON format:", "{", '"emotion_timeline": [emotion_timeline]', "engagement_metrics: {", '"eye_contact_frequency": [eye contact_frequency]', '"smile_frequency": [smile_frequency]', "}", "}", "The response MUST be in proper JSON format with keys and values in double quotes.", "The final response MUST not include any other text or anything else other than the JSON response.", "The final response MUST not include any backslashes in the JSON response.", "The final response MUST be a valid JSON object and MUST not have any unterminated strings in the JSON response." ], markdown=True, show_tool_calls=True, debug_mode=True ) # video = "../../videos/my_video.mp4" # prompt = f"Analyze facial expressions in the video file to detect emotions and engagement in the following video: {video}" # facial_expression_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = facial_expression_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/facial_expression_agent.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/feedback_agent.py
from agno.agent import Agent from agno.models.together import Together from dotenv import load_dotenv import os load_dotenv() # Define the content analysis agent feedback_agent = Agent( name="feedback-agent", model=Together( id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY") ), description=""" You are a feedback agent that evaluates presentation based on the analysis results from all agents. You will provide feedback on the overall effectiveness of the presentation. """, instructions=[ "You are a public speaking coach that evaluates a speaker's performance based on a detailed scoring rubric.", "You will be provided with analysis results from the facial expression agent, voice analysis agent, and content analysis agent.", "You will be given a criteria to evaluate the performance of the speaker based on the analysis results.", "Your task is to evaluate the speaker on the following 5 criteria, scoring each from 1 (Poor) to 5 (Excellent):", "1. **Content & Organization** - Evaluate how logically structured and well-organized the speech content is.", "2. **Delivery & Vocal Quality** - Assess clarity, articulation, vocal variety, and use of filler words.", "3. **Body Language & Eye Contact** - Consider posture, gestures, and level of eye contact.", "4. **Audience Engagement** - Evaluate enthusiasm and ability to hold the audience's attention.", "5. **Language & Clarity** - Check for grammar, clarity, appropriateness, and impact of language.", "You will then provide a summary of the speaker's strengths and areas for improvement based on the rubric.", "Important: You MUST directly address the speaker while providing constructive feedback.", "Provide your response in the following strict JSON format:", "{", '"scores": {', ' "content_organization": [1-5],', ' "delivery_vocal_quality": [1-5],', ' "body_language_eye_contact": [1-5],', ' "audience_engagement": [1-5],', ' "language_clarity": [1-5]', '},', '"total_score": [sum of all scores from 5 to 25],', '"interpretation": "[One of: \'Needs significant improvement\', \'Developing skills\', \'Competent speaker\', \'Proficient speaker\', \'Outstanding speaker\']",', '"feedback_summary": "[Concise feedback summarizing the speaker\'s strengths and areas for improvement based on rubric.]"', "}", "DO NOT include anything outside the JSON response.", "Ensure all keys and values are properly quoted and formatted.", "The response MUST be in proper JSON format with keys and values in double quotes.", "The final response MUST not include any other text or anything else other than the JSON response." ], markdown=True, show_tool_calls=True, debug_mode=True ) # # Example usage # if __name__ == "__main__": # # Sample transcript from the Voice Analysis Agent # transcript = ( # "So, um, I was thinking that, like, we could actually start the project soon. " # "You know, it's basically ready, and, uh, we just need to finalize some details." # ) # prompt = f"Analyze the following transcript:\n\n{transcript}" # content_analysis_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = content_analysis_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/feedback_agent.py", "license": "Apache License 2.0", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/facial_expression_tool.py
import cv2 import numpy as np import mediapipe as mp from deepface import DeepFace from agno.tools import tool import json def log_before_call(fc): """Pre-hook function that runs before the tool execution""" print(f"About to call function with arguments: {fc.arguments}") def log_after_call(fc): """Post-hook function that runs after the tool execution""" print(f"Function call completed with result: {fc.result}") @tool( name="analyze_facial_expressions", # Custom name for the tool (otherwise the function name is used) description="Analyzes facial expressions to detect emotions and engagement.", # Custom description (otherwise the function docstring is used) show_result=True, # Show result after function call stop_after_tool_call=True, # Return the result immediately after the tool call and stop the agent pre_hook=log_before_call, # Hook to run before execution post_hook=log_after_call, # Hook to run after execution cache_results=False, # Enable caching of results cache_dir="/tmp/agno_cache", # Custom cache directory cache_ttl=3600 # Cache TTL in seconds (1 hour) ) def analyze_facial_expressions(video_path: str) -> dict: """ Analyzes facial expressions in a video to detect emotions and engagement. Args: video_path: The path to the video file. Returns: A dictionary containing the emotion timeline and engagement metrics. """ mp_face_mesh = mp.solutions.face_mesh face_mesh = mp_face_mesh.FaceMesh(static_image_mode=False, max_num_faces=1) cap = cv2.VideoCapture(video_path) emotion_timeline = [] eye_contact_count = 0 smile_count = 0 frame_count = 0 fps = cap.get(cv2.CAP_PROP_FPS) # Process every nth frame for performance optimization frame_interval = 5 while cap.isOpened(): ret, frame = cap.read() if not ret: break frame_count += 1 if frame_count % frame_interval != 0: continue # Resize frame for faster processing frame = cv2.resize(frame, (640, 480)) rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = face_mesh.process(rgb_frame) if results.multi_face_landmarks: for face_landmarks in results.multi_face_landmarks: # Extract landmarks landmarks = face_landmarks.landmark # Convert landmarks to pixel coordinates h, w, _ = frame.shape landmark_coords = [(int(lm.x * w), int(lm.y * h)) for lm in landmarks] # Emotion Detection using DeepFace & Smile Detection try: analysis = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False) emotion = analysis[0]['dominant_emotion'] if emotion == "happy": smile_count += 1 timestamp = frame_count / fps # convert timestamp into seconds timestamp = round(timestamp, 2) emotion_timeline.append({"timestamp": timestamp, "emotion": emotion}) except Exception as e: print(f"Error analyzing frame: {e}") continue # Engagement Metric: Eye contact estimation # Using eye landmarks: 159 (left eye upper lid), 145 (left eye lower lid), 386 (right eye upper lid), 374 (right eye lower lid) left_eye_upper_lid = landmark_coords[159] left_eye_lower_lid = landmark_coords[145] right_eye_upper_lid = landmark_coords[386] right_eye_lower_lid = landmark_coords[374] left_eye_opening = np.linalg.norm(np.array(left_eye_upper_lid) - np.array(left_eye_lower_lid)) right_eye_opening = np.linalg.norm(np.array(right_eye_upper_lid) - np.array(right_eye_lower_lid)) eye_opening_avg = (left_eye_opening + right_eye_opening) / 2 # Simple heuristic: if eyes are wide open, assume eye contact if eye_opening_avg > 5: # Threshold adjustment through experimentation eye_contact_count += 1 cap.release() face_mesh.close() total_processed_frames = frame_count // frame_interval if total_processed_frames == 0: total_processed_frames = 1 # Avoid division by zero return json.dumps({ "emotion_timeline": emotion_timeline, "engagement_metrics": { "eye_contact_frequency": eye_contact_count / total_processed_frames, "smile_frequency": smile_count / total_processed_frames } })
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/facial_expression_tool.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/voice_analysis_tool.py
import os import json import tempfile import numpy as np import librosa from moviepy import VideoFileClip from faster_whisper import WhisperModel from agno.tools import tool from dotenv import load_dotenv load_dotenv() def extract_audio_from_video(video_path: str, output_audio_path: str) -> str: """ Extracts audio from a video file and saves it as an audio file. Args: video_path: Path to the input video file. output_audio_path: Path to save the extracted audio file. Returns: Path to the extracted audio file. """ video_clip = VideoFileClip(video_path) audio_clip = video_clip.audio audio_clip.write_audiofile(output_audio_path) audio_clip.close() video_clip.close() return output_audio_path def load_whisper_model(): try: model = WhisperModel("small", device="cpu", compute_type="int8") return model except Exception as e: print(f"Error loading Whisper model: {e}") return None def transcribe_audio(audio_file): """ Transcribe the audio file using faster-whisper. Returns: str: Transcribed text or error/fallback message. """ if not audio_file or not os.path.exists(audio_file): return "No audio file exists at the specified path." model = load_whisper_model() if not model: return "Model failed to load. Please check system resources or model path." try: print("Model loaded successfully. Transcribing audio...") segments, _ = model.transcribe(audio_file) full_text = " ".join(segment.text for segment in segments) return full_text.strip() if full_text else "I couldn't understand the audio. Please try again." except Exception as e: print(f"Error transcribing audio with faster-whisper: {e}") return "I'm having trouble transcribing your audio. Please try again or speak more clearly." def log_before_call(fc): """Pre-hook function that runs before the tool execution""" print(f"About to call function with arguments: {fc.arguments}") def log_after_call(fc): """Post-hook function that runs after the tool execution""" print(f"Function call completed with result: {fc.result}") @tool( name="analyze_voice_attributes", # Custom name for the tool (otherwise the function name is used) description="Analyzes vocal attributes like clarity, intonation, and pace.", # Custom description (otherwise the function docstring is used) show_result=True, # Show result after function call stop_after_tool_call=True, # Return the result immediately after the tool call and stop the agent pre_hook=log_before_call, # Hook to run before execution post_hook=log_after_call, # Hook to run after execution cache_results=False, # Enable caching of results cache_dir="/tmp/agno_cache", # Custom cache directory cache_ttl=3600 # Cache TTL in seconds (1 hour) ) def analyze_voice_attributes(file_path: str) -> dict: """ Analyzes vocal attributes in an audio file. Args: audio_path: The path to the audio file. Returns: A dictionary containing the transcribed text, speech rate, pitch variation, and volume consistency. """ # Determine file extension _, ext = os.path.splitext(file_path) ext = ext.lower() # If the file is a video, extract audio if ext in ['.mp4']: with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_audio_file: audio_path = extract_audio_from_video(file_path, temp_audio_file.name) else: audio_path = file_path # Transcribe audio transcription = transcribe_audio(audio_path) # Proceed with analysis using the audio_path # Load audio y, sr = librosa.load(audio_path, sr=16000) words = transcription.split() # Calculate speech rate duration = librosa.get_duration(y=y, sr=sr) speech_rate = len(words) / (duration / 60.0) # words per minute # Pitch variation pitches, magnitudes = librosa.piptrack(y=y, sr=sr) pitch_values = pitches[magnitudes > np.median(magnitudes)] pitch_variation = np.std(pitch_values) if pitch_values.size > 0 else 0 # Volume consistency rms = librosa.feature.rms(y=y)[0] volume_consistency = np.std(rms) # Clean up temporary audio file if created if ext in ['.mp4']: os.remove(audio_path) return json.dumps({ "transcription": transcription, "speech_rate_wpm": str(round(speech_rate, 2)), "pitch_variation": str(round(pitch_variation, 2)), "volume_consistency": str(round(volume_consistency, 4)) })
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/tools/voice_analysis_tool.py", "license": "Apache License 2.0", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/voice_analysis_agent.py
from agno.agent import Agent, RunResponse from agno.agent import Agent from agno.models.together import Together from agents.tools.voice_analysis_tool import analyze_voice_attributes as voice_analysis_tool from agno.utils.pprint import pprint_run_response from dotenv import load_dotenv import os load_dotenv() # Define the voice analysis agent voice_analysis_agent = Agent( name="voice-analysis-agent", model=Together(id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", api_key=os.getenv("TOGETHER_API_KEY")), tools=[voice_analysis_tool], description=""" You are a voice analysis agent that evaluates vocal attributes like clarity, intonation, and pace. You will return the transcribed text, speech rate, pitch variation, and volume consistency. """, instructions=[ "You will be provided with an audio file of a person speaking.", "Your task is to analyze the vocal attributes in the audio to detect speech rate, pitch variation, and volume consistency.", "The response MUST be in the following JSON format:", "{", '"transcription": [transcription]', '"speech_rate_wpm": [speech_rate_wpm],', '"pitch_variation": [pitch_variation],', '"volume_consistency": [volume_consistency]', "}", "The response MUST be in proper JSON format with keys and values in double quotes.", "The final response MUST not include any other text or anything else other than the JSON response." ], markdown=True, show_tool_calls=True, debug_mode=True ) # audio = "../../videos/my_video.mp4" # prompt = f"Analyze vocal attributes in the audio file to detect speech rate, pitch variation, and volume consistency in the following audio: {audio}" # voice_analysis_agent.print_response(prompt, stream=True) # # Run agent and return the response as a variable # response: RunResponse = voice_analysis_agent.run(prompt) # # Print the response in markdown format # pprint_run_response(response, markdown=True)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/agents/voice_analysis_agent.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/main.py
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pydantic import BaseModel from agents.coordinator_agent import coordinator_agent from agno.agent import RunResponse from dotenv import load_dotenv # Load environment variables load_dotenv() # Initialize FastAPI app app = FastAPI() # Configure CORS to allow requests from your frontend app.add_middleware( CORSMiddleware, allow_origins=["*"], # To be replaced with the frontend's origin in production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Define the request body model class AnalysisRequest(BaseModel): video_url: str # Define the entry point @app.get("/") async def root(): return {"message": "Welcome to the video analysis API!"} # Define the analysis endpoint @app.post("/analyze") async def analyze(request: AnalysisRequest): video_url = request.video_url prompt = f"Analyze the following video: {video_url}" response: RunResponse = coordinator_agent.run(prompt) # Assuming response.content is a Pydantic model or a dictionary json_compatible_response = jsonable_encoder(response.content) return JSONResponse(content=json_compatible_response)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/backend/main.py", "license": "Apache License 2.0", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/Home.py
import streamlit as st import requests import tempfile import os import json import numpy as np from page_congif import render_page_config render_page_config() # Initialize session state variables if "begin" not in st.session_state: st.session_state.begin = False if "video_path" not in st.session_state: st.session_state.video_path = None if "upload_file" not in st.session_state: st.session_state.upload_file = False if "response" not in st.session_state: st.session_state.response = None if "facial_expression_response" not in st.session_state: st.session_state.facial_expression_response = None if "voice_analysis_response" not in st.session_state: st.session_state.voice_analysis_response = None if "content_analysis_response" not in st.session_state: st.session_state.content_analysis_response = None if "feedback_response" not in st.session_state: st.session_state.feedback_response = None def clear_session_response(): st.session_state.response = None st.session_state.facial_expression_response = None st.session_state.voice_analysis_response = None st.session_state.content_analysis_response = None st.session_state.feedback_response = None # Create two columns with a 70:30 width ratio col1, col2 = st.columns([0.7, 0.3]) # Left column: Video area and buttons with col1: spacer1, btn_col = st.columns([0.8, 0.2]) if st.session_state.begin: with spacer1: st.markdown("<h4>📽️ Video</h4>", unsafe_allow_html=True) with btn_col: if st.button("📤 Upload Video"): if st.session_state.video_path: os.remove(st.session_state.video_path) st.session_state.video_path = None clear_session_response() st.session_state.upload_file = True st.rerun() # Force rerun to fully reset uploader if st.session_state.get("upload_file"): uploaded_file = st.file_uploader("📤 Upload Video", type=["mp4"]) if uploaded_file is not None: temp_dir = tempfile.gettempdir() # Use a random name to avoid reuse unique_name = f"{int(np.random.rand()*1e8)}_{uploaded_file.name}" file_path = os.path.join(temp_dir, unique_name) if not os.path.exists(file_path): with open(file_path, "wb") as f: f.write(uploaded_file.read()) st.session_state.video_path = file_path st.session_state.upload_file = False st.rerun() # elif not st.session_state.get("video_path"): if not st.session_state.begin: st.success(""" **Welcome to AI Speech Trainer!** Your ultimate companion to help improve your public speaking skills. """) st.info(""" 🚀 To get started: \n\t1. Record a video of yourself practicing a speech or presentation - use any video recording app. \n\t2. Upload the recorded video. \n\t3. Analyze the video to get personalized feedback. """) if st.button("👉 Let's begin!"): st.session_state.begin = True st.rerun() if st.session_state.video_path: st.video(st.session_state.video_path, autoplay=False) if not st.session_state.response: if st.button("▶️ Analyze Video"): with st.spinner("Analyzing video..."): st.warning("⚠️ This process may take some time, so please be patient and wait for the analysis to complete.") API_URL = "http://localhost:8000/analyze" response = requests.post(API_URL, json={"video_url": st.session_state.video_path}) if response.status_code == 200: st.success("Video analysis completed successfully.") response = response.json() st.session_state.response = response st.session_state.facial_expression_response = response.get("facial_expression_response") st.session_state.voice_analysis_response = response.get("voice_analysis_response") st.session_state.content_analysis_response = response.get("content_analysis_response") st.session_state.feedback_response = response.get("feedback_response") st.rerun() else: st.error("🚨 Error during video analysis. Please try again.") # Right column: Transcript and feedback with col2: st.markdown("<h4>📝 Transcript</h4>", unsafe_allow_html=True) transcript_text = "Your transcript will be displayed here." if st.session_state.response: voice_analysis_response = st.session_state.voice_analysis_response transcript = json.loads(voice_analysis_response).get("transcription") else: transcript = None st.markdown( f""" <div style="background-color:#f0f2f6; padding: 1.5rem; border-radius: 10px; border: 1px solid #ccc; font-family: 'Segoe UI', sans-serif; line-height: 1.6; color: #333; height: 400px; max-height: 400px; overflow-y: auto;"> {transcript if transcript else transcript_text} </div> <br> """, unsafe_allow_html=True ) if st.button("📝 Get Feedback"): st.switch_page("pages/1 - Feedback.py")
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/Home.py", "license": "Apache License 2.0", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/page_congif.py
import streamlit as st from sidebar import render_sidebar def render_page_config(): # Set page configuration st.set_page_config( page_icon="🎙️", page_title="AI Speech Trainer", initial_sidebar_state="auto", layout="wide") # Load external CSS with open("style.css") as f: st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True) # Sidebar render_sidebar() # Main title with an icon st.markdown( """ <div class="custom-header"'> <span>🗣️ AI Speech Trainer</span><br> <span>Your personal coach for public speaking</span> </div> """, unsafe_allow_html=True ) # Horizontal line st.markdown("<hr class='custom-hr'>", unsafe_allow_html=True)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/page_congif.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/pages/1 - Feedback.py
import streamlit as st import plotly.graph_objects as go import json from page_congif import render_page_config render_page_config() # Get feedback response from session state if st.session_state.feedback_response: feedback_response = json.loads(st.session_state.feedback_response) feedback_scores = feedback_response.get("scores") # Evaluation scores based on the public speaking rubric scores = { "Content & Organization": feedback_scores.get("content_organization"), "Delivery & Vocal Quality": feedback_scores.get("delivery_vocal_quality"), "Body Language & Eye Contact": feedback_scores.get("body_language_eye_contact"), "Audience Engagement": feedback_scores.get("audience_engagement"), "Language & Clarity": feedback_scores.get("language_clarity") } total_score = feedback_response.get("total_score") interpretation = feedback_response.get("interpretation") feedback_summary = feedback_response.get("feedback_summary") else: st.warning("No feedback available! Please upload a video and analyze it first.") scores = { "Content & Organization": 0, "Delivery & Vocal Quality": 0, "Body Language & Eye Contact": 0, "Audience Engagement": 0, "Language & Clarity": 0 } total_score = 0 interpretation = "" feedback_summary = "" # Calculate average score average_score = sum(scores.values()) / len(scores) # Determine strengths, weaknesses, and suggestions for improvement if st.session_state.response: strengths = st.session_state.response.get("strengths") weaknesses = st.session_state.response.get("weaknesses") suggestions = st.session_state.response.get("suggestions") else: strengths = [] weaknesses = [] suggestions = [] # Create three columns with equal width col1, col2, col3 = st.columns([0.3, 0.4, 0.3]) # Left Column: Evaluation Summary with col1: st.subheader("🧾 Evaluation Summary") st.markdown("<br>", unsafe_allow_html=True) for criterion, score in scores.items(): label_col, progress_col, score_col = st.columns([2, 3, 1]) # Adjust the ratio as needed with label_col: st.markdown(f"**{criterion}**") with progress_col: st.progress(score / 5) with score_col: st.markdown(f"<span><b>{score}/5</b></span>", unsafe_allow_html=True) st.markdown("<br>", unsafe_allow_html=True) # Display total score st.markdown(f"#### 🏆 Total Score: {total_score} / 25") # Display average score st.markdown(f"#### 🎯 Average Score: {average_score:.2f} / 5") st.markdown("""---""") st.markdown("##### 🗣️ Feedback Summary:") # Display interpretation st.markdown(f"📝 **Overall Assessment**: {interpretation}") # Display feedback summary st.info(f"{feedback_summary}") # Middle Column: Strengths, Weaknesses, and Suggestions with col2: # Display strengths st.markdown("##### 🦾 Strengths:") strengths_text = '\n'.join(f"- {item}" for item in strengths) st.success(strengths_text) # Display weaknesses st.markdown("##### ⚠️ Weaknesses:") weaknesses_text = '\n'.join(f"- {item}" for item in weaknesses) st.error(weaknesses_text) # Display suggestions st.markdown("##### 💡 Suggestions for Improvement:") suggestions_text = '\n'.join(f"- {item}" for item in suggestions) st.warning(suggestions_text) # Right Column: Performance Chart with col3: st.subheader("📊 Performance Chart") # Radar Chart radar_fig = go.Figure() radar_fig.add_trace(go.Scatterpolar( r=list(scores.values()), theta=list(scores.keys()), fill='toself', name='Scores' )) radar_fig.update_layout( polar=dict( radialaxis=dict(visible=True, range=[0, 5]) ), showlegend=False, margin=dict(t=50, b=50, l=50, r=50), # Reduced margins width=350, height=350 ) st.plotly_chart(radar_fig, use_container_width=True) st.markdown("""---""")
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/pages/1 - Feedback.py", "license": "Apache License 2.0", "lines": 104, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/sidebar.py
# Sidebar with About section import streamlit as st def render_sidebar(): st.sidebar.header("About") st.sidebar.info( """ **AI Speech Trainer** helps users improve their public speaking skills through:\ 📽️ Video Analysis\ 🗣️ Voice Analysis\ 📊 Content Analysis & Feedback\ - Upload your video to receive a detailed feedback. - Improve your public speaking skills with AI-powered analysis. - Get personalized suggestions to enhance your performance. """ )
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_speech_trainer_agent/frontend/sidebar.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/main.py
# main.py from langchain_google_genai import ChatGoogleGenerativeAI from windows_use.agent import Agent from dotenv import load_dotenv load_dotenv() llm=ChatGoogleGenerativeAI(model='gemini-2.0-flash') instructions=['We have Claude Desktop, Perplexity and ChatGPT App installed on the desktop so if you need any help, just ask your AI friends.'] agent = Agent(instructions=instructions,llm=llm,use_vision=True) query=input("Enter your query: ") agent_result=agent.invoke(query=query) print(agent_result.content)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/main.py", "license": "Apache License 2.0", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/prompt/service.py
from windows_use.agent.registry.views import ToolResult from windows_use.agent.views import AgentStep, AgentData from windows_use.desktop.views import DesktopState from langchain.prompts import PromptTemplate from importlib.resources import files from datetime import datetime from getpass import getuser from textwrap import dedent from pathlib import Path import pyautogui as pg import platform class Prompt: @staticmethod def system_prompt(tools_prompt:str,max_steps:int,instructions: list[str]=[]) -> str: width, height = pg.size() template =PromptTemplate.from_file(files('windows_use.agent.prompt').joinpath('system.md')) return template.format(**{ 'current_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'instructions': '\n'.join(instructions), 'tools_prompt': tools_prompt, 'os':platform.system(), 'home_dir':Path.home().as_posix(), 'user':getuser(), 'resolution':f'{width}x{height}', 'max_steps': max_steps }) @staticmethod def action_prompt(agent_data:AgentData) -> str: template = PromptTemplate.from_file(files('windows_use.agent.prompt').joinpath('action.md')) return template.format(**{ 'evaluate': agent_data.evaluate, 'memory': agent_data.memory, 'thought': agent_data.thought, 'action_name': agent_data.action.name, 'action_input': agent_data.action.params }) @staticmethod def previous_observation_prompt(observation: str)-> str: template=PromptTemplate.from_template(dedent(''' ```xml <Observation>{observation}</Observation> ``` ''')) return template.format(**{'observation': observation}) @staticmethod def observation_prompt(agent_step: AgentStep, tool_result:ToolResult,desktop_state: DesktopState) -> str: cursor_position = pg.position() tree_state = desktop_state.tree_state template = PromptTemplate.from_file(files('windows_use.agent.prompt').joinpath('observation.md')) return template.format(**{ 'steps': agent_step.step_number, 'max_steps': agent_step.max_steps, 'observation': tool_result.content if tool_result.is_success else tool_result.error, 'active_app': desktop_state.active_app_to_string(), 'cursor_location': f'{cursor_position.x},{cursor_position.y}', 'apps': desktop_state.apps_to_string(), 'interactive_elements': tree_state.interactive_elements_to_string() or 'No interactive elements found', 'informative_elements': tree_state.informative_elements_to_string() or 'No informative elements found', 'scrollable_elements': tree_state.scrollable_elements_to_string() or 'No scrollable elements found', }) @staticmethod def answer_prompt(agent_data: AgentData, tool_result: ToolResult): template = PromptTemplate.from_file(files('windows_use.agent.prompt').joinpath('answer.md')) return template.format(**{ 'evaluate': agent_data.evaluate, 'memory': agent_data.memory, 'thought': agent_data.thought, 'final_answer': tool_result.content })
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/prompt/service.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/registry/service.py
from windows_use.agent.registry.views import Tool as ToolData, ToolResult from windows_use.desktop import Desktop from langchain.tools import Tool from textwrap import dedent class Registry: def __init__(self,tools:list[Tool]): self.tools=tools self.tools_registry=self.registry() def tool_prompt(self, tool_name: str) -> str: tool = self.tools_registry.get(tool_name) return dedent(f""" Tool Name: {tool.name} Description: {tool.description} Parameters: {tool.params} """) def registry(self): return {tool.name: ToolData( name=tool.name, description=tool.description, params=tool.args, function=tool.run ) for tool in self.tools} def get_tools_prompt(self) -> str: tools_prompt = [self.tool_prompt(tool.name) for tool in self.tools] return dedent(f""" Available Tools: {'\n\n'.join(tools_prompt)} """) def execute(self, tool_name: str, desktop: Desktop, **kwargs) -> ToolResult: tool = self.tools_registry.get(tool_name) if tool is None: return ToolResult(is_success=False, error=f"Tool '{tool_name}' not found.") try: content = tool.function(tool_input={'desktop':desktop}|kwargs) return ToolResult(is_success=True, content=content) except Exception as error: return ToolResult(is_success=False, error=str(error))
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/registry/service.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/registry/views.py
from pydantic import BaseModel from typing import Callable class Tool(BaseModel): name:str description:str function: Callable params: dict class ToolResult(BaseModel): is_success: bool content: str | None = None error: str | None = None
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/registry/views.py", "license": "Apache License 2.0", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/service.py
from windows_use.agent.tools.service import click_tool, type_tool, launch_tool, shell_tool, clipboard_tool, done_tool, shortcut_tool, scroll_tool, drag_tool, move_tool, key_tool, wait_tool, scrape_tool from langchain_core.messages import SystemMessage, HumanMessage, AIMessage from windows_use.agent.views import AgentState, AgentStep, AgentResult from windows_use.agent.utils import extract_agent_data, image_message from langchain_core.language_models.chat_models import BaseChatModel from windows_use.agent.registry.views import ToolResult from windows_use.agent.registry.service import Registry from windows_use.agent.prompt.service import Prompt from langchain_core.tools import BaseTool from windows_use.desktop import Desktop from termcolor import colored import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter('%(message)s') handler.setFormatter(formatter) logger.addHandler(handler) class Agent: ''' Windows Use An agent that can interact with GUI elements on Windows Args: instructions (list[str], optional): Instructions for the agent. Defaults to []. additional_tools (list[BaseTool], optional): Additional tools for the agent. Defaults to []. llm (BaseChatModel): Language model for the agent. Defaults to None. max_steps (int, optional): Maximum number of steps for the agent. Defaults to 100. use_vision (bool, optional): Whether to use vision for the agent. Defaults to False. Returns: Agent ''' def __init__(self,instructions:list[str]=[],additional_tools:list[BaseTool]=[], llm: BaseChatModel=None,max_steps:int=100,use_vision:bool=False): self.name='Windows Use' self.description='An agent that can interact with GUI elements on Windows' self.registry = Registry([ click_tool,type_tool, launch_tool, shell_tool, clipboard_tool, done_tool, shortcut_tool, scroll_tool, drag_tool, move_tool, key_tool, wait_tool, scrape_tool ] + additional_tools) self.instructions=instructions self.desktop = Desktop() self.agent_state = AgentState() self.agent_step = AgentStep(max_steps=max_steps) self.use_vision=use_vision self.llm = llm def reason(self): message=self.llm.invoke(self.agent_state.messages) agent_data = extract_agent_data(message=message) self.agent_state.update_state(agent_data=agent_data, messages=[message]) logger.info(colored(f"💭: Thought: {agent_data.thought}",color='light_magenta',attrs=['bold'])) def action(self): self.agent_state.messages.pop() # Remove the last message to avoid duplication last_message = self.agent_state.messages[-1] if isinstance(last_message, HumanMessage): self.agent_state.messages[-1]=HumanMessage(content=Prompt.previous_observation_prompt(self.agent_state.previous_observation)) ai_message = AIMessage(content=Prompt.action_prompt(agent_data=self.agent_state.agent_data)) name = self.agent_state.agent_data.action.name params = self.agent_state.agent_data.action.params logger.info(colored(f"🔧: Action: {name}({', '.join(f'{k}={v}' for k, v in params.items())})",color='blue',attrs=['bold'])) tool_result = self.registry.execute(tool_name=name, desktop=self.desktop, **params) observation=tool_result.content if tool_result.is_success else tool_result.error logger.info(colored(f"🔭: Observation: {observation}",color='green',attrs=['bold'])) desktop_state = self.desktop.get_state(use_vision=self.use_vision) prompt=Prompt.observation_prompt(agent_step=self.agent_step, tool_result=tool_result, desktop_state=desktop_state) human_message=image_message(prompt=prompt,image=desktop_state.screenshot) if self.use_vision and desktop_state.screenshot else HumanMessage(content=prompt) self.agent_state.update_state(agent_data=None,observation=observation,messages=[ai_message, human_message]) def answer(self): self.agent_state.messages.pop() # Remove the last message to avoid duplication last_message = self.agent_state.messages[-1] if isinstance(last_message, HumanMessage): self.agent_state.messages[-1]=HumanMessage(content=Prompt.previous_observation_prompt(self.agent_state.previous_observation)) name = self.agent_state.agent_data.action.name params = self.agent_state.agent_data.action.params tool_result = self.registry.execute(tool_name=name, desktop=None, **params) ai_message = AIMessage(content=Prompt.answer_prompt(agent_data=self.agent_state.agent_data, tool_result=tool_result)) logger.info(colored(f"📜: Final Answer: {tool_result.content}",color='cyan',attrs=['bold'])) self.agent_state.update_state(agent_data=None,observation=None,result=tool_result.content,messages=[ai_message]) def invoke(self,query: str): max_steps = self.agent_step.max_steps tools_prompt = self.registry.get_tools_prompt() desktop_state = self.desktop.get_state(use_vision=self.use_vision) prompt=Prompt.observation_prompt(agent_step=self.agent_step, tool_result=ToolResult(is_success=True, content="No Action"), desktop_state=desktop_state) system_message=SystemMessage(content=Prompt.system_prompt(instructions=self.instructions,tools_prompt=tools_prompt,max_steps=max_steps)) human_message=image_message(prompt=prompt,image=desktop_state.screenshot) if self.use_vision and desktop_state.screenshot else HumanMessage(content=prompt) messages=[system_message,HumanMessage(content=f'Task: {query}'),human_message] self.agent_state.initialize_state(messages=messages) while True: if self.agent_step.is_last_step(): logger.info("Reached maximum number of steps, stopping execution.") return AgentResult(is_done=False, content=None, error="Maximum steps reached.") self.reason() if self.agent_state.is_done(): self.answer() return AgentResult(is_done=True, content=self.agent_state.result, error=None) self.action() if self.agent_state.consecutive_failures >= 3: logger.warning("Consecutive failures exceeded limit, stopping execution.") return AgentResult(is_done=False, content=None, error="Consecutive failures exceeded limit.") self.agent_step.increment_step()
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/service.py", "license": "Apache License 2.0", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/tools/service.py
from windows_use.agent.tools.views import Click, Type, Launch, Scroll, Drag, Move, Shortcut, Key, Wait, Scrape,Done, Clipboard, Shell from windows_use.desktop import Desktop from humancursor import SystemCursor from markdownify import markdownify from langchain.tools import tool from typing import Literal import uiautomation as ua import pyperclip as pc import pyautogui as pg import requests cursor=SystemCursor() @tool('Done Tool',args_schema=Done) def done_tool(answer:str,desktop:Desktop=None): '''To indicate that the task is completed''' return answer @tool('Launch Tool',args_schema=Launch) def launch_tool(name: str,desktop:Desktop=None) -> str: 'Launch an application present in start menu (e.g., "notepad", "calculator", "chrome")' _,status=desktop.launch_app(name) if status!=0: return f'Failed to launch {name.title()}.' else: return f'Launched {name.title()}.' @tool('Shell Tool',args_schema=Shell) def shell_tool(command: str,desktop:Desktop=None) -> str: 'Execute PowerShell commands and return the output with status code' response,status=desktop.execute_command(command) return f'Status Code: {status}\nResponse: {response}' @tool('Clipboard Tool',args_schema=Clipboard) def clipboard_tool(mode: Literal['copy', 'paste'], text: str = None,desktop:Desktop=None)->str: 'Copy text to clipboard or retrieve current clipboard content. Use "copy" mode with text parameter to copy, "paste" mode to retrieve.' if mode == 'copy': if text: pc.copy(text) # Copy text to system clipboard return f'Copied "{text}" to clipboard' else: raise ValueError("No text provided to copy") elif mode == 'paste': clipboard_content = pc.paste() # Get text from system clipboard return f'Clipboard Content: "{clipboard_content}"' else: raise ValueError('Invalid mode. Use "copy" or "paste".') @tool('Click Tool',args_schema=Click) def click_tool(loc:tuple[int,int],button:Literal['left','right','middle']='left',clicks:int=1,desktop:Desktop=None)->str: 'Click on UI elements at specific coordinates. Supports left/right/middle mouse buttons and single/double/triple clicks. Use coordinates from State-Tool output.' x,y=loc cursor.move_to(loc) control=desktop.get_element_under_cursor() pg.click(button=button,clicks=clicks) num_clicks={1:'Single',2:'Double',3:'Triple'} return f'{num_clicks.get(clicks)} {button} Clicked on {control.Name} Element with ControlType {control.ControlTypeName} at ({x},{y}).' @tool('Type Tool',args_schema=Type) def type_tool(loc:tuple[int,int],text:str,clear:str='false',caret_position:Literal['start','idle','end']='idle',desktop:Desktop=None): 'Type text into input fields, text areas, or focused elements. Set clear=True to replace existing text, False to append. Click on target element coordinates first.' x,y=loc cursor.click_on(loc) control=desktop.get_element_under_cursor() if caret_position == 'start': pg.press('home') elif caret_position == 'end': pg.press('end') else: pass if clear=='true': pg.hotkey('ctrl','a') pg.press('backspace') pg.typewrite(text,interval=0.1) return f'Typed {text} on {control.Name} Element with ControlType {control.ControlTypeName} at ({x},{y}).' @tool('Scroll Tool',args_schema=Scroll) def scroll_tool(loc:tuple[int,int]=None,type:Literal['horizontal','vertical']='vertical',direction:Literal['up','down','left','right']='down',wheel_times:int=1,desktop:Desktop=None)->str: 'Scroll at specific coordinates or current mouse position. Use wheel_times to control scroll amount (1 wheel = ~3-5 lines). Essential for navigating lists, web pages, and long content.' if loc: cursor.move_to(loc) match type: case 'vertical': match direction: case 'up': ua.WheelUp(wheel_times) case 'down': ua.WheelDown(wheel_times) case _: return 'Invalid direction. Use "up" or "down".' case 'horizontal': match direction: case 'left': pg.keyDown('Shift') pg.sleep(0.05) ua.WheelUp(wheel_times) pg.sleep(0.05) pg.keyUp('Shift') case 'right': pg.keyDown('Shift') pg.sleep(0.05) ua.WheelDown(wheel_times) pg.sleep(0.05) pg.keyUp('Shift') case _: return 'Invalid direction. Use "left" or "right".' case _: return 'Invalid type. Use "horizontal" or "vertical".' return f'Scrolled {type} {direction} by {wheel_times} wheel times.' @tool('Drag Tool',args_schema=Drag) def drag_tool(from_loc:tuple[int,int],to_loc:tuple[int,int],desktop:Desktop=None)->str: 'Drag and drop operation from source coordinates to destination coordinates. Useful for moving files, resizing windows, or drag-and-drop interactions.' control=desktop.get_element_under_cursor() x1,y1=from_loc x2,y2=to_loc cursor.drag_and_drop(from_loc,to_loc) return f'Dragged the {control.Name} element with ControlType {control.ControlTypeName} from ({x1},{y1}) to ({x2},{y2}).' @tool('Move Tool',args_schema=Move) def move_tool(to_loc:tuple[int,int],desktop:Desktop=None)->str: 'Move mouse cursor to specific coordinates without clicking. Useful for hovering over elements or positioning cursor before other actions.' x,y=to_loc cursor.move_to(to_loc) return f'Moved the mouse pointer to ({x},{y}).' @tool('Shortcut Tool',args_schema=Shortcut) def shortcut_tool(shortcut:list[str],desktop:Desktop=None): 'Execute keyboard shortcuts using key combinations. Pass keys as list (e.g., ["ctrl", "c"] for copy, ["alt", "tab"] for app switching, ["win", "r"] for Run dialog).' pg.hotkey(*shortcut) return f'Pressed {'+'.join(shortcut)}.' @tool('Key Tool',args_schema=Key) def key_tool(key:str='',desktop:Desktop=None)->str: 'Press individual keyboard keys. Supports special keys like "enter", "escape", "tab", "space", "backspace", "delete", arrow keys ("up", "down", "left", "right"), function keys ("f1"-"f12").' pg.press(key) return f'Pressed the key {key}.' @tool('Wait Tool',args_schema=Wait) def wait_tool(duration:int,desktop:Desktop=None)->str: 'Pause execution for specified duration in seconds. Useful for waiting for applications to load, animations to complete, or adding delays between actions.' pg.sleep(duration) return f'Waited for {duration} seconds.' @tool('Scrape Tool',args_schema=Scrape) def scrape_tool(url:str,desktop:Desktop=None)->str: 'Fetch and convert webpage content to markdown format. Provide full URL including protocol (http/https). Returns structured text content suitable for analysis.' response=requests.get(url,timeout=10) html=response.text content=markdownify(html=html) return f'Scraped the contents of the entire webpage:\n{content}'
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/tools/service.py", "license": "Apache License 2.0", "lines": 137, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/tools/views.py
from pydantic import BaseModel,Field from typing import Literal class SharedBaseModel(BaseModel): class Config: extra='allow' class Done(SharedBaseModel): answer:str = Field(...,description="the detailed final answer to the user query in proper markdown format",examples=["The task is completed successfully."]) class Clipboard(SharedBaseModel): mode:Literal['copy','paste'] = Field(...,description="the mode of the clipboard",examples=['Copy']) text:str = Field(...,description="the text to copy to clipboard",examples=["hello world"]) class Click(SharedBaseModel): loc:tuple[int,int]=Field(...,description="The coordinates of the element to click on.",examples=[(0,0)]) button:Literal['left','right','middle']=Field(description='The button to click on the element.',default='left',examples=['left']) clicks:Literal[0,1,2]=Field(description="The number of times to click on the element. (0 for hover, 1 for single click, 2 for double click)",default=2,examples=[0]) class Shell(SharedBaseModel): command:str=Field(...,description="The PowerShell command to execute.",examples=['Get-Process']) class Type(SharedBaseModel): loc:tuple[int,int]=Field(...,description="The coordinates of the element to type on.",examples=[(0,0)]) text:str=Field(...,description="The text to type on the element.",examples=['hello world']) clear:Literal['true','false']=Field(description="To clear the text field before typing.",default='false',examples=['true']) caret_position:Literal['start','idle','end']=Field(description="The position of the caret.",default='idle',examples=['start','idle','end']) class Launch(SharedBaseModel): name:str=Field(...,description="The name of the application to launch.",examples=['Google Chrome']) class Scroll(SharedBaseModel): loc:tuple[int,int]|None=Field(description="The coordinates of the element to scroll on. If None, the screen will be scrolled.",default=None,examples=[(0,0)]) type:Literal['horizontal','vertical']=Field(description="The type of scroll.",default='vertical',examples=['vertical']) direction:Literal['up','down','left','right']=Field(description="The direction of the scroll.",default=['down'],examples=['down']) wheel_times:int=Field(description="The number of times to scroll.",default=1,examples=[1,2,5]) class Drag(SharedBaseModel): from_loc:tuple[int,int]=Field(...,description="The from coordinates of the drag.",examples=[(0,0)]) to_loc:tuple[int,int]=Field(...,description="The to coordinates of the drag.",examples=[(100,100)]) class Move(SharedBaseModel): to_loc:tuple[int,int]=Field(...,description="The coordinates to move to.",examples=[(100,100)]) class Shortcut(SharedBaseModel): shortcut:list[str]=Field(...,description="The shortcut to execute by pressing the keys.",examples=[['ctrl','a'],['alt','f4']]) class Key(SharedBaseModel): key:str=Field(...,description="The key to press.",examples=['enter']) class Wait(SharedBaseModel): duration:int=Field(...,description="The duration to wait in seconds.",examples=[5]) class Scrape(SharedBaseModel): url:str=Field(...,description="The url of the webpage to scrape.",examples=['https://google.com'])
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/tools/views.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/utils.py
from langchain_core.messages import BaseMessage,HumanMessage from windows_use.agent.views import AgentData import ast import re def read_file(file_path: str) -> str: with open(file_path, 'r') as file: return file.read() def extract_agent_data(message: BaseMessage) -> AgentData: text = message.content # Dictionary to store extracted values result = {} # Extract Memory memory_match = re.search(r"<Memory>(.*?)<\/Memory>", text, re.DOTALL) if memory_match: result['memory'] = memory_match.group(1).strip() # Extract Evaluate evaluate_match = re.search(r"<Evaluate>(.*?)<\/Evaluate>", text, re.DOTALL) if evaluate_match: result['evaluate'] = evaluate_match.group(1).strip() # Extract Thought thought_match = re.search(r"<Thought>(.*?)<\/Thought>", text, re.DOTALL) if thought_match: result['thought'] = thought_match.group(1).strip() # Extract Action-Name action = {} action_name_match = re.search(r"<Action-Name>(.*?)<\/Action-Name>", text, re.DOTALL) if action_name_match: action['name'] = action_name_match.group(1).strip() # Extract and convert Action-Input to a dictionary action_input_match = re.search(r"<Action-Input>(.*?)<\/Action-Input>", text, re.DOTALL) if action_input_match: action_input_str = action_input_match.group(1).strip() try: # Convert string to dictionary safely using ast.literal_eval action['params'] = ast.literal_eval(action_input_str) except (ValueError, SyntaxError): # If there's an issue with conversion, store it as raw string action['params'] = action_input_str result['action'] = action return AgentData.model_validate(result) def image_message(prompt,image)->HumanMessage: return HumanMessage(content=[ { "type": "text", "text": prompt, }, { "type": "image_url", "image_url": image }, ])
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/utils.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/views.py
from langchain_core.messages.base import BaseMessage from pydantic import BaseModel,Field from typing import Optional from uuid import uuid4 class AgentState(BaseModel): id: str = Field(default_factory=lambda: str(uuid4())) consecutive_failures: int = 0 result: str = '' agent_data: 'AgentData' = None messages: list[BaseMessage] = Field(default_factory=list) previous_observation: str = None def is_done(self): return self.agent_data is not None and self.agent_data.action.name == 'Done Tool' def initialize_state(self, messages: list[BaseMessage]): self.consecutive_failures = 0 self.result = "" self.messages = messages def update_state(self, agent_data: 'AgentData' = None, observation: str = None, result: str = None, messages: list[BaseMessage] = None): self.result = result self.previous_observation = observation self.agent_data = agent_data self.messages.extend(messages or []) class AgentStep(BaseModel): step_number: int=0 max_steps: int def is_last_step(self): return self.step_number >= self.max_steps-1 def increment_step(self): self.step_number += 1 class AgentResult(BaseModel): is_done:bool|None=False content:str|None=None error:str|None=None class Action(BaseModel): name:str params: dict class AgentData(BaseModel): evaluate: Optional[str]=None memory: Optional[str]=None thought: Optional[str]=None action: Optional[Action]=None
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/agent/views.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/desktop/config.py
from typing import Set AVOIDED_APPS:Set[str]=set([ 'Recording toolbar' ]) EXCLUDED_APPS:Set[str]=set([ 'Program Manager','Taskbar' ]).union(AVOIDED_APPS)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/desktop/config.py", "license": "Apache License 2.0", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/desktop/views.py
from windows_use.tree.views import TreeState from dataclasses import dataclass from typing import Literal,Optional @dataclass class App: name:str depth:int status:Literal['Maximized','Minimized','Normal'] size:'Size' def to_string(self): return f'Name: {self.name}|Depth: {self.depth}|Status: {self.status}|Size: {self.size.to_string()}' @dataclass class Size: width:int height:int def to_string(self): return f'({self.width},{self.height})' @dataclass class DesktopState: apps:list[App] active_app:Optional[App] screenshot:bytes|None tree_state:TreeState def active_app_to_string(self): if self.active_app is None: return 'No active app' return self.active_app.to_string() def apps_to_string(self): if len(self.apps)==0: return 'No apps opened' return '\n'.join([app.to_string() for app in self.apps])
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/desktop/views.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/tree/config.py
INTERACTIVE_CONTROL_TYPE_NAMES=set([ 'ButtonControl','ListItemControl','MenuItemControl','DocumentControl', 'EditControl','CheckBoxControl', 'RadioButtonControl','ComboBoxControl', 'HyperlinkControl','SplitButtonControl','TabItemControl','CustomControl', 'TreeItemControl','DataItemControl','HeaderItemControl','TextBoxControl', 'ImageControl','SpinnerControl','ScrollBarControl' ]) INFORMATIVE_CONTROL_TYPE_NAMES=[ 'TextControl','ImageControl' ]
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/tree/config.py", "license": "Apache License 2.0", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/tree/views.py
from dataclasses import dataclass,field @dataclass class TreeState: interactive_nodes:list['TreeElementNode']=field(default_factory=[]) informative_nodes:list['TextElementNode']=field(default_factory=[]) scrollable_nodes:list['ScrollElementNode']=field(default_factory=[]) def interactive_elements_to_string(self)->str: return '\n'.join([f'Label: {index} App Name: {node.app_name} ControlType: {f'{node.control_type} Control'} Name: {node.name} Shortcut: {node.shortcut} Cordinates: {node.center.to_string()}' for index,node in enumerate(self.interactive_nodes)]) def informative_elements_to_string(self)->str: return '\n'.join([f'App Name: {node.app_name} Name: {node.name}' for node in self.informative_nodes]) def scrollable_elements_to_string(self)->str: n=len(self.interactive_nodes) return '\n'.join([f'Label: {n+index} App Name: {node.app_name} ControlType: {f'{node.control_type} Control'} Name: {node.name} Cordinates: {node.center.to_string()} Horizontal Scrollable: {node.horizontal_scrollable} Vertical Scrollable: {node.vertical_scrollable}' for index,node in enumerate(self.scrollable_nodes)]) @dataclass class BoundingBox: left:int top:int right:int bottom:int def to_string(self): return f'({self.left},{self.top},{self.right},{self.bottom})' @dataclass class Center: x:int y:int def to_string(self)->str: return f'({self.x},{self.y})' @dataclass class TreeElementNode: name:str control_type:str shortcut:str bounding_box:BoundingBox center:Center app_name:str @dataclass class TextElementNode: name:str app_name:str @dataclass class ScrollElementNode: name:str control_type:str app_name:str center:Center horizontal_scrollable:bool vertical_scrollable:bool
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/windows_use_autonomous_agent/windows_use/tree/views.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_llm_apps/chat-with-tarots/app.py
from langchain.prompts import PromptTemplate import pandas as pd from langchain_core.runnables import RunnableParallel, RunnableLambda # Import necessary for LCEL import random import streamlit as st import helpers.help_func as hf from PIL import Image # --- Load the dataset --- csv_file_path = 'data/tarots.csv' try: # Read CSV file df = pd.read_csv(csv_file_path, sep=';', encoding='latin1') print(f"CSV dataset loaded successfully: {csv_file_path}. Number of rows: {len(df)}") # Clean and normalize column names df.columns = df.columns.str.strip().str.lower() # Debug: Show column details print("\nDetails after cleanup:") for col in df.columns: print(f"Column: '{col}' (length: {len(col)})") # Define required columns (in lowercase) required_columns = ['card', 'upright', 'reversed', 'symbolism'] # Verify all required columns are present available_columns = set(df.columns) missing_columns = [col for col in required_columns if col not in available_columns] if missing_columns: raise ValueError( f"Missing columns in CSV file: {', '.join(missing_columns)}\n" f"Available columns: {', '.join(available_columns)}" ) # Create card meanings dictionary with cleaned data card_meanings = {} for _, row in df.iterrows(): card_name = row['card'].strip() card_meanings[card_name] = { 'upright': str(row['upright']).strip() if pd.notna(row['upright']) else '', 'reversed': str(row['reversed']).strip() if pd.notna(row['reversed']) else '', 'symbolism': str(row['symbolism']).strip() if pd.notna(row['symbolism']) else '' } print(f"\nKnowledge base created with {len(card_meanings)} cards, meanings and symbolisms.") except FileNotFoundError: print(f"Error: CSV File not found: {csv_file_path}") raise except ValueError as e: print(f"Validation Error: {str(e)}") raise except Exception as e: print(f"Unexpected error: {str(e)}") raise # --- Define the Prompt Template --- prompt_analysis = PromptTemplate.from_template(""" Analyze the following tarot cards, based on the meanings provided (also considering if they are reversed): {card_details} Pay attention to these aspects: - Provide a detailed analysis of the meaning of each card (upright or reversed). - Then offer a general interpretation of the answer based on the cards, linking it to the context: {context}. - Be mystical and provide information on the interpretation related to the symbolism of the cards, based on the specific column: {symbolism}. - At the end of the reading, always offer advice to improve or address the situation. Also, base it on your knowledge of psychology. """) print("\nPrompt Template 'prompt_analysis' defined.") # --- Create the LangChain Chain --- analyzer = ( RunnableParallel( cards=lambda x: x['cards'], context=lambda x: x['context'] ) | (lambda x: hf.prepare_prompt_input(x, card_meanings)) | prompt_analysis | hf.llm ) # --- Frontend Streamlit --- st.set_page_config( page_title="🔮 Interactive Tarot Reading", page_icon="🃏", layout="wide", initial_sidebar_state="expanded" ) st.title("🔮 Interactive Tarot Reading") st.markdown("Welcome to your personalized tarot consultation!") st.markdown("---") num_cards = st.selectbox("🃏 Select the number of cards for your spread (3 for a more focused answer, 7 for a more general overview).)", [3, 5, 7]) context_question = st.text_area("✍️ Please enter your context or your question here. You can speak in natural language.", height=100) if st.button("✨ Light your path: Draw and Analyze the Cards."): if not context_question: st.warning("For a more precise reading, please enter your context or question.") else: try: card_names_in_dataset = df['card'].unique().tolist() drawn_cards_list = hf.generate_random_draw(num_cards, card_names_in_dataset) st.subheader("✨ Your Cards Revealed:") st.markdown("---") cols = st.columns(len(drawn_cards_list)) for i, card_info in enumerate(drawn_cards_list): with cols[i]: # The card_info['name'] from data/tarots.csv is now the direct image filename e.g., "00-thefool.jpg" image_filename = card_info['name'] image_path = f"images/{image_filename}" reversed_label = "(R)" if 'is_reversed' in card_info else "" caption = f"{card_info['name']} {reversed_label}" try: img = Image.open(image_path) if card_info.get('is_reversed', False): img = img.rotate(180) st.image(img, caption=caption, width=150) except FileNotFoundError: st.info(f"Symbol: {card_info['name']} {reversed_label} (Image not found at {image_path})") st.markdown("---") with st.spinner("🔮 Unveiling the meanings..."): analysis_result = analyzer.invoke({"cards": drawn_cards_list, "context": context_question}) st.subheader("📜 The Interpretation:") st.write(analysis_result.content) except Exception as e: st.error(f"An error has occurred: {e}") st.error(f"Error details: {e}") st.markdown("---") st.info("Remember, the cards offer insights and reflections; your future is in your hands.")
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_llm_apps/chat-with-tarots/app.py", "license": "Apache License 2.0", "lines": 115, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:mcp_ai_agents/multi_mcp_agent/multi_mcp_agent.py
import asyncio import os import uuid from textwrap import dedent from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.mcp import MultiMCPTools from agno.db.sqlite import SqliteDb from dotenv import load_dotenv # Load environment variables load_dotenv() GITHUB_TOKEN = os.getenv("GITHUB_PERSONAL_ACCESS_TOKEN") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY") async def main(): print("\n" + "="*60) print(" 🚀 Multi-MCP Intelligent Assistant 🚀") print("="*60) print("🔗 Connected Services: GitHub • Perplexity • Calendar") print("💡 Powered by OpenAI GPT-4o with Advanced Tool Integration") print("="*60 + "\n") # Validate required environment variables required_vars = { "GITHUB_PERSONAL_ACCESS_TOKEN": GITHUB_TOKEN, "OPENAI_API_KEY": OPENAI_API_KEY, "PERPLEXITY_API_KEY": PERPLEXITY_API_KEY, } missing_vars = [name for name, value in required_vars.items() if not value] if missing_vars: print("❌ ERROR: Missing required environment variables:") for var in missing_vars: print(f" • {var}") print("\nPlease check your .env file and ensure all required variables are set.") return # Generate unique user and session IDs for this terminal session user_id = f"user_{uuid.uuid4().hex[:8]}" session_id = f"session_{uuid.uuid4().hex[:8]}" print(f"👤 User ID: {user_id}") print(f"🔑 Session ID: {session_id}") print("\n🔌 Initializing MCP server connections...\n") # Set up environment variables for MCP servers env = { **os.environ, "GITHUB_PERSONAL_ACCESS_TOKEN": GITHUB_TOKEN, "PERPLEXITY_API_KEY": PERPLEXITY_API_KEY } mcp_servers = [ "npx -y @modelcontextprotocol/server-github", "npx -y @chatmcp/server-perplexity-ask", "npx @gongrzhe/server-calendar-autoauth-mcp", "npx @gongrzhe/server-gmail-autoauth-mcp" ] # Setup database for memory db = SqliteDb(db_file="tmp/multi_mcp_agent.db") # Start the MCP Tools session async with MultiMCPTools(mcp_servers, env=env) as mcp_tools: print("✅ Successfully connected to all MCP servers!") # Create the agent with comprehensive instructions agent = Agent( name="MultiMCPAgent", model=OpenAIChat(id="gpt-4o", api_key=OPENAI_API_KEY), tools=[mcp_tools], description="Advanced AI assistant with GitHub, Perplexity, and Calendar integration", instructions=dedent(f""" You are an elite AI assistant with powerful integrations across multiple platforms. Your mission is to help users be incredibly productive across their digital workspace. 🎯 CORE CAPABILITIES & INSTRUCTIONS: 1. 🔧 TOOL MASTERY • You have DIRECT access to GitHub, Notion, Perplexity, and Calendar through MCP tools • ALWAYS use the appropriate MCP tool calls for any requests related to these platforms • Be proactive in suggesting powerful workflows and automations • Chain multiple tool calls together for complex tasks 2. 📋 GITHUB EXCELLENCE • Repository management: create, clone, fork, search repositories • Issue & PR workflow: create, update, review, merge, comment • Code analysis: search code, review diffs, suggest improvements • Branch management: create, switch, merge branches • Collaboration: manage teams, reviews, and project workflows 4. 🔍 PERPLEXITY RESEARCH • Real-time web search and research • Current events and trending information • Technical documentation and learning resources • Fact-checking and verification 5. 📅 CALENDAR INTEGRATION • Event scheduling and management • Meeting coordination and availability • Deadline tracking and reminders 6. 🎨 INTERACTION PRINCIPLES • Be conversational, helpful, and proactive • Explain what you're doing and why • Suggest follow-up actions and optimizations • Handle errors gracefully with alternative solutions • Ask clarifying questions when needed • Provide rich, formatted responses using markdown 7. 🚀 ADVANCED WORKFLOWS • Cross-platform automation (e.g., GitHub issues → Notion tasks) • Research-driven development (Perplexity → GitHub) • Project management integration • Documentation and knowledge sharing SESSION INFO: • User ID: {user_id} • Session ID: {session_id} • Active Services: GitHub, Notion, Perplexity, Calendar REMEMBER: You're not just answering questions - you're a productivity multiplier. Think big, suggest workflows, and help users achieve more than they imagined possible! """), markdown=True, debug_mode=True, retries=3, db=db, enable_user_memories=True, add_history_to_context=True, num_history_runs=10, # Increased for better context retention ) print("\n" + "🎉 " + "="*54 + " 🎉") print(" Multi-MCP Assistant is READY! Let's get productive!") print("🎉 " + "="*54 + " 🎉\n") print("💡 Try these example commands:") print(" • 'Show my recent GitHub repositories'") print(" • 'Search for the latest AI developments'") print(" • 'Schedule a meeting for next week'") print("⚡ Type 'exit', 'quit', or 'bye' to end the session\n") # Start interactive CLI session await agent.acli_app( user_id=user_id, session_id=session_id, user="You", emoji="🤖", stream=True, markdown=True, exit_on=["exit", "quit", "bye", "goodbye"] ) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "mcp_ai_agents/multi_mcp_agent/multi_mcp_agent.py", "license": "Apache License 2.0", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:rag_tutorials/agentic_rag_with_reasoning/rag_reasoning_agent.py
import streamlit as st from agno.agent import Agent from agno.knowledge.embedder.openai import OpenAIEmbedder from agno.knowledge.knowledge import Knowledge from agno.models.google import Gemini from agno.tools.reasoning import ReasoningTools from agno.vectordb.lancedb import LanceDb, SearchType from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Page configuration st.set_page_config( page_title="Agentic RAG with Reasoning", page_icon="🧐", layout="wide" ) # Main title and description st.title("🧐 Agentic RAG with Reasoning") st.markdown(""" This app demonstrates an AI agent that: 1. **Retrieves** relevant information from knowledge sources 2. **Reasons** through the information step-by-step 3. **Answers** your questions with citations Enter your API keys below to get started! """) # API Keys Section st.subheader("🔑 API Keys") col1, col2 = st.columns(2) with col1: google_key = st.text_input( "Google API Key", type="password", value=os.getenv("GOOGLE_API_KEY", ""), help="Get your key from https://aistudio.google.com/apikey" ) with col2: openai_key = st.text_input( "OpenAI API Key", type="password", value=os.getenv("OPENAI_API_KEY", ""), help="Get your key from https://platform.openai.com/" ) # Check if API keys are provided if google_key and openai_key: # Initialize URLs in session state if 'knowledge_urls' not in st.session_state: st.session_state.knowledge_urls = ["https://www.theunwindai.com/p/mcp-vs-a2a-complementing-or-supplementing"] # Default URL if 'urls_loaded' not in st.session_state: st.session_state.urls_loaded = set() # Initialize knowledge base (cached to avoid reloading) @st.cache_resource(show_spinner="📚 Loading knowledge base...") def load_knowledge() -> Knowledge: """Load and initialize the knowledge base with vector database""" kb = Knowledge( vector_db=LanceDb( uri="tmp/lancedb", table_name="agno_docs", search_type=SearchType.vector, # Use vector search embedder=OpenAIEmbedder( api_key=openai_key ), ), ) return kb # Initialize agent (cached to avoid reloading) @st.cache_resource(show_spinner="🤖 Loading agent...") def load_agent(_kb: Knowledge) -> Agent: """Create an agent with reasoning capabilities""" return Agent( model=Gemini( id="gemini-2.5-flash", api_key=google_key ), knowledge=_kb, search_knowledge=True, # Enable knowledge search tools=[ReasoningTools(add_instructions=True)], # Add reasoning tools instructions=[ "Include sources in your response.", "Always search your knowledge before answering the question.", ], markdown=True, # Enable markdown formatting ) # Load knowledge and agent knowledge = load_knowledge() # Load initial URLs if any (only load once per URL) for url in st.session_state.knowledge_urls: if url not in st.session_state.urls_loaded: knowledge.add_content(url=url) st.session_state.urls_loaded.add(url) agent = load_agent(knowledge) # Sidebar for knowledge management with st.sidebar: st.header("📚 Knowledge Sources") st.markdown("Add URLs to expand the knowledge base:") # Show current URLs st.write("**Current sources:**") for i, url in enumerate(st.session_state.knowledge_urls): st.text(f"{i+1}. {url}") # Add new URL st.divider() new_url = st.text_input( "Add new URL", placeholder="https://www.theunwindai.com/p/mcp-vs-a2a-complementing-or-supplementing", help="Enter a URL to add to the knowledge base" ) if st.button("➕ Add URL", type="primary"): if new_url: if new_url not in st.session_state.knowledge_urls: st.session_state.knowledge_urls.append(new_url) with st.spinner("📥 Loading new documents..."): if new_url not in st.session_state.urls_loaded: knowledge.add_content(url=new_url) st.session_state.urls_loaded.add(new_url) st.success(f"✅ Added: {new_url}") st.rerun() # Refresh to show new URL else: st.error("Please enter a URL") # Main query section st.divider() st.subheader("🤔 Ask a Question") # Suggested prompts st.markdown("**Try these prompts:**") col1, col2, col3 = st.columns(3) with col1: if st.button("What is MCP?", use_container_width=True): st.session_state.query = "What is MCP (Model Context Protocol) and how does it work?" with col2: if st.button("MCP vs A2A", use_container_width=True): st.session_state.query = "How do MCP and A2A protocols differ, and are they complementary or competing?" with col3: if st.button("Agent Communication", use_container_width=True): st.session_state.query = "How do MCP and A2A work together in AI agent systems for communication and tool access?" # Query input query = st.text_area( "Your question:", value=st.session_state.get("query", "What is the difference between MCP and A2A protocols?"), height=100, help="Ask anything about the loaded knowledge sources" ) # Run button if st.button("🚀 Get Answer with Reasoning", type="primary"): if query: # Create containers for streaming updates col1, col2 = st.columns([1, 1]) with col1: st.markdown("### 🧠 Reasoning Process") reasoning_container = st.container() reasoning_placeholder = reasoning_container.empty() with col2: st.markdown("### 💡 Answer") answer_container = st.container() answer_placeholder = answer_container.empty() # Variables to accumulate content citations = [] answer_text = "" reasoning_text = "" # Stream the agent's response with st.spinner("🔍 Searching and reasoning..."): for chunk in agent.run( query, stream=True, # Enable streaming stream_events=True, # Stream all events including reasoning ): # Update reasoning display if hasattr(chunk, 'reasoning_content') and chunk.reasoning_content: reasoning_text = chunk.reasoning_content reasoning_placeholder.markdown( reasoning_text, unsafe_allow_html=True ) # Update answer display if hasattr(chunk, 'content') and chunk.content and isinstance(chunk.content, str): answer_text += chunk.content answer_placeholder.markdown( answer_text, unsafe_allow_html=True ) # Collect citations if hasattr(chunk, 'citations') and chunk.citations: if hasattr(chunk.citations, 'urls') and chunk.citations.urls: citations = chunk.citations.urls # Show citations if available if citations: st.divider() st.subheader("📚 Sources") for cite in citations: title = cite.title or cite.url st.markdown(f"- [{title}]({cite.url})") else: st.error("Please enter a question") else: # Show instructions if API keys are missing st.info(""" 👋 **Welcome! To use this app, you need:** 1. **Google API Key** - For Gemini AI model - Sign up at [aistudio.google.com](https://aistudio.google.com/apikey) 2. **OpenAI API Key** - For embeddings - Sign up at [platform.openai.com](https://platform.openai.com/) Once you have both keys, enter them above to start! """) # Footer with explanation st.divider() with st.expander("📖 How This Works"): st.markdown(""" **This app uses the Agno framework to create an intelligent Q&A system:** 1. **Knowledge Loading**: URLs are processed and stored in a vector database (LanceDB) 2. **Vector Search**: Uses OpenAI's embeddings for semantic search to find relevant information 3. **Reasoning Tools**: The agent uses special tools to think through problems step-by-step 4. **Gemini AI**: Google's Gemini model processes the information and generates answers **Key Components:** - `Knowledge`: Manages document loading from URLs - `LanceDb`: Vector database for efficient similarity search - `OpenAIEmbedder`: Converts text to embeddings using OpenAI's embedding model - `ReasoningTools`: Enables step-by-step reasoning - `Agent`: Orchestrates everything to answer questions """)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "rag_tutorials/agentic_rag_with_reasoning/rag_reasoning_agent.py", "license": "Apache License 2.0", "lines": 217, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/ai_consultant_agent/ai_consultant_agent.py
import logging from typing import Dict, Any, List, Union from dataclasses import dataclass import base64 import requests import os # Google ADK imports from google.adk.agents import LlmAgent from google.adk.tools import google_search from google.adk.sessions import InMemorySessionService from google.adk.runners import Runner # Define constants for the agent configuration MODEL_ID = "gemini-2.5-flash" APP_NAME = "ai_consultant_agent" USER_ID = "consultant-user" SESSION_ID = "consultant-session" # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def sanitize_bytes_for_json(obj: Any) -> Any: """ Recursively convert bytes objects to strings to ensure JSON serializability. Args: obj: Any object that might contain bytes Returns: Object with all bytes converted to strings """ if isinstance(obj, bytes): try: # Try to decode as UTF-8 text first return obj.decode('utf-8') except UnicodeDecodeError: # If not valid UTF-8, encode as base64 string return base64.b64encode(obj).decode('ascii') elif isinstance(obj, dict): return {key: sanitize_bytes_for_json(value) for key, value in obj.items()} elif isinstance(obj, list): return [sanitize_bytes_for_json(item) for item in obj] elif isinstance(obj, tuple): return tuple(sanitize_bytes_for_json(item) for item in obj) else: return obj def safe_tool_wrapper(tool_func): """ Wrapper to ensure tool functions never return bytes objects. Args: tool_func: The original tool function Returns: Wrapped function that sanitizes output """ def wrapped_tool(*args, **kwargs): try: result = tool_func(*args, **kwargs) return sanitize_bytes_for_json(result) except Exception as e: logger.error(f"Error in tool {tool_func.__name__}: {e}") return { "error": f"Tool execution failed: {str(e)}", "tool": tool_func.__name__, "status": "error" } # Preserve function metadata wrapped_tool.__name__ = tool_func.__name__ wrapped_tool.__doc__ = tool_func.__doc__ return wrapped_tool @dataclass class MarketInsight: """Structure for market research insights""" category: str finding: str confidence: float source: str def analyze_market_data(research_query: str, industry: str = "") -> Dict[str, Any]: """ Analyze market data and generate insights Args: research_query: The business query to analyze industry: Optional industry context Returns: Market analysis insights and recommendations """ # Simulate market analysis - in real implementation this would process actual search results insights = [] if "startup" in research_query.lower() or "launch" in research_query.lower(): insights.extend([ MarketInsight("Market Opportunity", "Growing market with moderate competition", 0.8, "Market Research"), MarketInsight("Risk Assessment", "Standard startup risks apply - funding, competition", 0.7, "Analysis"), MarketInsight("Recommendation", "Conduct MVP testing before full launch", 0.9, "Strategic Planning") ]) if "saas" in research_query.lower() or "software" in research_query.lower(): insights.extend([ MarketInsight("Technology Trend", "Cloud-based solutions gaining adoption", 0.9, "Tech Analysis"), MarketInsight("Customer Behavior", "Businesses prefer subscription models", 0.8, "Market Study") ]) if industry: insights.append( MarketInsight("Industry Specific", f"{industry} sector shows growth potential", 0.7, "Industry Report") ) return { "query": research_query, "industry": industry, "insights": [ { "category": insight.category, "finding": insight.finding, "confidence": insight.confidence, "source": insight.source } for insight in insights ], "summary": f"Analysis completed for: {research_query}", "total_insights": len(insights) } def generate_strategic_recommendations(analysis_data: Dict[str, Any]) -> List[Dict[str, Any]]: """ Generate strategic business recommendations based on analysis Args: analysis_data: Market analysis results Returns: List of strategic recommendations """ recommendations = [] # Generate recommendations based on insights insights = analysis_data.get("insights", []) if any("startup" in insight["finding"].lower() for insight in insights): recommendations.append({ "category": "Market Entry Strategy", "priority": "High", "recommendation": "Implement phased market entry with MVP testing", "rationale": "Reduces risk and validates market fit before major investment", "timeline": "3-6 months", "action_items": [ "Develop minimum viable product", "Identify target customer segment", "Conduct market validation tests" ] }) if any("saas" in insight["finding"].lower() for insight in insights): recommendations.append({ "category": "Technology Strategy", "priority": "Medium", "recommendation": "Focus on cloud-native architecture and subscription model", "rationale": "Aligns with market trends and customer preferences", "timeline": "2-4 months", "action_items": [ "Design scalable cloud infrastructure", "Implement subscription billing system", "Plan for multi-tenant architecture" ] }) # Always include risk management recommendations.append({ "category": "Risk Management", "priority": "High", "recommendation": "Establish comprehensive risk monitoring framework", "rationale": "Proactive risk management is essential for business success", "timeline": "1-2 months", "action_items": [ "Identify key business risks", "Develop mitigation strategies", "Implement monitoring systems" ] }) return recommendations def perplexity_search(query: str, system_prompt: str = "Be precise and concise. Focus on business insights and market data.") -> Dict[str, Any]: """Search the web using Perplexity AI for real-time information and insights.""" try: api_key = os.getenv("PERPLEXITY_API_KEY") if not api_key: return {"error": "Perplexity API key not found. Please set PERPLEXITY_API_KEY environment variable.", "query": query, "status": "error"} response = requests.post("https://api.perplexity.ai/chat/completions", json={"model": "sonar", "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": query}]}, headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, timeout=30) response.raise_for_status() result = response.json() if "choices" in result and result["choices"]: return {"query": query, "content": result["choices"][0]["message"]["content"], "citations": result.get("citations", []), "search_results": result.get("search_results", []), "status": "success", "source": "Perplexity AI", "model": result.get("model", "sonar"), "usage": result.get("usage", {}), "response_id": result.get("id", ""), "created": result.get("created", 0)} return {"error": "No response content found", "query": query, "status": "error", "raw_response": result} except Exception as e: return {"error": f"Error: {str(e)}", "query": query, "status": "error"} # Define the consultant tools with safety wrappers consultant_tools = [ safe_tool_wrapper(analyze_market_data), safe_tool_wrapper(generate_strategic_recommendations), safe_tool_wrapper(perplexity_search) ] INSTRUCTIONS = """You are a senior AI business consultant specializing in market analysis and strategic planning. Your expertise includes: - Business strategy development and recommendations - Risk assessment and mitigation planning - Implementation planning with timelines - Market analysis using your knowledge and available tools - Real-time web research using Perplexity AI search capabilities When consulting with clients: 1. Use Perplexity search to gather current market data, competitor information, and industry trends from the web 2. Use the market analysis tool to process business queries and generate insights 3. Use the strategic recommendations tool to create actionable business advice 4. Provide clear, specific recommendations with implementation timelines 5. Focus on practical solutions that drive measurable business outcomes **Core Responsibilities:** - Conduct real-time web research using Perplexity AI for current market data and trends - Analyze competitive landscapes and market opportunities using search results and your knowledge - Provide strategic guidance with clear action items based on up-to-date information - Assess risks and suggest mitigation strategies using current market conditions - Create implementation roadmaps with realistic timelines - Generate comprehensive business insights combining web research with analysis tools **Critical Rules:** - Always search for current market data, trends, and competitor information when relevant using Perplexity search - Base recommendations on sound business principles, current market insights, and real-time web data - Provide specific, actionable advice rather than generic guidance - Include timelines and success metrics in recommendations - Prioritize recommendations by business impact and feasibility - Use Perplexity search to validate assumptions and gather supporting evidence with citations - Combine search results with your analysis tools for comprehensive consultation **Search Strategy:** - Use Perplexity search for competitor analysis, market size, industry trends, and regulatory changes - Look up recent news, funding rounds, and market developments in relevant sectors - Verify market assumptions with current web data before making recommendations - Research best practices and case studies from similar businesses - Always include citations and sources when referencing search results Always maintain a professional, analytical approach while being results-oriented. Use all available tools including Perplexity search to provide comprehensive, well-researched consultation backed by current web data and citations.""" # Define the agent instance root_agent = LlmAgent( model=MODEL_ID, name=APP_NAME, description="An AI business consultant that provides market research, strategic analysis, and actionable recommendations.", instruction=INSTRUCTIONS, tools=consultant_tools, output_key="consultation_response" ) # Setup Runner and Session Service session_service = InMemorySessionService() runner = Runner( agent=root_agent, app_name=APP_NAME, session_service=session_service ) if __name__ == "__main__": print("🤖 AI Consultant Agent with Google ADK") print("=====================================") print() print("This agent provides comprehensive business consultation including:") print("• Market research and analysis") print("• Strategic recommendations") print("• Implementation planning") print("• Risk assessment") print() print("To use this agent:") print("1. Run: adk web .") print("2. Open the web interface") print("3. Select 'AI Business Consultant' agent") print("4. Start your consultation") print() print("Example queries:") print('• "I want to launch a SaaS startup for small businesses"') print('• "Should I expand my retail business to e-commerce?"') print('• "What are the market opportunities in the healthcare tech space?"') print() print("📊 Use the Eval tab in ADK web to save and evaluate consultation sessions!") print() print(f"✅ Agent '{APP_NAME}' initialized successfully!") print(f" Model: {MODEL_ID}") print(f" Tools: {len(consultant_tools)} available") print(f" Session Service: {type(session_service).__name__}") print(f" Runner: {type(runner).__name__}")
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/ai_consultant_agent/ai_consultant_agent.py", "license": "Apache License 2.0", "lines": 268, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/product_launch_intelligence_agent/product_launch_intelligence_agent.py
import streamlit as st from agno.agent import Agent from agno.run.agent import RunOutput from agno.team import Team from agno.models.openai import OpenAIChat from agno.tools.firecrawl import FirecrawlTools from dotenv import load_dotenv from textwrap import dedent import os # ---------------- Page Config ---------------- st.set_page_config( page_title="AI Product Intelligence Agent", page_icon="🚀", layout="wide", initial_sidebar_state="expanded" ) # ---------------- Environment & Agent ---------------- load_dotenv() # Add API key inputs in sidebar st.sidebar.header("🔑 API Configuration") with st.sidebar.container(): openai_key = st.text_input( "OpenAI API Key", type="password", value=os.getenv("OPENAI_API_KEY", ""), help="Required for AI agent functionality" ) firecrawl_key = st.text_input( "Firecrawl API Key", type="password", value=os.getenv("FIRECRAWL_API_KEY", ""), help="Required for web search and crawling" ) # Set environment variables if openai_key: os.environ["OPENAI_API_KEY"] = openai_key if firecrawl_key: os.environ["FIRECRAWL_API_KEY"] = firecrawl_key # Initialize team only if both keys are provided if openai_key and firecrawl_key: # Agent 1: Competitor Launch Analyst launch_analyst = Agent( name="Product Launch Analyst", description=dedent(""" You are a senior Go-To-Market strategist who evaluates competitor product launches with a critical, evidence-driven lens. Your objective is to uncover: • How the product is positioned in the market • Which launch tactics drove success (strengths) • Where execution fell short (weaknesses) • Actionable learnings competitors can leverage Always cite observable signals (messaging, pricing actions, channel mix, timing, engagement metrics). Maintain a crisp, executive tone and focus on strategic value. IMPORTANT: Conclude your report with a 'Sources:' section, listing all URLs of websites you crawled or searched for this analysis. """), model=OpenAIChat(id="gpt-4o"), tools=[FirecrawlTools(search=True, crawl=True, poll_interval=10)], debug_mode=True, markdown=True, exponential_backoff=True, delay_between_retries=2, ) # Agent 2: Market Sentiment Specialist sentiment_analyst = Agent( name="Market Sentiment Specialist", description=dedent(""" You are a market research expert specializing in sentiment analysis and consumer perception tracking. Your expertise includes: • Analyzing social media sentiment and customer feedback • Identifying positive and negative sentiment drivers • Tracking brand perception trends across platforms • Monitoring customer satisfaction and review patterns • Providing actionable insights on market reception Focus on extracting sentiment signals from social platforms, review sites, forums, and customer feedback channels. IMPORTANT: Conclude your report with a 'Sources:' section, listing all URLs of websites you crawled or searched for this analysis. """), model=OpenAIChat(id="gpt-4o"), tools=[FirecrawlTools(search=True, crawl=True, poll_interval=10)], debug_mode=True, markdown=True, exponential_backoff=True, delay_between_retries=2, ) # Agent 3: Launch Metrics Specialist metrics_analyst = Agent( name="Launch Metrics Specialist", description=dedent(""" You are a product launch performance analyst who specializes in tracking and analyzing launch KPIs. Your focus areas include: • User adoption and engagement metrics • Revenue and business performance indicators • Market penetration and growth rates • Press coverage and media attention analysis • Social media traction and viral coefficient tracking • Competitive market share analysis Always provide quantitative insights with context and benchmark against industry standards when possible. IMPORTANT: Conclude your report with a 'Sources:' section, listing all URLs of websites you crawled or searched for this analysis. """), model=OpenAIChat(id="gpt-4o"), tools=[FirecrawlTools(search=True, crawl=True, poll_interval=10)], debug_mode=True, markdown=True, exponential_backoff=True, delay_between_retries=2, ) # Create the coordinated team product_intelligence_team = Team( name="Product Intelligence Team", model=OpenAIChat(id="gpt-4o"), members=[launch_analyst, sentiment_analyst, metrics_analyst], instructions=[ "Coordinate the analysis based on the user's request type:", "1. For competitor analysis: Use the Product Launch Analyst to evaluate positioning, strengths, weaknesses, and strategic insights", "2. For market sentiment: Use the Market Sentiment Specialist to analyze social media sentiment, customer feedback, and brand perception", "3. For launch metrics: Use the Launch Metrics Specialist to track KPIs, adoption rates, press coverage, and performance indicators", "Always provide evidence-based insights with specific examples and data points", "Structure responses with clear sections and actionable recommendations", "Include sources section with all URLs crawled or searched" ], markdown=True, debug_mode=True, show_members_responses=True, ) else: product_intelligence_team = None st.warning("⚠️ Please enter both API keys in the sidebar to use the application.") # Helper to craft competitor-focused launch report for product managers def expand_competitor_report(bullet_text: str, competitor: str) -> str: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") return "" prompt = ( f"Transform the insight bullets below into a professional launch review for product managers analysing {competitor}.\n\n" f"Produce well-structured **Markdown** with a mix of tables, call-outs and concise bullet points — avoid long paragraphs.\n\n" f"=== FORMAT SPECIFICATION ===\n" f"# {competitor} – Launch Review\n\n" f"## 1. Market & Product Positioning\n" f"• Bullet point summary of how the product is positioned (max 6 bullets).\n\n" f"## 2. Launch Strengths\n" f"| Strength | Evidence / Rationale |\n|---|---|\n| … | … | (add 4-6 rows)\n\n" f"## 3. Launch Weaknesses\n" f"| Weakness | Evidence / Rationale |\n|---|---|\n| … | … | (add 4-6 rows)\n\n" f"## 4. Strategic Takeaways for Competitors\n" f"1. … (max 5 numbered recommendations)\n\n" f"=== SOURCE BULLETS ===\n{bullet_text}\n\n" f"Guidelines:\n" f"• Populate the tables with specific points derived from the bullets.\n" f"• Only include rows that contain meaningful data; omit any blank entries." ) resp: RunOutput = product_intelligence_team.run(prompt) return resp.content if hasattr(resp, "content") else str(resp) # Helper to craft market sentiment report def expand_sentiment_report(bullet_text: str, product: str) -> str: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") return "" prompt = ( f"Use the tagged bullets below to create a concise market-sentiment brief for **{product}**.\n\n" f"### Positive Sentiment\n" f"• List each positive point as a separate bullet (max 6).\n\n" f"### Negative Sentiment\n" f"• List each negative point as a separate bullet (max 6).\n\n" f"### Overall Summary\n" f"Provide a short paragraph (≤120 words) summarising the overall sentiment balance and key drivers.\n\n" f"Tagged Bullets:\n{bullet_text}" ) resp: RunOutput = product_intelligence_team.run(prompt) return resp.content if hasattr(resp, "content") else str(resp) # Helper to craft launch metrics report def expand_metrics_report(bullet_text: str, launch: str) -> str: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") return "" prompt = ( f"Convert the KPI bullets below into a launch-performance snapshot for **{launch}** suitable for an executive dashboard.\n\n" f"## Key Performance Indicators\n" f"| Metric | Value / Detail | Source |\n" f"|---|---|---|\n" f"| … | … | … | (include one row per KPI)\n\n" f"## Qualitative Signals\n" f"• Bullet list of notable qualitative insights (max 5).\n\n" f"## Summary & Implications\n" f"Brief paragraph (≤120 words) highlighting what the metrics imply about launch success and next steps.\n\n" f"KPI Bullets:\n{bullet_text}" ) resp: RunOutput = product_intelligence_team.run(prompt) return resp.content if hasattr(resp, "content") else str(resp) # ---------------- UI ---------------- st.title("🚀 AI Product Launch Intelligence Agent") st.markdown("*AI-powered insights for GTM, Product Marketing & Growth Teams*") st.divider() # Company input section st.subheader("🏢 Company Analysis") with st.container(): col1, col2 = st.columns([3, 1]) with col1: company_name = st.text_input( label="Company Name", placeholder="Enter company name (e.g., OpenAI, Tesla, Spotify)", help="This company will be analyzed by the coordinated team of specialized agents", label_visibility="collapsed" ) with col2: if company_name: st.success(f"✓ Ready to analyze **{company_name}**") st.divider() # Create tabs for analysis types analysis_tabs = st.tabs([ "🔍 Competitor Analysis", "💬 Market Sentiment", "📈 Launch Metrics" ]) # Store separate responses for each agent if "competitor_response" not in st.session_state: st.session_state.competitor_response = None if "sentiment_response" not in st.session_state: st.session_state.sentiment_response = None if "metrics_response" not in st.session_state: st.session_state.metrics_response = None # -------- Competitor Analysis Tab -------- with analysis_tabs[0]: with st.container(): st.markdown("### 🔍 Competitor Launch Analysis") with st.expander("ℹ️ About this Agent", expanded=False): st.markdown(""" **Product Launch Analyst** - Strategic GTM Expert Specializes in: - Competitive positioning analysis - Launch strategy evaluation - Strengths & weaknesses identification - Strategic recommendations """) if company_name: col1, col2 = st.columns([2, 1]) with col1: analyze_btn = st.button( "🚀 Analyze Competitor Strategy", key="competitor_btn", type="primary", use_container_width=True ) with col2: if st.session_state.competitor_response: st.success("✅ Analysis Complete") else: st.info("⏳ Ready to analyze") if analyze_btn: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") else: with st.spinner("🔍 Product Intelligence Team analyzing competitive strategy..."): try: bullets: RunOutput = product_intelligence_team.run( f"Generate up to 16 evidence-based insight bullets about {company_name}'s most recent product launches.\n" f"Format requirements:\n" f"• Start every bullet with exactly one tag: Positioning | Strength | Weakness | Learning\n" f"• Follow the tag with a concise statement (max 30 words) referencing concrete observations: messaging, differentiation, pricing, channel selection, timing, engagement metrics, or customer feedback." ) long_text = expand_competitor_report( bullets.content if hasattr(bullets, "content") else str(bullets), company_name ) st.session_state.competitor_response = long_text st.success("✅ Competitor analysis ready") st.rerun() except Exception as e: st.error(f"❌ Error: {e}") # Display results if st.session_state.competitor_response: st.divider() with st.container(): st.markdown("### 📊 Analysis Results") st.markdown(st.session_state.competitor_response) else: st.info("👆 Please enter a company name above to start the analysis") # -------- Market Sentiment Tab -------- with analysis_tabs[1]: with st.container(): st.markdown("### 💬 Market Sentiment Analysis") with st.expander("ℹ️ About this Agent", expanded=False): st.markdown(""" **Market Sentiment Specialist** - Consumer Perception Expert Specializes in: - Social media sentiment tracking - Customer feedback analysis - Brand perception monitoring - Review pattern identification """) if company_name: col1, col2 = st.columns([2, 1]) with col1: sentiment_btn = st.button( "📊 Analyze Market Sentiment", key="sentiment_btn", type="primary", use_container_width=True ) with col2: if st.session_state.sentiment_response: st.success("✅ Analysis Complete") else: st.info("⏳ Ready to analyze") if sentiment_btn: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") else: with st.spinner("💬 Product Intelligence Team analyzing market sentiment..."): try: bullets: RunOutput = product_intelligence_team.run( f"Summarize market sentiment for {company_name} in <=10 bullets. " f"Cover top positive & negative themes with source mentions (G2, Reddit, Twitter, customer reviews)." ) long_text = expand_sentiment_report( bullets.content if hasattr(bullets, "content") else str(bullets), company_name ) st.session_state.sentiment_response = long_text st.success("✅ Sentiment analysis ready") st.rerun() except Exception as e: st.error(f"❌ Error: {e}") # Display results if st.session_state.sentiment_response: st.divider() with st.container(): st.markdown("### 📈 Analysis Results") st.markdown(st.session_state.sentiment_response) else: st.info("👆 Please enter a company name above to start the analysis") # -------- Launch Metrics Tab -------- with analysis_tabs[2]: with st.container(): st.markdown("### 📈 Launch Performance Metrics") with st.expander("ℹ️ About this Agent", expanded=False): st.markdown(""" **Launch Metrics Specialist** - Performance Analytics Expert Specializes in: - User adoption metrics tracking - Revenue performance analysis - Market penetration evaluation - Press coverage monitoring """) if company_name: col1, col2 = st.columns([2, 1]) with col1: metrics_btn = st.button( "📊 Analyze Launch Metrics", key="metrics_btn", type="primary", use_container_width=True ) with col2: if st.session_state.metrics_response: st.success("✅ Analysis Complete") else: st.info("⏳ Ready to analyze") if metrics_btn: if not product_intelligence_team: st.error("⚠️ Please enter both API keys in the sidebar first.") else: with st.spinner("📈 Product Intelligence Team analyzing launch metrics..."): try: bullets: RunOutput = product_intelligence_team.run( f"List (max 10 bullets) the most important publicly available KPIs & qualitative signals for {company_name}'s recent product launches. " f"Include engagement stats, press coverage, adoption metrics, and market traction data if available." ) long_text = expand_metrics_report( bullets.content if hasattr(bullets, "content") else str(bullets), company_name ) st.session_state.metrics_response = long_text st.success("✅ Metrics analysis ready") st.rerun() except Exception as e: st.error(f"❌ Error: {e}") # Display results if st.session_state.metrics_response: st.divider() with st.container(): st.markdown("### 📊 Analysis Results") st.markdown(st.session_state.metrics_response) else: st.info("👆 Please enter a company name above to start the analysis") # ---------------- Sidebar ---------------- # Agent status indicators with st.sidebar.container(): st.markdown("### 🤖 System Status") if openai_key and firecrawl_key: st.success("✅ Product Intelligence Team ready") else: st.error("❌ API keys required") st.sidebar.divider() # Multi-agent system info with st.sidebar.container(): st.markdown("### 🎯 Coordinated Team") agents_info = [ ("🔍", "Product Launch Analyst", "Strategic GTM expert"), ("💬", "Market Sentiment Specialist", "Consumer perception expert"), ("📈", "Launch Metrics Specialist", "Performance analytics expert") ] for icon, name, desc in agents_info: with st.container(): st.markdown(f"**{icon} {name}**") st.caption(desc) st.sidebar.divider() # Analysis status if company_name: with st.sidebar.container(): st.markdown("### 📊 Analysis Status") st.markdown(f"**Company:** {company_name}") status_items = [ ("🔍", "Competitor Analysis", st.session_state.competitor_response), ("💬", "Sentiment Analysis", st.session_state.sentiment_response), ("📈", "Metrics Analysis", st.session_state.metrics_response) ] for icon, name, status in status_items: if status: st.success(f"{icon} {name} ✓") else: st.info(f"{icon} {name} ⏳") st.sidebar.divider() # Quick actions with st.sidebar.container(): st.markdown("### ⚡ Quick Actions") if company_name: st.markdown(""" **J** - Competitor analysis **K** - Market sentiment **L** - Launch metrics """)
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/product_launch_intelligence_agent/product_launch_intelligence_agent.py", "license": "Apache License 2.0", "lines": 428, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_Self-Evolving_agent/ai_Self-Evolving_agent.py
import os from dotenv import load_dotenv from evoagentx.models import OpenAILLMConfig, OpenAILLM, LiteLLMConfig, LiteLLM from evoagentx.workflow import WorkFlowGenerator, WorkFlowGraph, WorkFlow from evoagentx.agents import AgentManager from evoagentx.actions.code_extraction import CodeExtraction from evoagentx.actions.code_verification import CodeVerification from evoagentx.core.module_utils import extract_code_blocks load_dotenv() # Loads environment variables from .env file OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY") def main(): # LLM configuration openai_config = OpenAILLMConfig(model="gpt-4o-mini", openai_key=OPENAI_API_KEY, stream=True, output_response=True, max_tokens=16000) # Initialize the language model llm = OpenAILLM(config=openai_config) goal = "Generate html code for the Tetris game that can be played in the browser." target_directory = "examples/output/tetris_game" wf_generator = WorkFlowGenerator(llm=llm) workflow_graph: WorkFlowGraph = wf_generator.generate_workflow(goal=goal) # [optional] display workflow workflow_graph.display() # [optional] save workflow # workflow_graph.save_module(f"{target_directory}/workflow_demo_4o_mini.json") #[optional] load saved workflow # workflow_graph: WorkFlowGraph = WorkFlowGraph.from_file(f"{target_directory}/workflow_demo_4o_mini.json") agent_manager = AgentManager() agent_manager.add_agents_from_workflow(workflow_graph, llm_config=openai_config) workflow = WorkFlow(graph=workflow_graph, agent_manager=agent_manager, llm=llm) output = workflow.execute() # verfiy the code verification_llm_config = LiteLLMConfig(model="anthropic/claude-3-7-sonnet-20250219", anthropic_key=ANTHROPIC_API_KEY, stream=True, output_response=True, max_tokens=20000) verification_llm = LiteLLM(config=verification_llm_config) code_verifier = CodeVerification() output = code_verifier.execute( llm = verification_llm, inputs={ "requirements": goal, "code": output } ).verified_code # extract the code os.makedirs(target_directory, exist_ok=True) code_blocks = extract_code_blocks(output) if len(code_blocks) == 1: file_path = os.path.join(target_directory, "index.html") with open(file_path, "w") as f: f.write(code_blocks[0]) print(f"You can open this HTML file in a browser to play the Tetris game: {file_path}") return code_extractor = CodeExtraction() results = code_extractor.execute( llm=llm, inputs={ "code_string": output, "target_directory": target_directory, } ) print(f"Extracted {len(results.extracted_files)} files:") for filename, path in results.extracted_files.items(): print(f" - {filename}: {path}") if results.main_file: print(f"\nMain file: {results.main_file}") file_type = os.path.splitext(results.main_file)[1].lower() if file_type == '.html': print(f"You can open this HTML file in a browser to play the Tetris game") else: print(f"This is the main entry point for your application") if __name__ == "__main__": main()
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/multi_agent_apps/ai_Self-Evolving_agent/ai_Self-Evolving_agent.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
Shubhamsaboo/awesome-llm-apps:mcp_ai_agents/notion_mcp_agent/notion_mcp_agent.py
import asyncio import json import os import sys import uuid from textwrap import dedent from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.mcp import MCPTools from agno.db.sqlite import SqliteDb from mcp import StdioServerParameters from dotenv import load_dotenv # Load environment variables load_dotenv() NOTION_TOKEN = os.getenv("NOTION_API_KEY") OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") async def main(): print("\n========================================") print(" Notion MCP Terminal Agent") print("========================================\n") # Get configuration from environment or use defaults notion_token = NOTION_TOKEN openai_api_key = OPENAI_API_KEY # Prompt for page ID first page_id = None if len(sys.argv) > 1: # Use command-line argument if provided page_id = sys.argv[1] print(f"Using provided page ID from command line: {page_id}") else: # Ask the user for the page ID print("Please enter your Notion page ID:") print("(You can find this in your page URL, e.g., https://www.notion.so/workspace/Your-Page-1f5b8a8ba283...)") print("The ID is the part after the last dash and before any query parameters") user_input = input("> ") # If user input is empty, prompt again if user_input.strip(): page_id = user_input.strip() print(f"Using provided page ID: {page_id}") else: print("❌ Error: Page ID is required. Please provide a Notion page ID.") return # Generate unique user and session IDs for this terminal session user_id = f"user_{uuid.uuid4().hex[:8]}" session_id = f"session_{uuid.uuid4().hex[:8]}" print(f"User ID: {user_id}") print(f"Session ID: {session_id}") print("\nConnecting to Notion MCP server...\n") # Configure the MCP Tools server_params = StdioServerParameters( command="npx", args=["-y", "@notionhq/notion-mcp-server"], env={ "OPENAPI_MCP_HEADERS": json.dumps( {"Authorization": f"Bearer {notion_token}", "Notion-Version": "2022-06-28"} ) } ) # Start the MCP Tools session async with MCPTools(server_params=server_params) as mcp_tools: print("Connected to Notion MCP server successfully!") db = SqliteDb(db_file="agno.db") # SQLite DB for memory # Create the agent agent = Agent( name="NotionDocsAgent", model=OpenAIChat(id="gpt-4o", api_key=openai_api_key), tools=[mcp_tools], description="Agent to query and modify Notion docs via MCP", instructions=dedent(f""" You are an expert Notion assistant that helps users interact with their Notion pages. IMPORTANT INSTRUCTIONS: 1. You have direct access to Notion documents through MCP tools - make full use of them. 2. ALWAYS use the page ID: {page_id} for all operations unless the user explicitly provides another ID. 3. When asked to update, read, or search pages, ALWAYS use the appropriate MCP tool calls. 4. Be proactive in suggesting actions users can take with their Notion documents. 5. When making changes, explain what you did and confirm the changes were made. 6. If a tool call fails, explain the issue and suggest alternatives. Example tasks you can help with: - Reading page content - Searching for specific information - Adding new content or updating existing content - Creating lists, tables, and other Notion blocks - Explaining page structure - Adding comments to specific blocks The user's current page ID is: {page_id} """), markdown=True, retries=3, db=db, enable_user_memories=True, # This enables Memory for the Agent add_history_to_context=True, # Include conversation history num_history_runs=5, # Keep track of the last 5 interactions ) print("\n\nNotion MCP Agent is ready! Start chatting with your Notion pages.\n") print("Type 'exit' or 'quit' to end the conversation.\n") # Start interactive CLI session with memory and proper session management await agent.acli_app( user_id=user_id, session_id=session_id, user="You", emoji="🤖", stream=True, markdown=True, exit_on=["exit", "quit", "bye", "goodbye"] ) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "mcp_ai_agents/notion_mcp_agent/notion_mcp_agent.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:rag_tutorials/qwen_local_rag/qwen_local_rag_agent.py
import os import tempfile from datetime import datetime from typing import List import streamlit as st import bs4 from agno.agent import Agent from agno.models.ollama import Ollama from langchain_community.document_loaders import PyPDFLoader, WebBaseLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_qdrant import QdrantVectorStore from qdrant_client import QdrantClient from qdrant_client.models import Distance, VectorParams from langchain_core.embeddings import Embeddings from agno.tools.exa import ExaTools from agno.knowledge.embedder.ollama import OllamaEmbedder class OllamaEmbedderr(Embeddings): def __init__(self, model_name="snowflake-arctic-embed"): """ Initialize the OllamaEmbedderr with a specific model. Args: model_name (str): The name of the model to use for embedding. """ self.embedder = OllamaEmbedder(id=model_name, dimensions=1024) def embed_documents(self, texts: List[str]) -> List[List[float]]: return [self.embed_query(text) for text in texts] def embed_query(self, text: str) -> List[float]: return self.embedder.get_embedding(text) # Constants COLLECTION_NAME = "test-qwen-r1" # Streamlit App Initialization st.title("🐋 Qwen 3 Local RAG Reasoning Agent") # --- Add Model Info Boxes --- st.info("**Qwen3:** The latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models.") st.info("**Gemma 3:** These models are multimodal—processing text and images—and feature a 128K context window with support for over 140 languages.") # ------------------------- # Session State Initialization if 'model_version' not in st.session_state: st.session_state.model_version = "qwen3:1.7b" # Default to lighter model if 'vector_store' not in st.session_state: st.session_state.vector_store = None if 'processed_documents' not in st.session_state: st.session_state.processed_documents = [] if 'history' not in st.session_state: st.session_state.history = [] if 'exa_api_key' not in st.session_state: st.session_state.exa_api_key = "" if 'use_web_search' not in st.session_state: st.session_state.use_web_search = False if 'force_web_search' not in st.session_state: st.session_state.force_web_search = False if 'similarity_threshold' not in st.session_state: st.session_state.similarity_threshold = 0.7 if 'rag_enabled' not in st.session_state: st.session_state.rag_enabled = True # RAG is enabled by default # Sidebar Configuration st.sidebar.header("⚙️ Settings") # Model Selection st.sidebar.header("🧠 Model Choice") model_help = """ - qwen3:1.7b: Lighter model (MoE) - gemma3:1b: More capable but requires better GPU/RAM(32k context window) - gemma3:4b: More capable and MultiModal (Vision)(128k context window) - deepseek-r1:1.5b - qwen3:8b: More capable but requires better GPU/RAM Choose based on your hardware capabilities. """ st.session_state.model_version = st.sidebar.radio( "Select Model Version", options=["qwen3:1.7b", "gemma3:1b", "gemma3:4b", "deepseek-r1:1.5b", "qwen3:8b"], help=model_help ) st.sidebar.info("Run ollama pull qwen3:1.7b") # RAG Mode Toggle st.sidebar.header("📚 RAG Mode") st.session_state.rag_enabled = st.sidebar.toggle("Enable RAG", value=st.session_state.rag_enabled) # Clear Chat Button if st.sidebar.button("✨ Clear Chat"): st.session_state.history = [] st.rerun() # Show API Configuration only if RAG is enabled if st.session_state.rag_enabled: st.sidebar.header("🔬 Search Tuning") st.session_state.similarity_threshold = st.sidebar.slider( "Similarity Threshold", min_value=0.0, max_value=1.0, value=0.7, help="Lower values will return more documents but might be less relevant. Higher values are more strict." ) # Add in the sidebar configuration section, after the existing API inputs st.sidebar.header("🌍 Web Search") st.session_state.use_web_search = st.sidebar.checkbox("Enable Web Search Fallback", value=st.session_state.use_web_search) if st.session_state.use_web_search: exa_api_key = st.sidebar.text_input( "Exa AI API Key", type="password", value=st.session_state.exa_api_key, help="Required for web search fallback when no relevant documents are found" ) st.session_state.exa_api_key = exa_api_key # Optional domain filtering default_domains = ["arxiv.org", "wikipedia.org", "github.com", "medium.com"] custom_domains = st.sidebar.text_input( "Custom domains (comma-separated)", value=",".join(default_domains), help="Enter domains to search from, e.g.: arxiv.org,wikipedia.org" ) search_domains = [d.strip() for d in custom_domains.split(",") if d.strip()] # Utility Functions def init_qdrant() -> QdrantClient | None: """Initialize Qdrant client with local Docker setup. Returns: QdrantClient: The initialized Qdrant client if successful. None: If the initialization fails. """ try: return QdrantClient(url="http://localhost:6333") except Exception as e: st.error(f"🔴 Qdrant connection failed: {str(e)}") return None # Document Processing Functions def process_pdf(file) -> List: """Process PDF file and add source metadata.""" try: with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file: tmp_file.write(file.getvalue()) loader = PyPDFLoader(tmp_file.name) documents = loader.load() # Add source metadata for doc in documents: doc.metadata.update({ "source_type": "pdf", "file_name": file.name, "timestamp": datetime.now().isoformat() }) text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) return text_splitter.split_documents(documents) except Exception as e: st.error(f"📄 PDF processing error: {str(e)}") return [] def process_web(url: str) -> List: """Process web URL and add source metadata.""" try: loader = WebBaseLoader( web_paths=(url,), bs_kwargs=dict( parse_only=bs4.SoupStrainer( class_=("post-content", "post-title", "post-header", "content", "main") ) ) ) documents = loader.load() # Add source metadata for doc in documents: doc.metadata.update({ "source_type": "url", "url": url, "timestamp": datetime.now().isoformat() }) text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) return text_splitter.split_documents(documents) except Exception as e: st.error(f"🌐 Web processing error: {str(e)}") return [] # Vector Store Management def create_vector_store(client, texts): """Create and initialize vector store with documents.""" try: # Create collection if needed try: client.create_collection( collection_name=COLLECTION_NAME, vectors_config=VectorParams( size=1024, distance=Distance.COSINE ) ) st.success(f"📚 Created new collection: {COLLECTION_NAME}") except Exception as e: if "already exists" not in str(e).lower(): raise e # Initialize vector store vector_store = QdrantVectorStore( client=client, collection_name=COLLECTION_NAME, embedding=OllamaEmbedderr() ) # Add documents with st.spinner('📤 Uploading documents to Qdrant...'): vector_store.add_documents(texts) st.success("✅ Documents stored successfully!") return vector_store except Exception as e: st.error(f"🔴 Vector store error: {str(e)}") return None def get_web_search_agent() -> Agent: """Initialize a web search agent.""" return Agent( name="Web Search Agent", model=Ollama(id="llama3.2"), tools=[ExaTools( api_key=st.session_state.exa_api_key, include_domains=search_domains, num_results=5 )], instructions="""You are a web search expert. Your task is to: 1. Search the web for relevant information about the query 2. Compile and summarize the most relevant information 3. Include sources in your response """, debug_mode=True, markdown=True, ) def get_rag_agent() -> Agent: """Initialize the main RAG agent.""" return Agent( name="Qwen 3 RAG Agent", model=Ollama(id=st.session_state.model_version), instructions="""You are an Intelligent Agent specializing in providing accurate answers. When asked a question: - Analyze the question and answer the question with what you know. When given context from documents: - Focus on information from the provided documents - Be precise and cite specific details When given web search results: - Clearly indicate that the information comes from web search - Synthesize the information clearly Always maintain high accuracy and clarity in your responses. """, debug_mode=True, markdown=True, ) def check_document_relevance(query: str, vector_store, threshold: float = 0.7) -> tuple[bool, List]: if not vector_store: return False, [] retriever = vector_store.as_retriever( search_type="similarity_score_threshold", search_kwargs={"k": 5, "score_threshold": threshold} ) docs = retriever.invoke(query) return bool(docs), docs chat_col, toggle_col = st.columns([0.9, 0.1]) with chat_col: prompt = st.chat_input("Ask about your documents..." if st.session_state.rag_enabled else "Ask me anything...") with toggle_col: st.session_state.force_web_search = st.toggle('🌐', help="Force web search") # Check if RAG is enabled if st.session_state.rag_enabled: qdrant_client = init_qdrant() # --- Document Upload Section (Moved to Main Area) --- with st.expander("📁 Upload Documents or URLs for RAG", expanded=False): if not qdrant_client: st.warning("⚠️ Please configure Qdrant API Key and URL in the sidebar to enable document processing.") else: uploaded_files = st.file_uploader( "Upload PDF files", accept_multiple_files=True, type='pdf' ) url_input = st.text_input("Enter URL to scrape") if uploaded_files: st.write(f"Processing {len(uploaded_files)} PDF file(s)...") all_texts = [] for file in uploaded_files: if file.name not in st.session_state.processed_documents: with st.spinner(f"Processing {file.name}... "): texts = process_pdf(file) if texts: all_texts.extend(texts) st.session_state.processed_documents.append(file.name) else: st.write(f"📄 {file.name} already processed.") if all_texts: with st.spinner("Creating vector store..."): st.session_state.vector_store = create_vector_store(qdrant_client, all_texts) if url_input: if url_input not in st.session_state.processed_documents: with st.spinner(f"Scraping and processing {url_input}..."): texts = process_web(url_input) if texts: st.session_state.vector_store = create_vector_store(qdrant_client, texts) st.session_state.processed_documents.append(url_input) else: st.write(f"🔗 {url_input} already processed.") if st.session_state.vector_store: st.success("Vector store is ready.") elif not uploaded_files and not url_input: st.info("Upload PDFs or enter a URL to populate the vector store.") # Display sources in sidebar if st.session_state.processed_documents: st.sidebar.header("📚 Processed Sources") for source in st.session_state.processed_documents: if source.endswith('.pdf'): st.sidebar.text(f"📄 {source}") else: st.sidebar.text(f"🌐 {source}") if prompt: # Add user message to history st.session_state.history.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.write(prompt) if st.session_state.rag_enabled: # Existing RAG flow remains unchanged with st.spinner("🤔Evaluating the Query..."): try: rewritten_query = prompt with st.expander("Evaluating the query"): st.write(f"User's Prompt: {prompt}") except Exception as e: st.error(f"❌ Error rewriting query: {str(e)}") rewritten_query = prompt # Step 2: Choose search strategy based on force_web_search toggle context = "" docs = [] if not st.session_state.force_web_search and st.session_state.vector_store: # Try document search first retriever = st.session_state.vector_store.as_retriever( search_type="similarity_score_threshold", search_kwargs={ "k": 5, "score_threshold": st.session_state.similarity_threshold } ) docs = retriever.invoke(rewritten_query) if docs: context = "\n\n".join([d.page_content for d in docs]) st.info(f"📊 Found {len(docs)} relevant documents (similarity > {st.session_state.similarity_threshold})") elif st.session_state.use_web_search: st.info("🔄 No relevant documents found in database, falling back to web search...") # Step 3: Use web search if: # 1. Web search is forced ON via toggle, or # 2. No relevant documents found AND web search is enabled in settings if (st.session_state.force_web_search or not context) and st.session_state.use_web_search and st.session_state.exa_api_key: with st.spinner("🔍 Searching the web..."): try: web_search_agent = get_web_search_agent() web_results = web_search_agent.run(rewritten_query).content if web_results: context = f"Web Search Results:\n{web_results}" if st.session_state.force_web_search: st.info("ℹ️ Using web search as requested via toggle.") else: st.info("ℹ️ Using web search as fallback since no relevant documents were found.") except Exception as e: st.error(f"❌ Web search error: {str(e)}") # Step 4: Generate response using the RAG agent with st.spinner("🤖 Thinking..."): try: rag_agent = get_rag_agent() if context: full_prompt = f"""Context: {context} Original Question: {prompt} Please provide a comprehensive answer based on the available information.""" else: full_prompt = f"Original Question: {prompt}\n" st.info("ℹ️ No relevant information found in documents or web search.") response = rag_agent.run(full_prompt) # Add assistant response to history st.session_state.history.append({ "role": "assistant", "content": response.content }) # Display assistant response with st.chat_message("assistant"): st.write(response.content) # Show sources if available if not st.session_state.force_web_search and 'docs' in locals() and docs: with st.expander("🔍 See document sources"): for i, doc in enumerate(docs, 1): source_type = doc.metadata.get("source_type", "unknown") source_icon = "📄" if source_type == "pdf" else "🌐" source_name = doc.metadata.get("file_name" if source_type == "pdf" else "url", "unknown") st.write(f"{source_icon} Source {i} from {source_name}:") st.write(f"{doc.page_content[:200]}...") except Exception as e: st.error(f"❌ Error generating response: {str(e)}") else: # Simple mode without RAG with st.spinner("🤖 Thinking..."): try: rag_agent = get_rag_agent() web_search_agent = get_web_search_agent() if st.session_state.use_web_search else None # Handle web search if forced or enabled context = "" if st.session_state.force_web_search and web_search_agent: with st.spinner("🔍 Searching the web..."): try: web_results = web_search_agent.run(prompt).content if web_results: context = f"Web Search Results:\n{web_results}" st.info("ℹ️ Using web search as requested.") except Exception as e: st.error(f"❌ Web search error: {str(e)}") # Generate response if context: full_prompt = f"""Context: {context} Question: {prompt} Please provide a comprehensive answer based on the available information.""" else: full_prompt = prompt response = rag_agent.run(full_prompt) response_content = response.content # Extract thinking process and final response import re think_pattern = r'<think>(.*?)</think>' think_match = re.search(think_pattern, response_content, re.DOTALL) if think_match: thinking_process = think_match.group(1).strip() final_response = re.sub(think_pattern, '', response_content, flags=re.DOTALL).strip() else: thinking_process = None final_response = response_content # Add assistant response to history (only the final response) st.session_state.history.append({ "role": "assistant", "content": final_response }) # Display assistant response with st.chat_message("assistant"): if thinking_process: with st.expander("🤔 See thinking process"): st.markdown(thinking_process) st.markdown(final_response) except Exception as e: st.error(f"❌ Error generating response: {str(e)}") else: st.warning("You can directly talk to qwen and gemma models locally! Toggle the RAG mode to upload documents!")
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "rag_tutorials/qwen_local_rag/qwen_local_rag_agent.py", "license": "Apache License 2.0", "lines": 434, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/ai_startup_insight_fire1_agent/ai_startup_insight_fire1_agent.py
from firecrawl import FirecrawlApp import streamlit as st import os import json from agno.agent import Agent from agno.run.agent import RunOutput from agno.models.openai import OpenAIChat st.set_page_config( page_title="Startup Info Extraction", page_icon="🔍", layout="wide" ) st.title("AI Startup Insight with Firecrawl's FIRE-1 Agent") # Sidebar for API key with st.sidebar: st.header("API Configuration") firecrawl_api_key = st.text_input("Firecrawl API Key", type="password") openai_api_key = st.text_input("OpenAI API Key", type="password") st.caption("Your API keys are securely stored and not shared.") st.markdown("---") st.markdown("### About") st.markdown("This tool extracts company information from websites using Firecrawl's FIRE-1 agent and provides AI-powered business analysis.") st.markdown("### How It Works") st.markdown("1. 🔍 **FIRE - 1 Agent** extracts structured data from websites") st.markdown("2. 🧠 **Agno Agent** analyzes the data for business insights") st.markdown("3. 📊 **Results** are presented in an organized format") # Main content # Add information about Firecrawl's capabilities st.markdown("## 🔥 Firecrawl FIRE 1 Agent Capabilities") col1, col2 = st.columns(2) with col1: st.info("**Advanced Web Extraction**\n\nFirecrawl's FIRE 1 agent combined with the extract endpoint can intelligently navigate websites to extract structured data, even from complex layouts and dynamic content.") st.success("**Interactive Navigation**\n\nThe agent can interact with buttons, links, input fields, and other dynamic elements to access hidden information.") with col2: st.warning("**Multi-page Processing**\n\nFIRE can handle pagination and multi-step processes, allowing it to gather comprehensive data across entire websites.") st.error("**Intelligent Data Structuring**\n\nThe agent automatically structures extracted information according to your specified schema, making it immediately usable.") st.markdown("---") st.markdown("### 🌐 Enter Website URLs") st.markdown("Provide one or more company website URLs (one per line) to extract information.") website_urls = st.text_area("Website URLs (one per line)", placeholder="https://example.com\nhttps://another-company.com") # Define a JSON schema directly without Pydantic extraction_schema = { "type": "object", "properties": { "company_name": { "type": "string", "description": "The official name of the company or startup" }, "company_description": { "type": "string", "description": "A description of what the company does and its value proposition" }, "company_mission": { "type": "string", "description": "The company's mission statement or purpose" }, "product_features": { "type": "array", "items": { "type": "string" }, "description": "Key features or capabilities of the company's products/services" }, "contact_phone": { "type": "string", "description": "Company's contact phone number if available" } }, "required": ["company_name", "company_description", "product_features"] } # Custom CSS for better UI st.markdown(""" <style> .stButton button { background-color: #FF4B4B; color: white; font-weight: bold; border-radius: 10px; padding: 0.5rem 1rem; border: none; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; } .stButton button:hover { background-color: #FF2B2B; box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15); transform: translateY(-2px); } .css-1r6slb0 { border-radius: 10px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } </style> """, unsafe_allow_html=True) # Start extraction when button is clicked if st.button("🚀 Start Analysis", type="primary"): if not website_urls.strip(): st.error("Please enter at least one website URL") else: try: with st.spinner("Extracting information from website..."): # Initialize the FirecrawlApp with the API key app = FirecrawlApp(api_key=firecrawl_api_key) # Parse the input URLs more robustly # Split by newline, strip whitespace from each line, and filter out empty lines urls = [url.strip() for url in website_urls.split('\n') if url.strip()] # Debug: Show the parsed URLs st.info(f"Attempting to process these URLs: {urls}") if not urls: st.error("No valid URLs found after parsing. Please check your input.") elif not openai_api_key: st.warning("Please provide an OpenAI API key in the sidebar to get AI analysis.") else: # Create tabs for each URL tabs = st.tabs([f"Website {i+1}: {url}" for i, url in enumerate(urls)]) # Initialize the Agno agent once (outside the loop) if openai_api_key: agno_agent = Agent( model=OpenAIChat(id="gpt-4o", api_key=openai_api_key), instructions="""You are an expert business analyst who provides concise, insightful summaries of companies. You will be given structured data about a company including its name, description, mission, and product features. Your task is to analyze this information and provide a brief, compelling summary that highlights: 1. What makes this company unique or innovative 2. The core value proposition for customers 3. The potential market impact or growth opportunities Keep your response under 150 words, be specific, and focus on actionable insights. """, markdown=True ) # Process each URL one at a time for i, (url, tab) in enumerate(zip(urls, tabs)): with tab: st.markdown(f"### 🔍 Analyzing: {url}") st.markdown("<hr style='border: 2px solid #FF4B4B; border-radius: 5px;'>", unsafe_allow_html=True) with st.spinner(f"FIRE agent is extracting information from {url}..."): try: # Extract data for this single URL data = app.extract( [url], # Pass as a list with a single URL params={ 'prompt': ''' Analyze this company website thoroughly and extract comprehensive information. 1. Company Information: - Identify the official company name Explain: This is the legal name the company operates under. - Extract a detailed yet concise description of what the company does - Find the company's mission statement or purpose Explain: What problem is the company trying to solve? How do they aim to make a difference? 2. Product/Service Information: - Identify 3-5 specific product features or service offerings Explain: What are the key things their product or service can do? Describe as if explaining to a non-expert. - Focus on concrete capabilities rather than marketing claims Explain: What does the product actually do, in simple terms, rather than how it's advertised? - Be specific about what the product/service actually does Explain: Give examples of how a customer might use this product or service in their daily life. 3. Contact Information: - Find direct contact methods (phone numbers) Explain: How can a potential customer reach out to speak with someone at the company? - Only extract contact information that is explicitly provided Explain: We're looking for official contact details, not inferring or guessing. Important guidelines: - Be thorough but concise in your descriptions - Extract factual information, not marketing language - If information is not available, do not make assumptions - For each piece of information, provide a brief, simple explanation of what it means and why it's important - Include a layman's explanation of what the company does, as if explaining to someone with no prior knowledge of the industry or technology involved ''', 'schema': extraction_schema, 'agent': {"model": "FIRE-1"} } ) # Check if extraction was successful if data and data.get('data'): # Display extracted data st.subheader("📊 Extracted Information") company_data = data.get('data') # Display company name prominently if 'company_name' in company_data: st.markdown(f"{company_data['company_name']}") # Display other extracted fields for key, value in company_data.items(): if key == 'company_name': continue # Already displayed above display_key = key.replace('_', ' ').capitalize() if value: # Only display if there's a value if isinstance(value, list): st.markdown(f"**{display_key}:**") for item in value: st.markdown(f"- {item}") elif isinstance(value, str): st.markdown(f"**{display_key}:** {value}") elif isinstance(value, bool): st.markdown(f"**{display_key}:** {str(value)}") else: st.write(f"**{display_key}:**", value) # Process with Agno agent if openai_api_key: with st.spinner("Generating AI analysis..."): # Run the agent with the extracted data agent_response: RunOutput = agno_agent.run(f"Analyze this company data and provide insights: {json.dumps(company_data)}") # Display the agent's analysis in a highlighted box st.subheader("🧠 AI Business Analysis") st.markdown(agent_response.content) # Show raw data in expander with st.expander("🔍 View Raw API Response"): st.json(data) # Add processing details with st.expander("ℹ️ Processing Details"): st.markdown("**FIRE Agent Actions:**") st.markdown("- 🔍 Scanned website content and structure") st.markdown("- 🖱️ Interacted with necessary page elements") st.markdown("- 📊 Extracted and structured data according to schema") st.markdown("- 🧠 Applied AI reasoning to identify relevant information") if 'status' in data: st.markdown(f"**Status:** {data['status']}") if 'expiresAt' in data: st.markdown(f"**Data Expires:** {data['expiresAt']}") else: st.error(f"No data was extracted from {url}. The website might be inaccessible, or the content structure may not match the expected format.") except Exception as e: st.error(f"Error processing {url}: {str(e)}") except Exception as e: st.error(f"Error during extraction: {str(e)}")
{ "repo_id": "Shubhamsaboo/awesome-llm-apps", "file_path": "advanced_ai_agents/single_agent_apps/ai_startup_insight_fire1_agent/ai_startup_insight_fire1_agent.py", "license": "Apache License 2.0", "lines": 223, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
Stability-AI/generative-models:scripts/sampling/simple_video_sample_4d2.py
import os import sys from glob import glob from typing import List, Optional from tqdm import tqdm sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), "../../"))) import numpy as np import torch from fire import Fire from scripts.demo.sv4d_helpers import ( load_model, preprocess_video, read_video, run_img2vid, save_video, ) from sgm.modules.encoders.modules import VideoPredictionEmbedderWithEncoder sv4d2_configs = { "sv4d2": { "T": 12, # number of frames per sample "V": 4, # number of views per sample "model_config": "scripts/sampling/configs/sv4d2.yaml", "version_dict": { "T": 12 * 4, "options": { "discretization": 1, "cfg": 2.0, "min_cfg": 2.0, "num_views": 4, "sigma_min": 0.002, "sigma_max": 700.0, "rho": 7.0, "guider": 2, "force_uc_zero_embeddings": [ "cond_frames", "cond_frames_without_noise", "cond_view", "cond_motion", ], "additional_guider_kwargs": { "additional_cond_keys": ["cond_view", "cond_motion"] }, }, }, }, "sv4d2_8views": { "T": 5, # number of frames per sample "V": 8, # number of views per sample "model_config": "scripts/sampling/configs/sv4d2_8views.yaml", "version_dict": { "T": 5 * 8, "options": { "discretization": 1, "cfg": 2.5, "min_cfg": 1.5, "num_views": 8, "sigma_min": 0.002, "sigma_max": 700.0, "rho": 7.0, "guider": 5, "force_uc_zero_embeddings": [ "cond_frames", "cond_frames_without_noise", "cond_view", "cond_motion", ], "additional_guider_kwargs": { "additional_cond_keys": ["cond_view", "cond_motion"] }, }, }, }, } def sample( input_path: str = "assets/sv4d_videos/camel.gif", # Can either be image file or folder with image files model_path: Optional[str] = "checkpoints/sv4d2.safetensors", output_folder: Optional[str] = "outputs", num_steps: Optional[int] = 50, img_size: int = 576, # image resolution n_frames: int = 21, # number of input and output video frames seed: int = 23, encoding_t: int = 8, # Number of frames encoded at a time! This eats most VRAM. Reduce if necessary. decoding_t: int = 4, # Number of frames decoded at a time! This eats most VRAM. Reduce if necessary. device: str = "cuda", elevations_deg: Optional[List[float]] = 0.0, azimuths_deg: Optional[List[float]] = None, image_frame_ratio: Optional[float] = 0.9, verbose: Optional[bool] = False, remove_bg: bool = False, ): """ Simple script to generate multiple novel-view videos conditioned on a video `input_path` or multiple frames, one for each image file in folder `input_path`. If you run out of VRAM, try decreasing `decoding_t` and `encoding_t`. """ # Set model config assert os.path.basename(model_path) in [ "sv4d2.safetensors", "sv4d2_8views.safetensors", ] sv4d2_model = os.path.splitext(os.path.basename(model_path))[0] config = sv4d2_configs[sv4d2_model] print(sv4d2_model, config) T = config["T"] V = config["V"] model_config = config["model_config"] version_dict = config["version_dict"] F = 8 # vae factor to downsize image->latent C = 4 H, W = img_size, img_size n_views = V + 1 # number of output video views (1 input view + 8 novel views) subsampled_views = np.arange(n_views) version_dict["H"] = H version_dict["W"] = W version_dict["C"] = C version_dict["f"] = F version_dict["options"]["num_steps"] = num_steps torch.manual_seed(seed) output_folder = os.path.join(output_folder, sv4d2_model) os.makedirs(output_folder, exist_ok=True) # Read input video frames i.e. images at view 0 print(f"Reading {input_path}") base_count = len(glob(os.path.join(output_folder, "*.mp4"))) // n_views processed_input_path = preprocess_video( input_path, remove_bg=remove_bg, n_frames=n_frames, W=W, H=H, output_folder=output_folder, image_frame_ratio=image_frame_ratio, base_count=base_count, ) images_v0 = read_video(processed_input_path, n_frames=n_frames, device=device) images_t0 = torch.zeros(n_views, 3, H, W).float().to(device) # Get camera viewpoints if isinstance(elevations_deg, float) or isinstance(elevations_deg, int): elevations_deg = [elevations_deg] * n_views assert ( len(elevations_deg) == n_views ), f"Please provide 1 value, or a list of {n_views} values for elevations_deg! Given {len(elevations_deg)}" if azimuths_deg is None: # azimuths_deg = np.linspace(0, 360, n_views + 1)[1:] % 360 azimuths_deg = ( np.array([0, 60, 120, 180, 240]) if sv4d2_model == "sv4d2" else np.array([0, 30, 75, 120, 165, 210, 255, 300, 330]) ) assert ( len(azimuths_deg) == n_views ), f"Please provide a list of {n_views} values for azimuths_deg! Given {len(azimuths_deg)}" polars_rad = np.array([np.deg2rad(90 - e) for e in elevations_deg]) azimuths_rad = np.array( [np.deg2rad((a - azimuths_deg[-1]) % 360) for a in azimuths_deg] ) # Initialize image matrix img_matrix = [[None] * n_views for _ in range(n_frames)] for i, v in enumerate(subsampled_views): img_matrix[0][i] = images_t0[v].unsqueeze(0) for t in range(n_frames): img_matrix[t][0] = images_v0[t] # Load SV4D++ model model, _ = load_model( model_config, device, version_dict["T"], num_steps, verbose, model_path, ) model.en_and_decode_n_samples_a_time = decoding_t for emb in model.conditioner.embedders: if isinstance(emb, VideoPredictionEmbedderWithEncoder): emb.en_and_decode_n_samples_a_time = encoding_t # Sampling novel-view videos v0 = 0 view_indices = np.arange(V) + 1 t0_list = ( range(0, n_frames, T-1) if sv4d2_model == "sv4d2" else range(0, n_frames - T + 1, T - 1) ) for t0 in tqdm(t0_list): if t0 + T > n_frames: t0 = n_frames - T frame_indices = t0 + np.arange(T) print(f"Sampling frames {frame_indices}") image = img_matrix[t0][v0] cond_motion = torch.cat([img_matrix[t][v0] for t in frame_indices], 0) cond_view = torch.cat([img_matrix[t0][v] for v in view_indices], 0) polars = polars_rad[subsampled_views[1:]][None].repeat(T, 0).flatten() azims = azimuths_rad[subsampled_views[1:]][None].repeat(T, 0).flatten() polars = (polars - polars_rad[v0] + torch.pi / 2) % (torch.pi * 2) azims = (azims - azimuths_rad[v0]) % (torch.pi * 2) cond_mv = False if t0 == 0 else True samples = run_img2vid( version_dict, model, image, seed, polars, azims, cond_motion, cond_view, decoding_t, cond_mv=cond_mv, ) samples = samples.view(T, V, 3, H, W) for i, t in enumerate(frame_indices): for j, v in enumerate(view_indices): img_matrix[t][v] = samples[i, j][None] * 2 - 1 # Save output videos for v in view_indices: vid_file = os.path.join(output_folder, f"{base_count:06d}_v{v:03d}.mp4") print(f"Saving {vid_file}") save_video( vid_file, [img_matrix[t][v] for t in range(n_frames) if img_matrix[t][v] is not None], ) if __name__ == "__main__": Fire(sample)
{ "repo_id": "Stability-AI/generative-models", "file_path": "scripts/sampling/simple_video_sample_4d2.py", "license": "MIT License", "lines": 220, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:scripts/sync_from_framework.py
#!/usr/bin/env python3 """ SuperClaude Framework Sync Script Automated pull-sync with namespace isolation for Plugin distribution This script synchronizes content from SuperClaude_Framework repository and transforms it for distribution as a Claude Code plugin with proper namespace isolation (sc: prefix for commands, sc- prefix for filenames). Usage: python scripts/sync_from_framework.py [OPTIONS] Options: --framework-repo URL Framework repository URL --plugin-root PATH Plugin repository root path --dry-run Preview changes without applying --output-report PATH Save sync report to file """ import sys import argparse import tempfile import shutil import hashlib from pathlib import Path from typing import Dict, List, Tuple, Optional import json import re import subprocess from dataclasses import dataclass, asdict from datetime import datetime import logging # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) class ProtectionViolationError(RuntimeError): """Raised when sync would overwrite a Plugin-owned file listed in PROTECTED_PATHS.""" pass @dataclass class SyncResult: """Results from sync operation.""" success: bool timestamp: str framework_commit: str framework_version: str files_synced: int files_modified: int commands_transformed: int agents_transformed: int mcp_servers_merged: int warnings: List[str] errors: List[str] def to_dict(self) -> dict: return asdict(self) class ContentTransformer: """Transforms Framework content for Plugin namespace.""" # Regex patterns for transformation COMMAND_HEADER_PATTERN = re.compile(r'^(#+\s+)/(\w+)', re.MULTILINE) COMMAND_REF_PATTERN = re.compile(r'(?<![/\w])/(\w+)(?=\s|$|:|`|\)|\])') LINK_REF_PATTERN = re.compile(r'\[/(\w+)\]') FRONTMATTER_NAME_PATTERN = re.compile(r'^name:\s*(.+)$', re.MULTILINE) @staticmethod def transform_command(content: str, filename: str) -> str: """ Transform command content for sc: namespace. Transformations: - Header: # /brainstorm → # /sc:brainstorm - References: /analyze → /sc:analyze - Links: [/task] → [/sc:task] Args: content: Original command file content filename: Command filename (for logging) Returns: Transformed content with sc: namespace """ logger.debug(f"Transforming command: {filename}") # Transform main header content = ContentTransformer.COMMAND_HEADER_PATTERN.sub( r'\1/sc:\2', content ) # Transform command references in text content = ContentTransformer.COMMAND_REF_PATTERN.sub( r'/sc:\1', content ) # Transform command references in links content = ContentTransformer.LINK_REF_PATTERN.sub( r'[/sc:\1]', content ) return content @staticmethod def transform_agent(content: str, filename: str) -> str: """ Transform agent frontmatter name. Transformations: - name: backend-architect → name: sc-backend-architect Args: content: Original agent file content filename: Agent filename (for logging) Returns: Transformed content with sc- prefix in name field """ logger.debug(f"Transforming agent: {filename}") # Parse frontmatter frontmatter_pattern = re.compile( r'^---\n(.*?)\n---', re.DOTALL | re.MULTILINE ) match = frontmatter_pattern.search(content) if not match: logger.warning(f"No frontmatter found in agent: {filename}") return content frontmatter = match.group(1) # Transform name field (add sc- prefix if not already present) def add_prefix(match): name = match.group(1).strip() if not name.startswith('sc-'): return f'name: sc-{name}' return match.group(0) frontmatter = ContentTransformer.FRONTMATTER_NAME_PATTERN.sub( add_prefix, frontmatter ) # Replace frontmatter content = frontmatter_pattern.sub( f'---\n{frontmatter}\n---', content, count=1 ) return content class FileSyncer: """Handles file synchronization with git integration.""" def __init__(self, plugin_root: Path, dry_run: bool = False): self.plugin_root = plugin_root self.dry_run = dry_run self.git_available = self._check_git() def _check_git(self) -> bool: """Check if git is available and repo is initialized.""" try: subprocess.run( ['git', 'rev-parse', '--git-dir'], cwd=self.plugin_root, capture_output=True, check=True ) return True except (subprocess.CalledProcessError, FileNotFoundError): logger.warning("Git not available - file operations will not preserve history") return False def sync_directory( self, source_dir: Path, dest_dir: Path, filename_prefix: str = "", transform_fn=None ) -> Dict[str, int]: """ Sync directory with namespace prefix and transformation. Args: source_dir: Source directory path dest_dir: Destination directory path filename_prefix: Prefix to add to filenames (e.g., 'sc-') transform_fn: Optional content transformation function Returns: Statistics dict with counts of synced/modified files """ stats = {'synced': 0, 'modified': 0, 'renamed': 0} if not source_dir.exists(): logger.warning(f"Source directory not found: {source_dir}") return stats dest_dir.mkdir(parents=True, exist_ok=True) # Get existing files in dest (with sc- prefix) existing_files = {f.name: f for f in dest_dir.glob('*.md')} synced_files = set() for source_file in source_dir.glob('*.md'): # Apply filename prefix new_name = f"{filename_prefix}{source_file.name}" synced_files.add(new_name) dest_file = dest_dir / new_name # Read and transform content content = source_file.read_text(encoding='utf-8') if transform_fn: content = transform_fn(content, source_file.name) # Check if file exists with different name (needs git mv) old_unprefixed = source_file.name old_file_path = dest_dir / old_unprefixed if old_file_path.exists() and new_name != old_unprefixed: # File needs renaming: use git mv to preserve history if self.git_available: self._git_mv(old_file_path, dest_file) stats['renamed'] += 1 else: # Fallback to regular rename if not self.dry_run: old_file_path.rename(dest_file) stats['renamed'] += 1 logger.info(f" 📝 Renamed: {old_unprefixed} → {new_name}") # Write content if not self.dry_run: dest_file.write_text(content, encoding='utf-8') if dest_file.exists(): stats['modified'] += 1 else: stats['synced'] += 1 # Remove files that no longer exist in source # (only remove files with prefix that aren't in synced set) for filename, filepath in existing_files.items(): if filename.startswith(filename_prefix) and filename not in synced_files: if not self.dry_run: filepath.unlink() logger.info(f" 🗑️ Removed: {filepath.relative_to(self.plugin_root)}") return stats def _git_mv(self, old_path: Path, new_path: Path): """Use git mv to preserve history.""" if self.dry_run: logger.info(f" [DRY RUN] git mv {old_path.name} {new_path.name}") return try: subprocess.run( ['git', 'mv', str(old_path), str(new_path)], cwd=self.plugin_root, check=True, capture_output=True ) logger.info(f" 📝 Renamed (git mv): {old_path.name} → {new_path.name}") except subprocess.CalledProcessError as e: # Fallback to regular rename logger.warning(f" ⚠️ Git mv failed, using regular rename: {e}") old_path.rename(new_path) def copy_directory(self, source_dir: Path, dest_dir: Path) -> int: """ Copy directory contents as-is (no transformation). Args: source_dir: Source directory path dest_dir: Destination directory path Returns: Number of files copied """ if not source_dir.exists(): logger.warning(f"Source directory not found: {source_dir}") return 0 dest_dir.mkdir(parents=True, exist_ok=True) count = 0 for source_file in source_dir.glob('**/*'): if source_file.is_file(): rel_path = source_file.relative_to(source_dir) dest_file = dest_dir / rel_path dest_file.parent.mkdir(parents=True, exist_ok=True) if not self.dry_run: shutil.copy2(source_file, dest_file) count += 1 logger.debug(f" 📄 Copied: {rel_path}") return count class PluginJsonGenerator: """Generates .claude-plugin/plugin.json from synced commands.""" def __init__(self, plugin_root: Path): self.plugin_root = plugin_root def generate(self, framework_version: str) -> dict: """ Generate plugin.json with command mappings. Args: framework_version: Version from Framework repository Returns: Complete plugin.json dictionary """ commands_dir = self.plugin_root / 'commands' # Base metadata from existing plugin.json root_plugin_json = self.plugin_root / 'plugin.json' if root_plugin_json.exists(): base_metadata = json.loads(root_plugin_json.read_text()) else: base_metadata = { "name": "sc", "description": "SuperClaude Plugin", "author": {"name": "SuperClaude Team"}, "license": "MIT" } # Build command mappings commands = {} if commands_dir.exists(): for cmd_file in sorted(commands_dir.glob('sc-*.md')): # Extract command name from filename # sc-brainstorm.md → brainstorm cmd_name = cmd_file.stem.replace('sc-', '') # Map sc:brainstorm to path commands[f"sc:{cmd_name}"] = f"commands/{cmd_file.name}" plugin_json = { "name": "sc", "version": framework_version, "description": base_metadata.get("description", ""), "author": base_metadata.get("author", {}), "homepage": base_metadata.get("homepage", ""), "repository": base_metadata.get("repository", ""), "license": base_metadata.get("license", "MIT"), "keywords": base_metadata.get("keywords", []) } logger.info(f"✅ Generated plugin.json with {len(commands)} commands") return plugin_json def write(self, plugin_json: dict, dry_run: bool = False): """Write plugin.json to .claude-plugin/ directory.""" output_path = self.plugin_root / '.claude-plugin' / 'plugin.json' output_path.parent.mkdir(parents=True, exist_ok=True) if dry_run: logger.info(f"[DRY RUN] Would write plugin.json to: {output_path}") logger.info(json.dumps(plugin_json, indent=2)) return output_path.write_text( json.dumps(plugin_json, indent=2) + '\n', encoding='utf-8' ) logger.info(f"✅ Written: {output_path}") class McpMerger: """Safely merges MCP server configurations.""" def __init__(self, plugin_root: Path): self.plugin_root = plugin_root def merge( self, framework_mcp: dict, plugin_mcp: dict ) -> Tuple[dict, List[str]]: """ Merge MCP configurations with conflict detection. Strategy: - Framework servers take precedence - Preserve Plugin-specific servers - Log warnings for conflicts Args: framework_mcp: MCP servers from Framework plugin_mcp: MCP servers from Plugin Returns: (merged_config, warnings) """ merged = {} warnings = [] # Add Framework servers (source of truth) for name, config in framework_mcp.items(): merged[name] = config # Add Plugin-specific servers if not in Framework for name, config in plugin_mcp.items(): if name not in merged: merged[name] = config warnings.append( f"Preserved plugin-specific MCP server: {name}" ) else: # Check if configurations differ if config != merged[name]: warnings.append( f"MCP server '{name}' conflict - using Framework version" ) return merged, warnings def backup_current(self) -> Optional[Path]: """Create backup of current plugin.json.""" plugin_json = self.plugin_root / 'plugin.json' if not plugin_json.exists(): return None backup_dir = self.plugin_root / 'backups' backup_dir.mkdir(exist_ok=True) timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') backup_path = backup_dir / f'plugin.json.{timestamp}.backup' shutil.copy2(plugin_json, backup_path) logger.info(f"📦 Backup created: {backup_path}") return backup_path class FrameworkSyncer: """Main orchestrator for Framework → Plugin sync.""" # ── SYNC MAPPINGS ────────────────────────────────────────────────────────── # What to pull from Framework and transform for Plugin distribution. # Symmetric pair with PROTECTED_PATHS below: a path appears in one or the other, # never both. SYNC_MAPPINGS = { "src/superclaude/commands": "commands", # /cmd → /sc:cmd, sc- prefix "src/superclaude/agents": "agents", # name → sc-name in frontmatter # core/ and modes/ are intentionally absent — they live in PROTECTED_PATHS } # ── PROTECTED PATHS ──────────────────────────────────────────────────────── # Plugin-owned files and directories that must NEVER be overwritten by sync, # regardless of what the Framework contains. # # Algorithm: before sync → hash all protected paths → after sync → re-hash # and raise ProtectionViolationError if anything changed. # # To move a path from protected to synced: remove it here, add to SYNC_MAPPINGS. PROTECTED_PATHS: List[str] = [ # Plugin-specific documentation (Plugin spec, not Framework spec) "README.md", "README-ja.md", "README-zh.md", "BACKUP_GUIDE.md", "MIGRATION_GUIDE.md", "SECURITY.md", "CLAUDE.md", "LICENSE", ".gitignore", # Plugin configuration & marketplace metadata ".claude-plugin/", # Plugin infrastructure (workflows, scripts, tests are Plugin-owned) ".github/", "docs/", "scripts/", "tests/", "backups/", # Plugin-customized behavioral content # Plugin maintains its own tuned versions; Framework versions are ignored. "core/", "modes/", ] def __init__( self, framework_repo: str, plugin_root: Path, dry_run: bool = False ): self.framework_repo = framework_repo self.plugin_root = plugin_root self.dry_run = dry_run self.temp_dir = None self.warnings = [] self.errors = [] def sync(self) -> SyncResult: """Execute full sync workflow.""" try: logger.info("🔄 Starting Framework sync...") # Step 1: Clone Framework framework_path = self._clone_framework() framework_commit = self._get_commit_hash(framework_path) framework_version = self._get_version(framework_path) logger.info(f"📦 Framework version: {framework_version}") logger.info(f"📝 Framework commit: {framework_commit[:8]}") # Step 2: Snapshot protected files BEFORE any changes protection_snapshot = self._snapshot_protected_files() # Step 3: Create backup self._create_backup() # Step 4: Transform and sync content stats = self._sync_content(framework_path) # Step 5: Verify protected files were NOT touched self._validate_protected_files(protection_snapshot) # Step 6: Generate plugin.json self._generate_plugin_json(framework_version) # Step 7: Merge MCP configurations mcp_merged = self._merge_mcp_configs(framework_path) # Step 8: Validate sync results self._validate_sync() logger.info("✅ Sync completed successfully!") return SyncResult( success=True, timestamp=datetime.now().isoformat(), framework_commit=framework_commit, framework_version=framework_version, files_synced=stats['files_synced'], files_modified=stats['files_modified'], commands_transformed=stats['commands'], agents_transformed=stats['agents'], mcp_servers_merged=mcp_merged, warnings=self.warnings, errors=self.errors ) except ProtectionViolationError as e: # Protection violations are logged already; surface them clearly in the report self.errors.append(str(e)) return SyncResult( success=False, timestamp=datetime.now().isoformat(), framework_commit="", framework_version="", files_synced=0, files_modified=0, commands_transformed=0, agents_transformed=0, mcp_servers_merged=0, warnings=self.warnings, errors=self.errors ) except Exception as e: logger.error(f"❌ Sync failed: {e}", exc_info=True) self.errors.append(str(e)) return SyncResult( success=False, timestamp=datetime.now().isoformat(), framework_commit="", framework_version="", files_synced=0, files_modified=0, commands_transformed=0, agents_transformed=0, mcp_servers_merged=0, warnings=self.warnings, errors=self.errors ) finally: self._cleanup() # ── Protection helpers ───────────────────────────────────────────────────── @staticmethod def _hash_file(path: Path) -> str: """Return SHA-256 hex digest of a file's contents.""" h = hashlib.sha256() h.update(path.read_bytes()) return h.hexdigest() def _snapshot_protected_files(self) -> Dict[str, str]: """ Hash every file that lives under a PROTECTED_PATHS entry. Called BEFORE sync begins so we have a baseline to compare against. Returns: Mapping of relative-path-string → SHA-256 hex digest. """ snapshot: Dict[str, str] = {} for protected in self.PROTECTED_PATHS: target = self.plugin_root / protected if target.is_file(): rel = protected snapshot[rel] = self._hash_file(target) elif target.is_dir(): for f in sorted(target.rglob('*')): if f.is_file(): rel = str(f.relative_to(self.plugin_root)) snapshot[rel] = self._hash_file(f) logger.info(f"🔒 Protection snapshot: {len(snapshot)} Plugin-owned files hashed") return snapshot def _validate_protected_files(self, snapshot: Dict[str, str]) -> None: """ Re-hash every file from the snapshot and compare. Called AFTER sync to verify no protected file was touched. Raises: ProtectionViolationError: if any protected file was modified or deleted. """ violations: List[str] = [] for rel_path, original_hash in snapshot.items(): current = self.plugin_root / rel_path if not current.exists(): violations.append(f"DELETED : {rel_path}") else: current_hash = self._hash_file(current) if current_hash != original_hash: violations.append(f"MODIFIED : {rel_path}") if violations: msg = ( "🚨 PROTECTION VIOLATION — sync modified Plugin-owned files:\n" + "\n".join(f" • {v}" for v in violations) + "\n\nFix: ensure SYNC_MAPPINGS does not target any path in PROTECTED_PATHS." ) logger.error(msg) raise ProtectionViolationError(msg) logger.info(f"🔒 Protection check passed — {len(snapshot)} Plugin-owned files unchanged") # ── Core sync workflow ───────────────────────────────────────────────────── def _clone_framework(self) -> Path: """Clone Framework repository to temp directory.""" logger.info(f"📥 Cloning Framework: {self.framework_repo}") self.temp_dir = tempfile.mkdtemp(prefix='superclaude_framework_') framework_path = Path(self.temp_dir) / 'framework' try: subprocess.run( ['git', 'clone', '--depth', '1', self.framework_repo, str(framework_path)], check=True, capture_output=True, text=True ) logger.info(f"✅ Cloned to: {framework_path}") return framework_path except subprocess.CalledProcessError as e: logger.error(f"Failed to clone Framework: {e.stderr}") raise def _get_commit_hash(self, repo_path: Path) -> str: """Get current commit hash from repository.""" try: result = subprocess.run( ['git', 'rev-parse', 'HEAD'], cwd=repo_path, check=True, capture_output=True, text=True ) return result.stdout.strip() except subprocess.CalledProcessError: return "unknown" def _get_version(self, framework_path: Path) -> str: """Extract version from Framework.""" # Try to read version from plugin.json or package.json for version_file in ['plugin.json', 'package.json']: version_path = framework_path / version_file if version_path.exists(): try: data = json.loads(version_path.read_text()) if 'version' in data: return data['version'] except (json.JSONDecodeError, KeyError): continue # Fallback to current Plugin version plugin_json = self.plugin_root / 'plugin.json' if plugin_json.exists(): try: data = json.loads(plugin_json.read_text()) return data.get('version', '1.0.0') except json.JSONDecodeError: pass return '1.0.0' def _create_backup(self): """Create backup of current plugin state.""" logger.info("📦 Creating backup...") mcp_merger = McpMerger(self.plugin_root) backup_path = mcp_merger.backup_current() if backup_path: logger.info(f"✅ Backup created: {backup_path}") def _sync_content(self, framework_path: Path) -> Dict[str, int]: """Sync and transform content from Framework.""" logger.info("🔄 Syncing content...") file_syncer = FileSyncer(self.plugin_root, self.dry_run) stats = { 'files_synced': 0, 'files_modified': 0, 'commands': 0, 'agents': 0 } # Sync commands with transformation logger.info("📝 Syncing commands...") source_commands = framework_path / 'src/superclaude/commands' dest_commands = self.plugin_root / 'commands' if source_commands.exists(): cmd_stats = file_syncer.sync_directory( source_commands, dest_commands, filename_prefix='sc-', transform_fn=ContentTransformer.transform_command ) stats['commands'] = cmd_stats['synced'] + cmd_stats['modified'] stats['files_synced'] += cmd_stats['synced'] stats['files_modified'] += cmd_stats['modified'] logger.info(f"✅ Commands: {stats['commands']} transformed") # Sync agents with transformation logger.info("📝 Syncing agents...") source_agents = framework_path / 'src/superclaude/agents' dest_agents = self.plugin_root / 'agents' if source_agents.exists(): agent_stats = file_syncer.sync_directory( source_agents, dest_agents, filename_prefix='sc-', transform_fn=ContentTransformer.transform_agent ) stats['agents'] = agent_stats['synced'] + agent_stats['modified'] stats['files_synced'] += agent_stats['synced'] stats['files_modified'] += agent_stats['modified'] logger.info(f"✅ Agents: {stats['agents']} transformed") # core/ and modes/ are in PROTECTED_PATHS — Plugin maintains its own versions. # They are intentionally excluded from SYNC_MAPPINGS and will never be # overwritten here. To re-enable Framework sync for either directory, # remove it from PROTECTED_PATHS and add it back to SYNC_MAPPINGS. logger.info("🔒 core/ and modes/ are Plugin-owned (PROTECTED_PATHS) — skipping") return stats def _generate_plugin_json(self, framework_version: str): """Generate plugin.json from synced commands.""" logger.info("📄 Generating plugin.json...") generator = PluginJsonGenerator(self.plugin_root) plugin_json = generator.generate(framework_version) generator.write(plugin_json, self.dry_run) def _merge_mcp_configs(self, framework_path: Path) -> int: """Merge MCP configurations from Framework.""" logger.info("🔗 Merging MCP configurations...") # Read Framework MCP config framework_plugin_json = framework_path / 'plugin.json' framework_mcp = {} if framework_plugin_json.exists(): try: data = json.loads(framework_plugin_json.read_text()) framework_mcp = data.get('mcpServers', {}) except json.JSONDecodeError: logger.warning("Failed to read Framework plugin.json") # Read Plugin MCP config plugin_json_path = self.plugin_root / 'plugin.json' plugin_mcp = {} if plugin_json_path.exists(): try: data = json.loads(plugin_json_path.read_text()) plugin_mcp = data.get('mcpServers', {}) except json.JSONDecodeError: logger.warning("Failed to read Plugin plugin.json") # Merge configurations merger = McpMerger(self.plugin_root) merged_mcp, warnings = merger.merge(framework_mcp, plugin_mcp) # Log warnings for warning in warnings: logger.warning(f"⚠️ {warning}") self.warnings.append(warning) # Update plugin.json with merged MCP config if not self.dry_run and plugin_json_path.exists(): data = json.loads(plugin_json_path.read_text()) data['mcpServers'] = merged_mcp plugin_json_path.write_text( json.dumps(data, indent=2) + '\n', encoding='utf-8' ) logger.info(f"✅ MCP servers merged: {len(merged_mcp)}") return len(merged_mcp) def _validate_sync(self): """Validate sync results.""" logger.info("🔍 Validating sync...") # Check commands directory commands_dir = self.plugin_root / 'commands' if commands_dir.exists(): sc_commands = list(commands_dir.glob('sc-*.md')) logger.info(f"✅ Found {len(sc_commands)} sc- prefixed commands") # Check agents directory agents_dir = self.plugin_root / 'agents' if agents_dir.exists(): sc_agents = list(agents_dir.glob('sc-*.md')) logger.info(f"✅ Found {len(sc_agents)} sc- prefixed agents") # Check plugin.json plugin_json_path = self.plugin_root / '.claude-plugin' / 'plugin.json' if plugin_json_path.exists(): logger.info(f"✅ plugin.json exists at {plugin_json_path}") else: logger.warning("⚠️ plugin.json not found") def _cleanup(self): """Clean up temporary directories.""" if self.temp_dir and Path(self.temp_dir).exists(): shutil.rmtree(self.temp_dir) logger.debug(f"🧹 Cleaned up temp directory: {self.temp_dir}") def main(): """Main entry point.""" parser = argparse.ArgumentParser( description='Sync SuperClaude Framework to Plugin with namespace isolation' ) parser.add_argument( '--framework-repo', default='https://github.com/SuperClaude-Org/SuperClaude_Framework', help='Framework repository URL' ) parser.add_argument( '--plugin-root', type=Path, default=Path.cwd(), help='Plugin repository root path' ) parser.add_argument( '--dry-run', type=lambda x: x.lower() in ('true', '1', 'yes'), default=False, help='Preview changes without applying' ) parser.add_argument( '--output-report', type=Path, help='Save sync report to file' ) parser.add_argument( '--verbose', action='store_true', help='Enable verbose logging' ) args = parser.parse_args() if args.verbose: logging.getLogger().setLevel(logging.DEBUG) if args.dry_run: logger.info("🔍 DRY RUN MODE - No changes will be applied") # Run sync syncer = FrameworkSyncer( framework_repo=args.framework_repo, plugin_root=args.plugin_root, dry_run=args.dry_run ) result = syncer.sync() # Output report if args.output_report: args.output_report.write_text( json.dumps(result.to_dict(), indent=2) + '\n' ) logger.info(f"📊 Report saved to: {args.output_report}") # Print summary print("\n" + "=" * 60) print("SYNC SUMMARY") print("=" * 60) print(f"Success: {result.success}") print(f"Framework Version: {result.framework_version}") print(f"Framework Commit: {result.framework_commit[:8]}") print(f"Files Synced: {result.files_synced}") print(f"Files Modified: {result.files_modified}") print(f"Commands Transformed: {result.commands_transformed}") print(f"Agents Transformed: {result.agents_transformed}") print(f"MCP Servers Merged: {result.mcp_servers_merged}") if result.warnings: print(f"\n⚠️ Warnings: {len(result.warnings)}") for warning in result.warnings: print(f" - {warning}") if result.errors: print(f"\n❌ Errors: {len(result.errors)}") for error in result.errors: print(f" - {error}") print("=" * 60) sys.exit(0 if result.success else 1) if __name__ == '__main__': main()
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "scripts/sync_from_framework.py", "license": "MIT License", "lines": 790, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/cli/install_mcp.py
""" MCP Server Installation Module for SuperClaude Installs and manages MCP servers using the latest Claude Code API. Based on the installer logic from commit d4a17fc but adapted for modern Claude Code. """ import os import platform import shlex import subprocess from typing import Dict, List, Optional, Tuple import click # AIRIS MCP Gateway - Unified MCP solution (recommended) AIRIS_GATEWAY = { "name": "airis-mcp-gateway", "description": "Unified MCP gateway with 60+ tools, HOT/COLD management, 98% token reduction", "transport": "sse", "endpoint": "http://localhost:9400/sse", "docker_compose_url": "https://raw.githubusercontent.com/agiletec-inc/airis-mcp-gateway/main/docker-compose.dist.yml", "mcp_config_url": "https://raw.githubusercontent.com/agiletec-inc/airis-mcp-gateway/main/config/mcp-config.template.json", "repository": "https://github.com/agiletec-inc/airis-mcp-gateway", } # Individual MCP Server Registry (legacy, for users who prefer individual servers) # Adapted from commit d4a17fc with modern transport configuration MCP_SERVERS = { "sequential-thinking": { "name": "sequential-thinking", "description": "Multi-step problem solving and systematic analysis", "transport": "stdio", "command": "npx -y @modelcontextprotocol/server-sequential-thinking", "required": False, }, "context7": { "name": "context7", "description": "Official library documentation and code examples", "transport": "stdio", "command": "npx -y @upstash/context7-mcp", "required": False, }, "magic": { "name": "magic", "description": "Modern UI component generation and design systems", "transport": "stdio", "command": "npx -y @21st-dev/magic", "required": False, "api_key_env": "TWENTYFIRST_API_KEY", "api_key_description": "21st.dev API key for UI component generation", }, "playwright": { "name": "playwright", "description": "Cross-browser E2E testing and automation", "transport": "stdio", "command": "npx -y @playwright/mcp@latest", "required": False, }, "serena": { "name": "serena", "description": "Semantic code analysis and intelligent editing", "transport": "stdio", "command": "uvx --from git+https://github.com/oraios/serena serena start-mcp-server --context ide-assistant --enable-web-dashboard false --enable-gui-log-window false", "required": False, }, "morphllm-fast-apply": { "name": "morphllm-fast-apply", "description": "Fast Apply capability for context-aware code modifications", "transport": "stdio", "command": "npx -y @morph-llm/morph-fast-apply", "required": False, "api_key_env": "MORPH_API_KEY", "api_key_description": "Morph API key for Fast Apply", }, "tavily": { "name": "tavily", "description": "Web search and real-time information retrieval for deep research", "transport": "stdio", "command": "npx -y tavily-mcp@0.1.2", "required": False, "api_key_env": "TAVILY_API_KEY", "api_key_description": "Tavily API key for web search (get from https://app.tavily.com)", }, "chrome-devtools": { "name": "chrome-devtools", "description": "Chrome DevTools debugging and performance analysis", "transport": "stdio", "command": "npx -y chrome-devtools-mcp@latest", "required": False, }, } def _run_command(cmd: List[str], **kwargs) -> subprocess.CompletedProcess: """ Run a command with proper cross-platform shell handling. Args: cmd: Command as list of strings **kwargs: Additional subprocess.run arguments Returns: CompletedProcess result """ # Ensure UTF-8 encoding on all platforms to handle Unicode output if "encoding" not in kwargs: kwargs["encoding"] = "utf-8" if "errors" not in kwargs: kwargs["errors"] = "replace" # Replace undecodable bytes instead of raising if platform.system() == "Windows": # On Windows, wrap command in 'cmd /c' to properly handle commands like npx cmd = ["cmd", "/c"] + cmd return subprocess.run(cmd, **kwargs) else: # macOS/Linux: Use string format with proper shell to support aliases cmd_str = " ".join(shlex.quote(str(arg)) for arg in cmd) # Use the user's shell to execute the command, supporting aliases user_shell = os.environ.get("SHELL", "/bin/bash") return subprocess.run( cmd_str, shell=True, env=os.environ, executable=user_shell, **kwargs ) def check_docker_available() -> bool: """Check if Docker is available and running.""" try: result = _run_command( ["docker", "info"], capture_output=True, text=True, timeout=10 ) return result.returncode == 0 except (subprocess.TimeoutExpired, FileNotFoundError): return False def install_airis_gateway(dry_run: bool = False) -> bool: """ Install AIRIS MCP Gateway using Docker. Installs to ~/.superclaude/airis-mcp-gateway/ to avoid polluting the host. Returns: True if successful, False otherwise """ from pathlib import Path click.echo("\n🚀 Installing AIRIS MCP Gateway (Recommended)") click.echo( " This provides 60+ tools through a single endpoint with 98% token reduction.\n" ) # Check Docker if not check_docker_available(): click.echo(" ❌ Docker is required but not available.", err=True) click.echo( " Please install Docker: https://docs.docker.com/get-docker/", err=True ) return False click.echo(" ✅ Docker is available") # Create dedicated installation directory install_dir = Path.home() / ".superclaude" / "airis-mcp-gateway" compose_file = install_dir / "docker-compose.yml" if dry_run: click.echo(f" [DRY RUN] Would create directory: {install_dir}") click.echo(" [DRY RUN] Would download docker-compose.yml") click.echo(" [DRY RUN] Would create .env file with default configuration") click.echo(" [DRY RUN] Would run: docker compose up -d") click.echo(" [DRY RUN] Would register with Claude Code") return True # Create installation directory install_dir.mkdir(parents=True, exist_ok=True) click.echo(f" 📁 Installation directory: {install_dir}") # Download docker-compose file click.echo(" 📥 Downloading docker-compose configuration...") try: result = _run_command( [ "curl", "-fsSL", "-o", str(compose_file), AIRIS_GATEWAY["docker_compose_url"], ], capture_output=True, text=True, timeout=60, ) if result.returncode != 0: click.echo( f" ❌ Failed to download docker-compose file: {result.stderr}", err=True, ) return False except Exception as e: click.echo(f" ❌ Error downloading: {e}", err=True) return False # Download mcp-config.json (backend server definitions for the gateway) mcp_config_file = install_dir / "mcp-config.json" if not mcp_config_file.exists(): click.echo(" 📥 Downloading MCP server configuration...") try: result = _run_command( [ "curl", "-fsSL", "-o", str(mcp_config_file), AIRIS_GATEWAY["mcp_config_url"], ], capture_output=True, text=True, timeout=60, ) if result.returncode != 0: click.echo( f" ⚠️ Failed to download mcp-config.json: {result.stderr}", err=True, ) # Create a minimal default config so the gateway can start import json default_config = { "mcpServers": { "memory": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"], "env": {}, "enabled": True, "mode": "hot", "description": "Session memory", } }, "log": {"level": "info"}, } mcp_config_file.write_text(json.dumps(default_config, indent=2)) click.echo(" ✅ Created minimal default mcp-config.json") else: # Disable servers that require containers not in docker-compose.dist.yml import json try: config = json.loads(mcp_config_file.read_text()) servers_to_disable = ["airis-agent", "mindbase"] changed = False for server_name in servers_to_disable: if server_name in config.get("mcpServers", {}): config["mcpServers"][server_name]["enabled"] = False changed = True if changed: mcp_config_file.write_text(json.dumps(config, indent=2)) click.echo(" ✅ MCP server configuration downloaded") except (json.JSONDecodeError, KeyError): click.echo( " ⚠️ Could not parse mcp-config.json, using as-is", err=True, ) except Exception as e: click.echo(f" ❌ Error downloading mcp-config.json: {e}", err=True) # Create empty but valid config so Docker mount doesn't fail mcp_config_file.write_text('{"mcpServers": {}}') else: click.echo(" ✅ MCP server configuration already exists") # Create .env file if it doesn't exist env_file = install_dir / ".env" if not env_file.exists(): click.echo(" 📝 Creating .env file with default configuration...") workspace_dir = Path.home() / "github" env_content = f"""# AIRIS MCP Gateway Configuration # Edit this file to customize your setup # Workspace directory (host path mounted into containers) HOST_WORKSPACE_DIR={workspace_dir} # AIRIS mode (embedded = single-container gateway only) AIRIS_MODE=embedded # Mindbase URL (if using mindbase MCP server) MINDBASE_URL=http://host.docker.internal:18003 # Tavily API key for web search (get from https://app.tavily.com) TAVILY_API_KEY= """ env_file.write_text(env_content) click.echo(f" ✅ Created .env file at {env_file}") click.echo( f" 💡 Edit {env_file} to customize settings (e.g., add TAVILY_API_KEY)" ) else: click.echo(" ✅ .env file already exists") # Start the gateway from the installation directory click.echo(" 🐳 Starting AIRIS MCP Gateway containers...") try: result = _run_command( [ "docker", "compose", "-f", str(compose_file), "--project-directory", str(install_dir), "up", "-d", ], capture_output=True, text=True, timeout=300, ) if result.returncode != 0: click.echo(f" ❌ Failed to start containers: {result.stderr}", err=True) return False except subprocess.TimeoutExpired: click.echo(" ❌ Timeout starting containers", err=True) return False click.echo(" ✅ Gateway containers started") # Wait for gateway to become healthy click.echo(" 🔍 Checking gateway health...") import time gateway_healthy = False for attempt in range(1, 7): try: result = _run_command( ["curl", "-sf", "http://localhost:9400/health"], capture_output=True, text=True, timeout=5, ) if result.returncode == 0: click.echo(" ✅ Gateway is healthy") gateway_healthy = True break except Exception: pass if attempt < 6: click.echo(f" ⏳ Waiting for gateway to start (attempt {attempt}/6)...") time.sleep(5) if not gateway_healthy: click.echo( " ⚠️ Gateway may still be starting. Check with: curl http://localhost:9400/health", err=True, ) # Register with Claude Code # SSE transport takes the URL directly (not via npx mcp-remote) click.echo(" 📝 Registering with Claude Code...") try: cmd = [ "claude", "mcp", "add", "--scope", "user", "--transport", "sse", AIRIS_GATEWAY["name"], AIRIS_GATEWAY["endpoint"], ] result = _run_command(cmd, capture_output=True, text=True, timeout=60) if result.returncode != 0: # May already be registered if "already exists" in (result.stderr or "").lower(): click.echo(" ✅ Already registered with Claude Code") else: click.echo(f" ⚠️ Registration warning: {result.stderr}", err=True) else: click.echo(" ✅ Registered with Claude Code") except Exception as e: click.echo(f" ⚠️ Registration error: {e}", err=True) click.echo("\n✅ AIRIS MCP Gateway installed successfully!") click.echo(f"\n📁 Installed to: {install_dir}") click.echo("\n📖 Next steps:") click.echo(" • Health check: curl http://localhost:9400/health") click.echo(" • Web UI: http://localhost:9400") click.echo(f" • Manage: cd {install_dir} && docker compose logs -f") click.echo(f" • Documentation: {AIRIS_GATEWAY['repository']}") return True def check_prerequisites() -> Tuple[bool, List[str]]: """Check if required tools are available.""" errors = [] # Check Claude CLI try: result = _run_command( ["claude", "--version"], capture_output=True, text=True, timeout=10 ) if result.returncode != 0: errors.append("Claude CLI not found - required for MCP server management") except (subprocess.TimeoutExpired, FileNotFoundError): errors.append("Claude CLI not found - required for MCP server management") # Check Node.js for npm-based servers try: result = _run_command( ["node", "--version"], capture_output=True, text=True, timeout=10 ) if result.returncode != 0: errors.append("Node.js not found - required for npm-based MCP servers") else: version = result.stdout.strip() try: version_num = int(version.lstrip("v").split(".")[0]) if version_num < 18: errors.append( f"Node.js version {version} found, but version 18+ required" ) except (ValueError, IndexError): pass except (subprocess.TimeoutExpired, FileNotFoundError): errors.append("Node.js not found - required for npm-based MCP servers") # Check uv for Python-based servers (optional) try: result = _run_command( ["uv", "--version"], capture_output=True, text=True, timeout=10 ) if result.returncode != 0: click.echo("⚠️ uv not found - required for Serena MCP server", err=True) except (subprocess.TimeoutExpired, FileNotFoundError): click.echo("⚠️ uv not found - required for Serena MCP server", err=True) return len(errors) == 0, errors def check_mcp_server_installed(server_name: str) -> bool: """Check if an MCP server is already installed.""" try: result = _run_command( ["claude", "mcp", "list"], capture_output=True, text=True, timeout=60 ) if result is None or result.returncode != 0: return False # Handle case where stdout might be None output = result.stdout if output is None: return False # Parse output to check if server is installed return server_name.lower() in output.lower() except (subprocess.TimeoutExpired, subprocess.SubprocessError): return False def prompt_for_api_key( server_name: str, env_var: str, description: str ) -> Optional[str]: """Prompt user for API key if needed.""" click.echo(f"\n🔑 MCP server '{server_name}' requires an API key") click.echo(f" Environment variable: {env_var}") click.echo(f" Description: {description}") # Check if already set in environment if os.getenv(env_var): click.echo(f" ✅ {env_var} already set in environment") return os.getenv(env_var) # Prompt user if click.confirm(f" Would you like to set {env_var} now?", default=True): api_key = click.prompt(f" Enter {env_var}", hide_input=True) return api_key else: click.echo( f" ⚠️ Proceeding without {env_var} - server may not function properly" ) return None def install_mcp_server( server_info: Dict, scope: str = "user", dry_run: bool = False ) -> bool: """ Install a single MCP server using modern Claude Code API. Args: server_info: Server configuration dictionary scope: Installation scope (local, project, user) dry_run: If True, only show what would be done Returns: True if successful, False otherwise """ server_name = server_info["name"] transport = server_info["transport"] command = server_info["command"] click.echo(f"📦 Installing MCP server: {server_name}") # Check if already installed if check_mcp_server_installed(server_name): click.echo(f" ✅ Already installed: {server_name}") return True # Handle API key requirements env_args = [] if "api_key_env" in server_info: api_key_env = server_info["api_key_env"] api_key = prompt_for_api_key( server_name, api_key_env, server_info.get("api_key_description", f"API key for {server_name}"), ) if api_key: env_args = ["--env", f"{api_key_env}={api_key}"] # Build installation command using modern Claude Code API # Format: claude mcp add --transport <transport> [--scope <scope>] [--env KEY=VALUE] <name> -- <command> cmd = ["claude", "mcp", "add", "--transport", transport] # Add scope if not default if scope != "local": cmd.extend(["--scope", scope]) # Add environment variables if any if env_args: cmd.extend(env_args) # Add server name cmd.append(server_name) # Add separator cmd.append("--") # Add server command (split into parts) cmd.extend(shlex.split(command)) if dry_run: click.echo(f" [DRY RUN] Would run: {' '.join(cmd)}") return True try: click.echo( f" Running: claude mcp add --transport {transport} {server_name} -- {command}" ) result = _run_command(cmd, capture_output=True, text=True, timeout=120) if result.returncode == 0: click.echo(f" ✅ Successfully installed: {server_name}") return True else: error_msg = result.stderr.strip() if result.stderr else "Unknown error" click.echo(f" ❌ Failed to install {server_name}: {error_msg}", err=True) return False except subprocess.TimeoutExpired: click.echo(f" ❌ Timeout installing {server_name}", err=True) return False except Exception as e: click.echo(f" ❌ Error installing {server_name}: {e}", err=True) return False def list_available_servers(): """List all available MCP servers.""" click.echo("📋 Available MCP Servers:\n") # Show gateway option first click.echo(" ┌─────────────────────────────────────────────────────────────┐") click.echo(" │ 🚀 AIRIS MCP Gateway (Recommended) │") gateway_installed = check_mcp_server_installed("airis-mcp-gateway") gateway_status = "✅ installed" if gateway_installed else "⬜ not installed" click.echo(f" │ Status: {gateway_status:40} │") click.echo(" │ 60+ tools, 98% token reduction, Web UI │") click.echo(" │ Install: superclaude mcp --servers airis-mcp-gateway │") click.echo(" └─────────────────────────────────────────────────────────────┘") click.echo() click.echo(" Individual Servers (legacy):\n") for server_key, server_info in MCP_SERVERS.items(): name = server_info["name"] description = server_info["description"] api_key_note = "" if "api_key_env" in server_info: api_key_note = f" (requires {server_info['api_key_env']})" # Check if installed is_installed = check_mcp_server_installed(name) status = "✅ installed" if is_installed else "⬜ not installed" click.echo(f" {name:25} {status}") click.echo(f" {description}{api_key_note}") click.echo() click.echo( f"Total: {len(MCP_SERVERS)} individual servers + AIRIS Gateway available" ) def install_mcp_servers( selected_servers: Optional[List[str]] = None, scope: str = "user", dry_run: bool = False, use_gateway: Optional[bool] = None, ) -> Tuple[bool, str]: """ Install MCP servers for Claude Code. Args: selected_servers: List of server names to install, or None for interactive selection scope: Installation scope (local, project, user) dry_run: If True, only show what would be done use_gateway: If True, install AIRIS MCP Gateway. If None, prompt user. Returns: Tuple of (success, message) """ # Check prerequisites success, errors = check_prerequisites() if not success: error_msg = "Prerequisites not met:\n" + "\n".join(f" ❌ {e}" for e in errors) return False, error_msg # Handle explicit gateway selection if selected_servers and "airis-mcp-gateway" in selected_servers: if install_airis_gateway(dry_run): return True, "AIRIS MCP Gateway installed successfully!" return False, "Failed to install AIRIS MCP Gateway" # Determine which servers to install if selected_servers: # Use explicitly selected servers servers_to_install = [] for server_name in selected_servers: if server_name in MCP_SERVERS: servers_to_install.append(server_name) else: click.echo(f"⚠️ Unknown server: {server_name}", err=True) if not servers_to_install: return False, "No valid servers selected" else: # Interactive selection - offer gateway first click.echo("\n🔌 SuperClaude MCP Server Installation\n") click.echo("Choose your installation method:\n") click.echo(" ┌─────────────────────────────────────────────────────────────┐") click.echo(" │ 🚀 AIRIS MCP Gateway (Recommended) │") click.echo(" │ • 60+ tools through single endpoint │") click.echo(" │ • 98% token reduction with HOT/COLD management │") click.echo(" │ • Web UI for server management │") click.echo(" │ • Requires: Docker │") click.echo(" └─────────────────────────────────────────────────────────────┘") click.echo() click.echo(" Or install individual servers (legacy method):\n") server_options = [] for key, info in MCP_SERVERS.items(): api_note = ( f" (requires {info['api_key_env']})" if "api_key_env" in info else "" ) server_options.append( f"{info['name']:25} - {info['description']}{api_note}" ) for i, option in enumerate(server_options, 1): click.echo(f" {i}. {option}") click.echo() click.echo(" ─────────────────────────────────────────────────────────────") click.echo(" g. Install AIRIS MCP Gateway (recommended)") click.echo(" 0. Install all individual servers") click.echo() selection = click.prompt( "Select option (g for gateway, 0 for all, or comma-separated numbers)", default="g", ) if selection.strip().lower() == "g": # Install gateway if install_airis_gateway(dry_run): return True, "AIRIS MCP Gateway installed successfully!" return False, "Failed to install AIRIS MCP Gateway" elif selection.strip() == "0": servers_to_install = list(MCP_SERVERS.keys()) else: try: indices = [int(x.strip()) for x in selection.split(",")] server_list = list(MCP_SERVERS.keys()) servers_to_install = [ server_list[i - 1] for i in indices if 0 < i <= len(server_list) ] except (ValueError, IndexError): return False, "Invalid selection" if not servers_to_install: return False, "No servers selected" # Install each server click.echo(f"\n🔌 Installing {len(servers_to_install)} MCP server(s)...\n") installed_count = 0 failed_servers = [] for server_name in servers_to_install: server_info = MCP_SERVERS[server_name] if install_mcp_server(server_info, scope, dry_run): installed_count += 1 else: failed_servers.append(server_name) # Generate result message if failed_servers: message = f"\n⚠️ Partially completed: {installed_count}/{len(servers_to_install)} servers installed\n" message += f"Failed servers: {', '.join(failed_servers)}" return False, message else: message = f"\n✅ Successfully installed {installed_count} MCP server(s)!\n" message += "\nℹ️ Use 'claude mcp list' to see all installed servers" message += "\nℹ️ Use '/mcp' in Claude Code to check server status" return True, message
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/cli/install_mcp.py", "license": "MIT License", "lines": 631, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/scripts/clean_command_names.py
#!/usr/bin/env python3 """ SuperClaude Plugin - Command Name Attribute Cleanup Script This script automatically removes redundant 'name:' attributes from command frontmatter in markdown files. The plugin naming system derives command names from the plugin name + filename, making explicit name attributes unnecessary. Usage: python scripts/clean_command_names.py Exit Codes: 0 - Success (files modified or no changes needed) 1 - Error (directory not found or processing failed) """ import re import sys from pathlib import Path from typing import Tuple def find_project_root() -> Path: """ Find the project root directory by locating plugin.json. Returns: Path: Project root directory Raises: FileNotFoundError: If project root cannot be determined """ script_dir = Path(__file__).parent.absolute() current_dir = script_dir.parent # Look for plugin.json up to 3 levels up for _ in range(3): if (current_dir / "plugin.json").exists(): return current_dir current_dir = current_dir.parent raise FileNotFoundError("Could not find project root (plugin.json not found)") def clean_name_attributes(content: str) -> Tuple[str, bool]: """ Remove 'name:' attributes from YAML frontmatter. Args: content: File content as string Returns: Tuple of (cleaned content, was_modified) """ # Pattern to match 'name: value' in frontmatter # Matches: name: value, name : value, NAME: value (case-insensitive) name_pattern = re.compile(r"^\s*name\s*:\s*.*$", re.MULTILINE | re.IGNORECASE) # Check if modification is needed if not name_pattern.search(content): return content, False # Remove name attributes cleaned = name_pattern.sub("", content) # Clean up multiple consecutive newlines (max 2) cleaned = re.sub(r"\n{3,}", "\n\n", cleaned) # Remove trailing whitespace while preserving final newline cleaned = cleaned.rstrip() + "\n" if cleaned.strip() else "" return cleaned, True def process_commands_directory(commands_dir: Path) -> int: """ Process all command markdown files in directory. Args: commands_dir: Path to commands directory Returns: Number of files modified """ if not commands_dir.is_dir(): print(f"Error: Directory not found: {commands_dir}", file=sys.stderr) return -1 modified_count = 0 processed_count = 0 error_count = 0 print(f"🔍 Scanning: {commands_dir}") print(f"{'=' * 60}") # Process all .md files for md_file in sorted(commands_dir.glob("*.md")): processed_count += 1 try: # Read file content content = md_file.read_text(encoding="utf-8") # Clean name attributes cleaned_content, was_modified = clean_name_attributes(content) if was_modified: # Write cleaned content back md_file.write_text(cleaned_content, encoding="utf-8") modified_count += 1 print(f"✅ Modified: {md_file.name}") else: print(f"⏭️ Skipped: {md_file.name} (no name attribute)") except Exception as e: error_count += 1 print(f"❌ Error: {md_file.name} - {e}", file=sys.stderr) print("=" * 60) print("📊 Summary:") print(f" • Processed: {processed_count} files") print(f" • Modified: {modified_count} files") print(f" • Errors: {error_count} files") return modified_count if error_count == 0 else -1 def main() -> int: """ Main execution function. Returns: Exit code (0 for success, 1 for error) """ print("🚀 SuperClaude Plugin - Command Name Cleanup") print() try: # Find project root and commands directory project_root = find_project_root() commands_dir = project_root / "commands" print(f"📁 Project root: {project_root}") print() # Process commands directory result = process_commands_directory(commands_dir) if result < 0: print("\n❌ Cleanup failed with errors", file=sys.stderr) return 1 print("\n✅ Cleanup completed successfully") return 0 except FileNotFoundError as e: print(f"❌ Error: {e}", file=sys.stderr) return 1 except Exception as e: print(f"❌ Unexpected error: {e}", file=sys.stderr) import traceback traceback.print_exc() return 1 if __name__ == "__main__": sys.exit(main())
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/scripts/clean_command_names.py", "license": "MIT License", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/cli/install_commands.py
""" Command Installation Installs SuperClaude slash commands to ~/.claude/commands/sc/ directory. """ import shutil from pathlib import Path from typing import List, Tuple def install_commands(target_path: Path = None, force: bool = False) -> Tuple[bool, str]: """ Install all SuperClaude commands to Claude Code Args: target_path: Target installation directory (default: ~/.claude/commands/sc) force: Force reinstall if commands exist Returns: Tuple of (success: bool, message: str) """ # Default to ~/.claude/commands/sc to maintain /sc: namespace if target_path is None: target_path = Path.home() / ".claude" / "commands" / "sc" # Get command source directory command_source = _get_commands_source() if not command_source or not command_source.exists(): return False, f"Command source directory not found: {command_source}" # Create target directory target_path.mkdir(parents=True, exist_ok=True) # Get all command files command_files = list(command_source.glob("*.md")) if not command_files: return False, f"No command files found in {command_source}" installed_commands = [] skipped_commands = [] failed_commands = [] for command_file in command_files: target_file = target_path / command_file.name command_name = command_file.stem # Check if already exists if target_file.exists() and not force: skipped_commands.append(command_name) continue # Copy command file try: shutil.copy2(command_file, target_file) installed_commands.append(command_name) except Exception as e: failed_commands.append(f"{command_name}: {e}") # Build result message messages = [] if installed_commands: messages.append(f"✅ Installed {len(installed_commands)} commands:") for cmd in installed_commands: messages.append(f" - /{cmd}") if skipped_commands: messages.append( f"\n⚠️ Skipped {len(skipped_commands)} existing commands (use --force to reinstall):" ) for cmd in skipped_commands: messages.append(f" - /{cmd}") if failed_commands: messages.append(f"\n❌ Failed to install {len(failed_commands)} commands:") for fail in failed_commands: messages.append(f" - {fail}") if not installed_commands and not skipped_commands: return False, "No commands were installed" messages.append(f"\n📁 Installation directory: {target_path}") messages.append("\n💡 Tip: Restart Claude Code to use the new commands") success = len(failed_commands) == 0 return success, "\n".join(messages) def _get_commands_source() -> Path: """ Get source directory for commands Commands are stored in: 1. package_root/commands/ (installed package) 2. plugins/superclaude/commands/ (source checkout) Returns: Path to commands source directory """ # Get package root (superclaude/ when installed, src/superclaude/ in dev) package_root = Path(__file__).resolve().parent.parent # Priority 1: Try commands/ in package (for installed package via pipx/pip) # This will be site-packages/superclaude/commands/ package_commands_dir = package_root / "commands" if package_commands_dir.exists(): return package_commands_dir # Priority 2: Try plugins/superclaude/commands/ in project root (for source checkout) # package_root = src/superclaude/ # repo_root = src/superclaude/../../ = project root repo_root = package_root.parent.parent plugins_commands_dir = repo_root / "plugins" / "superclaude" / "commands" if plugins_commands_dir.exists(): return plugins_commands_dir # If neither exists, return package location (will fail with clear error) return package_commands_dir def list_available_commands() -> List[str]: """ List all available commands Returns: List of command names """ command_source = _get_commands_source() if not command_source.exists(): return [] commands = [] for file in command_source.glob("*.md"): if file.stem != "README": commands.append(file.stem) return sorted(commands) def list_installed_commands() -> List[str]: """ List installed commands in ~/.claude/commands/sc/ Returns: List of installed command names """ commands_dir = Path.home() / ".claude" / "commands" / "sc" if not commands_dir.exists(): return [] installed = [] for file in commands_dir.glob("*.md"): if file.stem != "README": installed.append(file.stem) return sorted(installed)
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/cli/install_commands.py", "license": "MIT License", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:tests/integration/test_pytest_plugin.py
""" Integration tests for SuperClaude pytest plugin Tests that the pytest plugin loads correctly and provides expected fixtures. """ import pytest class TestPytestPluginIntegration: """Test suite for pytest plugin integration""" def test_confidence_checker_fixture_available(self, confidence_checker): """Test that confidence_checker fixture is available""" assert confidence_checker is not None assert hasattr(confidence_checker, "assess") assert hasattr(confidence_checker, "get_recommendation") def test_self_check_protocol_fixture_available(self, self_check_protocol): """Test that self_check_protocol fixture is available""" assert self_check_protocol is not None assert hasattr(self_check_protocol, "validate") assert hasattr(self_check_protocol, "format_report") def test_reflexion_pattern_fixture_available(self, reflexion_pattern): """Test that reflexion_pattern fixture is available""" assert reflexion_pattern is not None assert hasattr(reflexion_pattern, "record_error") assert hasattr(reflexion_pattern, "get_solution") def test_token_budget_fixture_available(self, token_budget): """Test that token_budget fixture is available""" assert token_budget is not None assert hasattr(token_budget, "limit") assert hasattr(token_budget, "complexity") def test_pm_context_fixture_available(self, pm_context): """Test that pm_context fixture is available""" assert pm_context is not None assert "memory_dir" in pm_context assert "pm_context" in pm_context assert "last_session" in pm_context assert "next_actions" in pm_context def test_all_fixtures_work_together( self, confidence_checker, self_check_protocol, reflexion_pattern, token_budget ): """ Test that all PM Agent fixtures can be used together This simulates a complete PM Agent workflow """ # 1. Confidence check context = { "test_name": "test_complete_workflow", "duplicate_check_complete": True, "architecture_check_complete": True, "official_docs_verified": True, "oss_reference_complete": True, "root_cause_identified": True, } confidence = confidence_checker.assess(context) assert confidence >= 0.9, "Should have high confidence for complete checks" # 2. Implementation (simulated) implementation = { "tests_passed": True, "test_output": "✅ All tests passed", "requirements": ["Feature X"], "requirements_met": ["Feature X"], "assumptions": ["API is REST"], "assumptions_verified": ["API is REST"], "evidence": { "test_results": "Passed", "code_changes": ["file.py"], "validation": "Linting passed", }, "status": "complete", } # 3. Self-check validation passed, issues = self_check_protocol.validate(implementation) assert passed is True, f"Validation should pass: {issues}" # 4. Token budget check assert token_budget.limit > 0, "Should have token budget allocated" # 5. If there were errors, reflexion would record them # (no errors in this happy path test) def test_pytest_markers_registered(self): """Test that custom markers are registered""" # Note: This test might need adjustment based on pytest version # The important thing is that our custom markers exist # confidence_check, self_check, reflexion, complexity # These are registered in pytest_plugin.py pass class TestPytestPluginHooks: """Test pytest hooks functionality""" def test_plugin_loaded(self): """Test that SuperClaude plugin is loaded""" # This test just needs to run - if the plugin isn't loaded, # the fixtures won't be available and other tests will fail assert True def test_auto_markers_applied(self, request): """Test that auto-markers are applied based on test location""" # This test is in integration/ so should get integration marker markers = [marker.name for marker in request.node.iter_markers()] # Check if integration marker was auto-applied # (depends on test file location) test_path = str(request.node.fspath) if "/integration/" in test_path: assert "integration" in markers or True # Auto-marker should be applied @pytest.mark.integration def test_integration_marker_works(): """ Test that integration marker can be explicitly applied This test explicitly uses the integration marker """ assert True def test_pm_context_memory_structure(pm_context): """Test that PM context memory structure is correct""" memory_dir = pm_context["memory_dir"] assert memory_dir.exists() assert pm_context["pm_context"].exists() assert pm_context["last_session"].exists() assert pm_context["next_actions"].exists() # Files should be readable content = pm_context["pm_context"].read_text() assert isinstance(content, str)
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "tests/integration/test_pytest_plugin.py", "license": "MIT License", "lines": 114, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
SuperClaude-Org/SuperClaude_Framework:tests/unit/test_cli_install.py
""" Unit tests for CLI install command Tests the command installation functionality. """ from superclaude.cli.install_commands import ( install_commands, list_available_commands, list_installed_commands, ) class TestInstallCommands: """Test suite for install commands functionality""" def test_list_available_commands(self): """Test listing available commands""" commands = list_available_commands() assert isinstance(commands, list) assert len(commands) > 0 assert "research" in commands assert "index-repo" in commands def test_install_commands_to_temp_dir(self, tmp_path): """Test installing commands to a temporary directory""" target_dir = tmp_path / "commands" success, message = install_commands(target_path=target_dir, force=False) assert success is True assert "Installed" in message assert target_dir.exists() # Check that command files were copied command_files = list(target_dir.glob("*.md")) assert len(command_files) > 0 # Verify specific commands assert (target_dir / "research.md").exists() assert (target_dir / "index-repo.md").exists() def test_install_commands_skip_existing(self, tmp_path): """Test that existing commands are skipped without --force""" target_dir = tmp_path / "commands" # First install success1, message1 = install_commands(target_path=target_dir, force=False) assert success1 is True # Second install without force success2, message2 = install_commands(target_path=target_dir, force=False) assert success2 is True assert "Skipped" in message2 def test_install_commands_force_reinstall(self, tmp_path): """Test force reinstall of existing commands""" target_dir = tmp_path / "commands" # First install success1, message1 = install_commands(target_path=target_dir, force=False) assert success1 is True # Modify a file research_file = target_dir / "research.md" research_file.write_text("modified") assert research_file.read_text() == "modified" # Force reinstall success2, message2 = install_commands(target_path=target_dir, force=True) assert success2 is True assert "Installed" in message2 # Verify file was overwritten content = research_file.read_text() assert content != "modified" assert "research" in content.lower() def test_list_installed_commands(self, tmp_path): """Test listing installed commands""" target_dir = tmp_path / "commands" # Before install # Note: list_installed_commands checks ~/.claude/commands by default # We can't easily test this without mocking, so just verify it returns a list installed = list_installed_commands() assert isinstance(installed, list) # After install to temp dir install_commands(target_path=target_dir, force=False) # Verify files exist command_files = list(target_dir.glob("*.md")) assert len(command_files) > 0 def test_install_commands_creates_target_directory(self, tmp_path): """Test that target directory is created if it doesn't exist""" target_dir = tmp_path / "nested" / "commands" assert not target_dir.exists() success, message = install_commands(target_path=target_dir, force=False) assert success is True assert target_dir.exists() def test_available_commands_format(self): """Test that available commands have expected format""" commands = list_available_commands() # Should be list of strings assert all(isinstance(cmd, str) for cmd in commands) # Should not include file extensions assert all(not cmd.endswith(".md") for cmd in commands) # Should be sorted assert commands == sorted(commands) def test_research_command_exists(self, tmp_path): """Test that research command specifically gets installed""" target_dir = tmp_path / "commands" install_commands(target_path=target_dir, force=False) research_file = target_dir / "research.md" assert research_file.exists() content = research_file.read_text() assert "research" in content.lower() assert len(content) > 100 # Should have substantial content def test_all_expected_commands_available(self): """Test that all expected commands are available""" commands = list_available_commands() expected = ["agent", "index-repo", "recommend", "research"] for expected_cmd in expected: assert expected_cmd in commands, ( f"Expected command '{expected_cmd}' not found" ) class TestInstallCommandsEdgeCases: """Test edge cases and error handling""" def test_install_to_nonexistent_parent(self, tmp_path): """Test installation to path with nonexistent parent directories""" target_dir = tmp_path / "a" / "b" / "c" / "commands" success, message = install_commands(target_path=target_dir, force=False) assert success is True assert target_dir.exists() def test_empty_target_directory_ok(self, tmp_path): """Test that installation works with empty target directory""" target_dir = tmp_path / "commands" target_dir.mkdir() success, message = install_commands(target_path=target_dir, force=False) assert success is True def test_cli_integration(): """ Integration test: verify CLI can import and use install functions This tests that the CLI main.py can successfully import the functions """ from superclaude.cli.install_commands import ( list_available_commands, ) # Should not raise ImportError commands = list_available_commands() assert len(commands) > 0
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "tests/unit/test_cli_install.py", "license": "MIT License", "lines": 130, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
SuperClaude-Org/SuperClaude_Framework:tests/unit/test_reflexion.py
""" Unit tests for ReflexionPattern Tests error learning and prevention functionality. """ import pytest from superclaude.pm_agent.reflexion import ReflexionPattern class TestReflexionPattern: """Test suite for ReflexionPattern class""" def test_initialization(self): """Test ReflexionPattern initialization""" reflexion = ReflexionPattern() assert reflexion is not None assert hasattr(reflexion, "record_error") assert hasattr(reflexion, "get_solution") def test_record_error_basic(self): """Test recording a basic error""" reflexion = ReflexionPattern() error_info = { "test_name": "test_feature", "error_type": "AssertionError", "error_message": "Expected 5, got 3", "traceback": "File test.py, line 10...", } # Should not raise an exception reflexion.record_error(error_info) def test_record_error_with_solution(self): """Test recording an error with a solution""" reflexion = ReflexionPattern() error_info = { "test_name": "test_database_connection", "error_type": "ConnectionError", "error_message": "Could not connect to database", "solution": "Ensure database is running and credentials are correct", } reflexion.record_error(error_info) def test_get_solution_for_known_error(self): """Test retrieving solution for a known error pattern""" reflexion = ReflexionPattern() # Record an error with solution error_info = { "error_type": "ImportError", "error_message": "No module named 'pytest'", "solution": "Install pytest: pip install pytest", } reflexion.record_error(error_info) # Try to get solution for similar error error_signature = "ImportError: No module named 'pytest'" solution = reflexion.get_solution(error_signature) # Note: Actual implementation might return None if not implemented yet # This test documents expected behavior assert solution is None or isinstance(solution, str) def test_error_pattern_matching(self): """Test error pattern matching functionality""" reflexion = ReflexionPattern() # Record multiple similar errors errors = [ { "error_type": "TypeError", "error_message": "expected str, got int", "solution": "Convert int to str using str()", }, { "error_type": "TypeError", "error_message": "expected int, got str", "solution": "Convert str to int using int()", }, ] for error in errors: reflexion.record_error(error) # Test pattern matching (implementation-dependent) error_signature = "TypeError" solution = reflexion.get_solution(error_signature) assert solution is None or isinstance(solution, str) def test_reflexion_memory_persistence(self, temp_memory_dir): """Test that reflexion can work with memory directory""" reflexion = ReflexionPattern(memory_dir=temp_memory_dir) error_info = { "test_name": "test_feature", "error_type": "ValueError", "error_message": "Invalid input", } # Should not raise exception even with custom memory dir reflexion.record_error(error_info) def test_error_learning_across_sessions(self): """ Test that errors can be learned across sessions Note: This tests the interface, actual persistence depends on implementation """ reflexion = ReflexionPattern() # Session 1: Record error error_info = { "error_type": "FileNotFoundError", "error_message": "config.json not found", "solution": "Create config.json in project root", "session": "session_1", } reflexion.record_error(error_info) # Session 2: Retrieve solution error_signature = "FileNotFoundError: config.json" solution = reflexion.get_solution(error_signature) # Implementation may or may not persist across instances assert solution is None or isinstance(solution, str) @pytest.mark.reflexion def test_reflexion_marker_integration(reflexion_pattern): """ Test that reflexion marker works with pytest plugin fixture If this test fails, reflexion should record the failure """ # Test that fixture is properly provided assert reflexion_pattern is not None # Record a test error error_info = { "test_name": "test_reflexion_marker_integration", "error_type": "IntegrationTestError", "error_message": "Testing reflexion integration", } # Should not raise exception reflexion_pattern.record_error(error_info) def test_reflexion_with_real_exception(): """ Test reflexion pattern with a real exception scenario This simulates how reflexion would be used in practice """ reflexion = ReflexionPattern() try: # Simulate an operation that fails _ = 10 / 0 # noqa: F841 except ZeroDivisionError as e: # Record the error error_info = { "test_name": "test_reflexion_with_real_exception", "error_type": type(e).__name__, "error_message": str(e), "traceback": "simulated traceback", "solution": "Check denominator is not zero before division", } reflexion.record_error(error_info) # Test should complete successfully assert True
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "tests/unit/test_reflexion.py", "license": "MIT License", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
SuperClaude-Org/SuperClaude_Framework:tests/unit/test_self_check.py
""" Unit tests for SelfCheckProtocol Tests post-implementation validation functionality. """ import pytest from superclaude.pm_agent.self_check import SelfCheckProtocol class TestSelfCheckProtocol: """Test suite for SelfCheckProtocol class""" def test_validate_passing_implementation(self, sample_implementation): """ Test validation of a complete, passing implementation Should pass all four questions: 1. Tests passing? ✅ 2. Requirements met? ✅ 3. Assumptions verified? ✅ 4. Evidence provided? ✅ """ protocol = SelfCheckProtocol() passed, issues = protocol.validate(sample_implementation) assert passed is True, f"Expected validation to pass, got issues: {issues}" assert len(issues) == 0, f"Expected no issues, got {len(issues)}: {issues}" def test_validate_failing_implementation(self, failing_implementation): """ Test validation of a failing implementation Should fail multiple checks """ protocol = SelfCheckProtocol() passed, issues = protocol.validate(failing_implementation) assert passed is False, "Expected validation to fail" assert len(issues) > 0, "Expected issues to be detected" # Check specific issues issue_text = " ".join(issues) assert "Tests not passing" in issue_text or "test" in issue_text.lower() def test_check_tests_passing_with_output(self): """Test that tests_passed requires actual output""" protocol = SelfCheckProtocol() # Tests passed WITH output - should pass impl_with_output = { "tests_passed": True, "test_output": "✅ 10 tests passed", } assert protocol._check_tests_passing(impl_with_output) is True # Tests passed WITHOUT output - should fail (hallucination detection) impl_without_output = { "tests_passed": True, "test_output": "", } assert protocol._check_tests_passing(impl_without_output) is False def test_check_requirements_met(self): """Test requirements validation""" protocol = SelfCheckProtocol() # All requirements met impl_complete = { "requirements": ["A", "B", "C"], "requirements_met": ["A", "B", "C"], } unmet = protocol._check_requirements_met(impl_complete) assert len(unmet) == 0 # Some requirements not met impl_incomplete = { "requirements": ["A", "B", "C"], "requirements_met": ["A", "B"], } unmet = protocol._check_requirements_met(impl_incomplete) assert len(unmet) == 1 assert "C" in unmet def test_check_assumptions_verified(self): """Test assumptions verification""" protocol = SelfCheckProtocol() # All assumptions verified impl_verified = { "assumptions": ["API is REST", "DB is PostgreSQL"], "assumptions_verified": ["API is REST", "DB is PostgreSQL"], } unverified = protocol._check_assumptions_verified(impl_verified) assert len(unverified) == 0 # Some assumptions unverified impl_unverified = { "assumptions": ["API is REST", "DB is PostgreSQL"], "assumptions_verified": ["API is REST"], } unverified = protocol._check_assumptions_verified(impl_unverified) assert len(unverified) == 1 assert "DB is PostgreSQL" in unverified def test_check_evidence_exists(self): """Test evidence requirement validation""" protocol = SelfCheckProtocol() # All evidence present impl_with_evidence = { "evidence": { "test_results": "Tests passed", "code_changes": ["file1.py"], "validation": "Linting passed", } } missing = protocol._check_evidence_exists(impl_with_evidence) assert len(missing) == 0 # Missing all evidence impl_no_evidence = {"evidence": {}} missing = protocol._check_evidence_exists(impl_no_evidence) assert len(missing) == 3 assert "test_results" in missing assert "code_changes" in missing assert "validation" in missing def test_detect_hallucinations_tests_without_output(self): """Test hallucination detection: claims tests pass without output""" protocol = SelfCheckProtocol() impl = { "tests_passed": True, "test_output": "", # No output - hallucination! } detected = protocol._detect_hallucinations(impl) assert len(detected) > 0 assert any("without showing output" in d for d in detected) def test_detect_hallucinations_complete_without_evidence(self): """Test hallucination detection: claims complete without evidence""" protocol = SelfCheckProtocol() impl = { "status": "complete", "evidence": None, # No evidence - hallucination! } detected = protocol._detect_hallucinations(impl) assert len(detected) > 0 assert any("without evidence" in d for d in detected) def test_detect_hallucinations_complete_with_failing_tests(self): """Test hallucination detection: claims complete despite failing tests""" protocol = SelfCheckProtocol() impl = { "status": "complete", "tests_passed": False, # Tests failed but claims complete! } detected = protocol._detect_hallucinations(impl) assert len(detected) > 0 assert any("failing tests" in d for d in detected) def test_detect_hallucinations_ignored_errors(self): """Test hallucination detection: ignored errors/warnings""" protocol = SelfCheckProtocol() impl = { "status": "complete", "errors": ["TypeError in module X"], "warnings": ["Deprecated function used"], } detected = protocol._detect_hallucinations(impl) assert len(detected) > 0 assert any("errors/warnings" in d for d in detected) def test_detect_hallucinations_uncertainty_language(self): """Test hallucination detection: uncertainty language""" protocol = SelfCheckProtocol() impl = { "description": "This probably works and might be correct", } detected = protocol._detect_hallucinations(impl) assert len(detected) > 0 assert any("Uncertainty language" in d for d in detected) def test_format_report_passing(self): """Test report formatting for passing validation""" protocol = SelfCheckProtocol() report = protocol.format_report(passed=True, issues=[]) assert "PASSED" in report assert "✅" in report def test_format_report_failing(self): """Test report formatting for failing validation""" protocol = SelfCheckProtocol() issues = [ "❌ Tests not passing", "❌ Missing evidence: test_results", ] report = protocol.format_report(passed=False, issues=issues) assert "FAILED" in report assert "❌" in report for issue in issues: assert issue in report @pytest.mark.self_check def test_self_check_marker_integration(self_check_protocol, sample_implementation): """ Test that self_check marker works with pytest plugin fixture This test validates the fixture provided by pytest plugin """ passed, issues = self_check_protocol.validate(sample_implementation) assert passed is True, f"Sample implementation should pass validation: {issues}" assert len(issues) == 0, "No issues should be detected in sample implementation"
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "tests/unit/test_self_check.py", "license": "MIT License", "lines": 181, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
SuperClaude-Org/SuperClaude_Framework:tests/unit/test_token_budget.py
""" Unit tests for TokenBudgetManager Tests token budget allocation and management functionality. """ import pytest from superclaude.pm_agent.token_budget import TokenBudgetManager class TestTokenBudgetManager: """Test suite for TokenBudgetManager class""" def test_simple_complexity(self): """Test token budget for simple tasks (typo fixes)""" manager = TokenBudgetManager(complexity="simple") assert manager.limit == 200 assert manager.complexity == "simple" def test_medium_complexity(self): """Test token budget for medium tasks (bug fixes)""" manager = TokenBudgetManager(complexity="medium") assert manager.limit == 1000 assert manager.complexity == "medium" def test_complex_complexity(self): """Test token budget for complex tasks (features)""" manager = TokenBudgetManager(complexity="complex") assert manager.limit == 2500 assert manager.complexity == "complex" def test_default_complexity(self): """Test default complexity is medium""" manager = TokenBudgetManager() assert manager.limit == 1000 assert manager.complexity == "medium" def test_invalid_complexity_defaults_to_medium(self): """Test that invalid complexity defaults to medium""" manager = TokenBudgetManager(complexity="invalid") assert manager.limit == 1000 assert manager.complexity == "medium" def test_token_usage_tracking(self): """Test token usage tracking if implemented""" manager = TokenBudgetManager(complexity="simple") # Check if usage tracking is available if hasattr(manager, "used"): assert manager.used == 0 if hasattr(manager, "remaining"): assert manager.remaining == manager.limit def test_budget_allocation_strategy(self): """Test token budget allocation strategy""" # Simple tasks should have smallest budget simple = TokenBudgetManager(complexity="simple") # Medium tasks should have moderate budget medium = TokenBudgetManager(complexity="medium") # Complex tasks should have largest budget complex_task = TokenBudgetManager(complexity="complex") assert simple.limit < medium.limit < complex_task.limit def test_complexity_examples(self): """Test that complexity levels match documented examples""" # Simple: typo fix (200 tokens) simple = TokenBudgetManager(complexity="simple") assert simple.limit == 200 # Medium: bug fix, small feature (1,000 tokens) medium = TokenBudgetManager(complexity="medium") assert medium.limit == 1000 # Complex: feature implementation (2,500 tokens) complex_task = TokenBudgetManager(complexity="complex") assert complex_task.limit == 2500 @pytest.mark.complexity("simple") def test_complexity_marker_simple(token_budget): """ Test that complexity marker works with pytest plugin fixture This test should have a simple (200 token) budget """ assert token_budget.limit == 200 assert token_budget.complexity == "simple" @pytest.mark.complexity("medium") def test_complexity_marker_medium(token_budget): """ Test that complexity marker works with medium budget This test should have a medium (1000 token) budget """ assert token_budget.limit == 1000 assert token_budget.complexity == "medium" @pytest.mark.complexity("complex") def test_complexity_marker_complex(token_budget): """ Test that complexity marker works with complex budget This test should have a complex (2500 token) budget """ assert token_budget.limit == 2500 assert token_budget.complexity == "complex" def test_token_budget_no_marker(token_budget): """ Test that token_budget fixture defaults to medium without marker Tests without complexity marker should get medium budget """ assert token_budget.limit == 1000 assert token_budget.complexity == "medium"
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "tests/unit/test_token_budget.py", "license": "MIT License", "lines": 92, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
SuperClaude-Org/SuperClaude_Framework:plugins/superclaude/scripts/clean_command_names.py
#!/usr/bin/env python3 """ SuperClaude Plugin - Command Name Attribute Cleanup Script This script automatically removes redundant 'name:' attributes from command frontmatter in markdown files. The plugin naming system derives command names from the plugin name + filename, making explicit name attributes unnecessary. Usage: python scripts/clean_command_names.py Exit Codes: 0 - Success (files modified or no changes needed) 1 - Error (directory not found or processing failed) """ import re import sys from pathlib import Path from typing import Tuple def find_project_root() -> Path: """ Find the project root directory by locating plugin.json. Returns: Path: Project root directory Raises: FileNotFoundError: If project root cannot be determined """ script_dir = Path(__file__).parent.absolute() current_dir = script_dir.parent # Look for plugin.json up to 3 levels up for _ in range(3): if (current_dir / "plugin.json").exists(): return current_dir current_dir = current_dir.parent raise FileNotFoundError("Could not find project root (plugin.json not found)") def clean_name_attributes(content: str) -> Tuple[str, bool]: """ Remove 'name:' attributes from YAML frontmatter. Args: content: File content as string Returns: Tuple of (cleaned content, was_modified) """ # Pattern to match 'name: value' in frontmatter # Matches: name: value, name : value, NAME: value (case-insensitive) name_pattern = re.compile(r'^\s*name\s*:\s*.*$', re.MULTILINE | re.IGNORECASE) # Check if modification is needed if not name_pattern.search(content): return content, False # Remove name attributes cleaned = name_pattern.sub('', content) # Clean up multiple consecutive newlines (max 2) cleaned = re.sub(r'\n{3,}', '\n\n', cleaned) # Remove trailing whitespace while preserving final newline cleaned = cleaned.rstrip() + '\n' if cleaned.strip() else '' return cleaned, True def process_commands_directory(commands_dir: Path) -> int: """ Process all command markdown files in directory. Args: commands_dir: Path to commands directory Returns: Number of files modified """ if not commands_dir.is_dir(): print(f"Error: Directory not found: {commands_dir}", file=sys.stderr) return -1 modified_count = 0 processed_count = 0 error_count = 0 print(f"🔍 Scanning: {commands_dir}") print(f"{'='*60}") # Process all .md files for md_file in sorted(commands_dir.glob("*.md")): processed_count += 1 try: # Read file content content = md_file.read_text(encoding='utf-8') # Clean name attributes cleaned_content, was_modified = clean_name_attributes(content) if was_modified: # Write cleaned content back md_file.write_text(cleaned_content, encoding='utf-8') modified_count += 1 print(f"✅ Modified: {md_file.name}") else: print(f"⏭️ Skipped: {md_file.name} (no name attribute)") except Exception as e: error_count += 1 print(f"❌ Error: {md_file.name} - {e}", file=sys.stderr) print("="*60) print("📊 Summary:") print(f" • Processed: {processed_count} files") print(f" • Modified: {modified_count} files") print(f" • Errors: {error_count} files") return modified_count if error_count == 0 else -1 def main() -> int: """ Main execution function. Returns: Exit code (0 for success, 1 for error) """ print("🚀 SuperClaude Plugin - Command Name Cleanup") print() try: # Find project root and commands directory project_root = find_project_root() commands_dir = project_root / "commands" print(f"📁 Project root: {project_root}") print() # Process commands directory result = process_commands_directory(commands_dir) if result < 0: print("\n❌ Cleanup failed with errors", file=sys.stderr) return 1 print("\n✅ Cleanup completed successfully") return 0 except FileNotFoundError as e: print(f"❌ Error: {e}", file=sys.stderr) return 1 except Exception as e: print(f"❌ Unexpected error: {e}", file=sys.stderr) import traceback traceback.print_exc() return 1 if __name__ == "__main__": sys.exit(main())
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "plugins/superclaude/scripts/clean_command_names.py", "license": "MIT License", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:scripts/build_superclaude_plugin.py
#!/usr/bin/env python3 """ Build SuperClaude plugin distribution artefacts from unified sources. Usage: python scripts/build_superclaude_plugin.py """ from __future__ import annotations import json import shutil from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PLUGIN_SRC = ROOT / "plugins" / "superclaude" DIST_ROOT = ROOT / "dist" / "plugins" / "superclaude" MANIFEST_DIR = PLUGIN_SRC / "manifest" def load_metadata() -> dict: with (MANIFEST_DIR / "metadata.json").open() as f: metadata = json.load(f) version_file = ROOT / "VERSION" if version_file.exists(): metadata["plugin_version"] = version_file.read_text().strip() else: # Fall back to metadata override or default version metadata["plugin_version"] = metadata.get("plugin_version", "0.0.0") metadata.setdefault("keywords", []) return metadata def render_template(template_path: Path, placeholders: dict[str, str]) -> str: content = template_path.read_text() for key, value in placeholders.items(): token = f"{{{{{key}}}}}" content = content.replace(token, value) return content def copy_tree(src: Path, dest: Path) -> None: if not src.exists(): return shutil.copytree(src, dest, dirs_exist_ok=True) def main() -> None: if not PLUGIN_SRC.exists(): raise SystemExit(f"Missing plugin sources: {PLUGIN_SRC}") metadata = load_metadata() placeholders = { "plugin_name": metadata["plugin_name"], "plugin_version": metadata["plugin_version"], "plugin_description": metadata["plugin_description"], "author_name": metadata["author_name"], "homepage_url": metadata["homepage_url"], "repository_url": metadata["repository_url"], "license": metadata["license"], "keywords_json": json.dumps(metadata["keywords"]), "marketplace_name": metadata["marketplace_name"], "marketplace_description": metadata["marketplace_description"], } # Clean dist directory if DIST_ROOT.exists(): shutil.rmtree(DIST_ROOT) DIST_ROOT.mkdir(parents=True, exist_ok=True) # Copy top-level asset directories for folder in ["agents", "commands", "hooks", "scripts", "skills"]: copy_tree(PLUGIN_SRC / folder, DIST_ROOT / folder) # Render manifests claude_dir = DIST_ROOT / ".claude-plugin" claude_dir.mkdir(parents=True, exist_ok=True) plugin_manifest = render_template(MANIFEST_DIR / "plugin.template.json", placeholders) (claude_dir / "plugin.json").write_text(plugin_manifest + "\n") marketplace_manifest = render_template(MANIFEST_DIR / "marketplace.template.json", placeholders) (claude_dir / "marketplace.json").write_text(marketplace_manifest + "\n") # Copy tests into manifest directory tests_src = PLUGIN_SRC / "tests" if tests_src.exists(): copy_tree(tests_src, claude_dir / "tests") print(f"✅ Built plugin artefacts at {DIST_ROOT}") if __name__ == "__main__": main()
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "scripts/build_superclaude_plugin.py", "license": "MIT License", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
SuperClaude-Org/SuperClaude_Framework:src/superclaude/cli/doctor.py
""" SuperClaude Doctor Command Health check for SuperClaude installation. """ from pathlib import Path from typing import Any, Dict def run_doctor(verbose: bool = False) -> Dict[str, Any]: """ Run SuperClaude health checks Args: verbose: Include detailed diagnostic information Returns: Dict with check results """ checks = [] # Check 1: pytest plugin loaded plugin_check = _check_pytest_plugin() checks.append(plugin_check) # Check 2: Skills installed skills_check = _check_skills_installed() checks.append(skills_check) # Check 3: Configuration config_check = _check_configuration() checks.append(config_check) return { "checks": checks, "passed": all(check["passed"] for check in checks), } def _check_pytest_plugin() -> Dict[str, Any]: """ Check if pytest plugin is loaded Returns: Check result dict """ try: import pytest # Try to get pytest config try: config = pytest.Config.fromdictargs({}, []) plugins = config.pluginmanager.list_plugin_distinfo() # Check if superclaude plugin is loaded superclaude_loaded = any( "superclaude" in str(plugin[0]).lower() for plugin in plugins ) if superclaude_loaded: return { "name": "pytest plugin loaded", "passed": True, "details": ["SuperClaude pytest plugin is active"], } else: return { "name": "pytest plugin loaded", "passed": False, "details": ["SuperClaude plugin not found in pytest plugins"], } except Exception as e: return { "name": "pytest plugin loaded", "passed": False, "details": [f"Could not check pytest plugins: {e}"], } except ImportError: return { "name": "pytest plugin loaded", "passed": False, "details": ["pytest not installed"], } def _check_skills_installed() -> Dict[str, Any]: """ Check if any skills are installed Returns: Check result dict """ skills_dir = Path("~/.claude/skills").expanduser() if not skills_dir.exists(): return { "name": "Skills installed", "passed": True, # Optional, so pass "details": ["No skills installed (optional)"], } # Find skills (directories with implementation.md) skills = [] for item in skills_dir.iterdir(): if item.is_dir() and (item / "implementation.md").exists(): skills.append(item.name) if skills: return { "name": "Skills installed", "passed": True, "details": [f"{len(skills)} skill(s) installed: {', '.join(skills)}"], } else: return { "name": "Skills installed", "passed": True, # Optional "details": ["No skills installed (optional)"], } def _check_configuration() -> Dict[str, Any]: """ Check SuperClaude configuration Returns: Check result dict """ # Check if package is importable try: import superclaude version = superclaude.__version__ return { "name": "Configuration", "passed": True, "details": [f"SuperClaude {version} installed correctly"], } except ImportError as e: return { "name": "Configuration", "passed": False, "details": [f"Could not import superclaude: {e}"], }
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/cli/doctor.py", "license": "MIT License", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/cli/install_skill.py
""" Skill Installation Command Installs SuperClaude skills to ~/.claude/skills/ directory. """ import shutil from pathlib import Path from typing import List, Optional, Tuple def install_skill_command( skill_name: str, target_path: Path, force: bool = False ) -> Tuple[bool, str]: """ Install a skill to target directory Args: skill_name: Name of skill to install (e.g., 'pm-agent') target_path: Target installation directory force: Force reinstall if skill exists Returns: Tuple of (success: bool, message: str) """ # Get skill source directory skill_source = _get_skill_source(skill_name) if not skill_source: return False, f"Skill '{skill_name}' not found" if not skill_source.exists(): return False, f"Skill source directory not found: {skill_source}" # Create target directory skill_target = target_path / skill_name target_path.mkdir(parents=True, exist_ok=True) # Check if skill already installed if skill_target.exists() and not force: return ( False, f"Skill '{skill_name}' already installed (use --force to reinstall)", ) # Remove existing if force if skill_target.exists() and force: shutil.rmtree(skill_target) # Copy skill files try: shutil.copytree(skill_source, skill_target) return True, f"Skill '{skill_name}' installed successfully to {skill_target}" except Exception as e: return False, f"Failed to install skill: {e}" def _get_skill_source(skill_name: str) -> Optional[Path]: """ Get source directory for skill Skills are stored in: src/superclaude/skills/{skill_name}/ Args: skill_name: Name of skill Returns: Path to skill source directory """ package_root = Path(__file__).resolve().parent.parent skill_dirs: List[Path] = [] def _candidate_paths(base: Path) -> List[Path]: if not base.exists(): return [] normalized = skill_name.replace("-", "_") return [ base / skill_name, base / normalized, ] # Packaged skills (src/superclaude/skills/…) skill_dirs.extend(_candidate_paths(package_root / "skills")) # Repository root skills/ when running from source checkout repo_root = package_root.parent # -> src/ if repo_root.name == "src": project_root = repo_root.parent skill_dirs.extend(_candidate_paths(project_root / "skills")) for candidate in skill_dirs: if _is_valid_skill_dir(candidate): return candidate return None def _is_valid_skill_dir(path: Path) -> bool: """Return True if directory looks like a SuperClaude skill payload.""" if not path or not path.exists() or not path.is_dir(): return False manifest_files = {"SKILL.md", "skill.md", "implementation.md"} if any((path / manifest).exists() for manifest in manifest_files): return True # Otherwise check for any content files (ts/py/etc.) for item in path.iterdir(): if item.is_file() and item.suffix in {".ts", ".js", ".py", ".json"}: return True return False def list_available_skills() -> list[str]: """ List all available skills Returns: List of skill names """ package_root = Path(__file__).resolve().parent.parent candidate_dirs = [ package_root / "skills", ] repo_root = package_root.parent if repo_root.name == "src": candidate_dirs.append(repo_root.parent / "skills") skills: List[str] = [] seen: set[str] = set() for base in candidate_dirs: if not base.exists(): continue for item in base.iterdir(): if not item.is_dir() or item.name.startswith("_"): continue if not _is_valid_skill_dir(item): continue # Prefer kebab-case names as canonical canonical = item.name.replace("_", "-") if canonical not in seen: seen.add(canonical) skills.append(canonical) skills.sort() return skills
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/cli/install_skill.py", "license": "MIT License", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/cli/main.py
""" SuperClaude CLI Main Entry Point Provides command-line interface for SuperClaude operations. """ import sys from pathlib import Path import click # Add parent directory to path to import superclaude sys.path.insert(0, str(Path(__file__).parent.parent.parent)) from superclaude import __version__ @click.group() @click.version_option(version=__version__, prog_name="SuperClaude") def main(): """ SuperClaude - AI-enhanced development framework for Claude Code A pytest plugin providing PM Agent capabilities and optional skills system. """ pass @main.command() @click.option( "--target", default="~/.claude/commands/sc", help="Installation directory (default: ~/.claude/commands/sc)", ) @click.option( "--force", is_flag=True, help="Force reinstall if commands already exist", ) @click.option( "--list", "list_only", is_flag=True, help="List available commands without installing", ) def install(target: str, force: bool, list_only: bool): """ Install SuperClaude commands to Claude Code Installs all slash commands (/sc:research, /sc:index-repo, etc.) to your ~/.claude/commands/sc directory so you can use them in Claude Code. Examples: superclaude install superclaude install --force superclaude install --list superclaude install --target /custom/path """ from .install_commands import ( install_commands, list_available_commands, list_installed_commands, ) # List only mode if list_only: available = list_available_commands() installed = list_installed_commands() click.echo("📋 Available Commands:") for cmd in available: status = "✅ installed" if cmd in installed else "⬜ not installed" click.echo(f" /{cmd:20} {status}") click.echo(f"\nTotal: {len(available)} available, {len(installed)} installed") return # Install commands target_path = Path(target).expanduser() click.echo(f"📦 Installing SuperClaude commands to {target_path}...") click.echo() success, message = install_commands(target_path=target_path, force=force) click.echo(message) if not success: sys.exit(1) @main.command() @click.option("--servers", "-s", multiple=True, help="Specific MCP servers to install") @click.option("--list", "list_only", is_flag=True, help="List available MCP servers") @click.option( "--scope", default="user", type=click.Choice(["local", "project", "user"]), help="Installation scope", ) @click.option( "--dry-run", is_flag=True, help="Show what would be installed without actually installing", ) def mcp(servers, list_only, scope, dry_run): """ Install and manage MCP servers for Claude Code Examples: superclaude mcp --list superclaude mcp --servers tavily --servers context7 superclaude mcp --scope project superclaude mcp --dry-run """ from .install_mcp import install_mcp_servers, list_available_servers if list_only: list_available_servers() return click.echo(f"🔌 Installing MCP servers (scope: {scope})...") click.echo() success, message = install_mcp_servers( selected_servers=list(servers) if servers else None, scope=scope, dry_run=dry_run, ) click.echo(message) if not success: sys.exit(1) @main.command() @click.option( "--target", default="~/.claude/commands/sc", help="Installation directory (default: ~/.claude/commands/sc)", ) def update(target: str): """ Update SuperClaude commands to latest version Re-installs all slash commands to match the current package version. This is a convenience command equivalent to 'install --force'. Example: superclaude update superclaude update --target /custom/path """ from .install_commands import install_commands target_path = Path(target).expanduser() click.echo(f"🔄 Updating SuperClaude commands to version {__version__}...") click.echo() success, message = install_commands(target_path=target_path, force=True) click.echo(message) if not success: sys.exit(1) @main.command() @click.argument("skill_name") @click.option( "--target", default="~/.claude/skills", help="Installation directory (default: ~/.claude/skills)", ) @click.option( "--force", is_flag=True, help="Force reinstall if skill already exists", ) def install_skill(skill_name: str, target: str, force: bool): """ Install a SuperClaude skill to Claude Code SKILL_NAME: Name of the skill to install (e.g., pm-agent) Example: superclaude install-skill pm-agent superclaude install-skill pm-agent --target ~/.claude/skills --force """ from .install_skill import install_skill_command target_path = Path(target).expanduser() click.echo(f"📦 Installing skill '{skill_name}' to {target_path}...") success, message = install_skill_command( skill_name=skill_name, target_path=target_path, force=force ) if success: click.echo(f"✅ {message}") else: click.echo(f"❌ {message}", err=True) sys.exit(1) @main.command() @click.option( "--verbose", is_flag=True, help="Show detailed diagnostic information", ) def doctor(verbose: bool): """ Check SuperClaude installation health Verifies: - pytest plugin loaded correctly - Skills installed (if any) - Configuration files present """ from .doctor import run_doctor click.echo("🔍 SuperClaude Doctor\n") results = run_doctor(verbose=verbose) # Display results for check in results["checks"]: status_symbol = "✅" if check["passed"] else "❌" click.echo(f"{status_symbol} {check['name']}") if verbose and check.get("details"): for detail in check["details"]: click.echo(f" {detail}") # Summary click.echo() total = len(results["checks"]) passed = sum(1 for check in results["checks"] if check["passed"]) if passed == total: click.echo("✅ SuperClaude is healthy") else: click.echo(f"⚠️ {total - passed}/{total} checks failed") sys.exit(1) @main.command() def version(): """Show SuperClaude version""" click.echo(f"SuperClaude version {__version__}") if __name__ == "__main__": main()
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/cli/main.py", "license": "MIT License", "lines": 199, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/execution/parallel.py
""" Parallel Execution Engine - Automatic Parallelization Analyzes task dependencies and executes independent operations concurrently for maximum speed. Key features: - Dependency graph construction - Automatic parallel group detection - Concurrent execution with ThreadPoolExecutor - Result aggregation and error handling """ import time from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import dataclass from enum import Enum from typing import Any, Callable, Dict, List, Optional, Set class TaskStatus(Enum): """Task execution status""" PENDING = "pending" RUNNING = "running" COMPLETED = "completed" FAILED = "failed" @dataclass class Task: """Single executable task""" id: str description: str execute: Callable depends_on: List[str] # Task IDs this depends on status: TaskStatus = TaskStatus.PENDING result: Any = None error: Optional[Exception] = None def can_execute(self, completed_tasks: Set[str]) -> bool: """Check if all dependencies are satisfied""" return all(dep in completed_tasks for dep in self.depends_on) @dataclass class ParallelGroup: """Group of tasks that can execute in parallel""" group_id: int tasks: List[Task] dependencies: Set[str] # External task IDs this group depends on def __repr__(self) -> str: return f"Group {self.group_id}: {len(self.tasks)} tasks" @dataclass class ExecutionPlan: """Complete execution plan with parallelization strategy""" groups: List[ParallelGroup] total_tasks: int sequential_time_estimate: float parallel_time_estimate: float speedup: float def __repr__(self) -> str: return ( f"Execution Plan:\n" f" Total tasks: {self.total_tasks}\n" f" Parallel groups: {len(self.groups)}\n" f" Sequential time: {self.sequential_time_estimate:.1f}s\n" f" Parallel time: {self.parallel_time_estimate:.1f}s\n" f" Speedup: {self.speedup:.1f}x" ) class ParallelExecutor: """ Automatic Parallel Execution Engine Analyzes task dependencies and executes independent operations concurrently for maximum performance. Example: executor = ParallelExecutor(max_workers=10) tasks = [ Task("read1", "Read file1.py", lambda: read_file("file1.py"), []), Task("read2", "Read file2.py", lambda: read_file("file2.py"), []), Task("analyze", "Analyze", lambda: analyze(), ["read1", "read2"]), ] plan = executor.plan(tasks) results = executor.execute(plan) """ def __init__(self, max_workers: int = 10): self.max_workers = max_workers def plan(self, tasks: List[Task]) -> ExecutionPlan: """ Create execution plan with automatic parallelization Builds dependency graph and identifies parallel groups. """ print(f"⚡ Parallel Executor: Planning {len(tasks)} tasks") print("=" * 60) # Find parallel groups using topological sort groups = [] completed = set() group_id = 0 while len(completed) < len(tasks): # Find tasks that can execute now (dependencies met) ready = [ task for task in tasks if task.id not in completed and task.can_execute(completed) ] if not ready: # Circular dependency or logic error remaining = [t.id for t in tasks if t.id not in completed] raise ValueError(f"Circular dependency detected: {remaining}") # Create parallel group group = ParallelGroup( group_id=group_id, tasks=ready, dependencies=set().union(*[set(t.depends_on) for t in ready]), ) groups.append(group) # Mark as completed for dependency resolution completed.update(task.id for task in ready) group_id += 1 # Calculate time estimates # Assume each task takes 1 second (placeholder) task_time = 1.0 sequential_time = len(tasks) * task_time # Parallel time = sum of slowest task in each group parallel_time = sum( max(1, len(group.tasks) // self.max_workers) * task_time for group in groups ) speedup = sequential_time / parallel_time if parallel_time > 0 else 1.0 plan = ExecutionPlan( groups=groups, total_tasks=len(tasks), sequential_time_estimate=sequential_time, parallel_time_estimate=parallel_time, speedup=speedup, ) print(plan) print("=" * 60) return plan def execute(self, plan: ExecutionPlan) -> Dict[str, Any]: """ Execute plan with parallel groups Returns dict of task_id -> result """ print(f"\n🚀 Executing {plan.total_tasks} tasks in {len(plan.groups)} groups") print("=" * 60) results = {} start_time = time.time() for group in plan.groups: print(f"\n📦 {group}") group_start = time.time() # Execute group in parallel group_results = self._execute_group(group) results.update(group_results) group_time = time.time() - group_start print(f" Completed in {group_time:.2f}s") total_time = time.time() - start_time actual_speedup = plan.sequential_time_estimate / total_time print("\n" + "=" * 60) print(f"✅ All tasks completed in {total_time:.2f}s") print(f" Estimated: {plan.parallel_time_estimate:.2f}s") print(f" Actual speedup: {actual_speedup:.1f}x") print("=" * 60) return results def _execute_group(self, group: ParallelGroup) -> Dict[str, Any]: """Execute single parallel group""" results = {} with ThreadPoolExecutor(max_workers=self.max_workers) as executor: # Submit all tasks in group future_to_task = { executor.submit(task.execute): task for task in group.tasks } # Collect results as they complete for future in as_completed(future_to_task): task = future_to_task[future] try: result = future.result() task.status = TaskStatus.COMPLETED task.result = result results[task.id] = result print(f" ✅ {task.description}") except Exception as e: task.status = TaskStatus.FAILED task.error = e results[task.id] = None print(f" ❌ {task.description}: {e}") return results # Convenience functions for common patterns def parallel_file_operations(files: List[str], operation: Callable) -> List[Any]: """ Execute operation on multiple files in parallel Example: results = parallel_file_operations( ["file1.py", "file2.py", "file3.py"], lambda f: read_file(f) ) """ executor = ParallelExecutor() tasks = [ Task( id=f"op_{i}", description=f"Process {file}", execute=lambda f=file: operation(f), depends_on=[], ) for i, file in enumerate(files) ] plan = executor.plan(tasks) results = executor.execute(plan) return [results[task.id] for task in tasks] def should_parallelize(items: List[Any], threshold: int = 3) -> bool: """ Auto-trigger for parallel execution Returns True if number of items exceeds threshold. """ return len(items) >= threshold # Example usage patterns def example_parallel_read(): """Example: Parallel file reading""" files = ["file1.py", "file2.py", "file3.py", "file4.py", "file5.py"] executor = ParallelExecutor() tasks = [ Task( id=f"read_{i}", description=f"Read {file}", execute=lambda f=file: f"Content of {f}", # Placeholder depends_on=[], ) for i, file in enumerate(files) ] plan = executor.plan(tasks) results = executor.execute(plan) return results def example_dependent_tasks(): """Example: Tasks with dependencies""" executor = ParallelExecutor() tasks = [ # Wave 1: Independent reads (parallel) Task("read1", "Read config.py", lambda: "config", []), Task("read2", "Read utils.py", lambda: "utils", []), Task("read3", "Read main.py", lambda: "main", []), # Wave 2: Analysis (depends on reads) Task( "analyze", "Analyze code", lambda: "analysis", ["read1", "read2", "read3"] ), # Wave 3: Generate report (depends on analysis) Task("report", "Generate report", lambda: "report", ["analyze"]), ] plan = executor.plan(tasks) # Expected: 3 groups (Wave 1: 3 parallel, Wave 2: 1, Wave 3: 1) results = executor.execute(plan) return results if __name__ == "__main__": print("Example 1: Parallel file reading") example_parallel_read() print("\n" * 2) print("Example 2: Dependent tasks") example_dependent_tasks()
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/execution/parallel.py", "license": "MIT License", "lines": 246, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/execution/reflection.py
""" Reflection Engine - 3-Stage Pre-Execution Confidence Check Implements the "Triple Reflection" pattern: 1. Requirement clarity analysis 2. Past mistake pattern detection 3. Context sufficiency validation Only proceeds with execution if confidence >70%. """ import json from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional @dataclass class ReflectionResult: """Single reflection analysis result""" stage: str score: float # 0.0 - 1.0 evidence: List[str] concerns: List[str] def __repr__(self) -> str: emoji = "✅" if self.score > 0.7 else "⚠️" if self.score > 0.4 else "❌" return f"{emoji} {self.stage}: {self.score:.0%}" @dataclass class ConfidenceScore: """Overall pre-execution confidence assessment""" # Individual reflection scores requirement_clarity: ReflectionResult mistake_check: ReflectionResult context_ready: ReflectionResult # Overall confidence (weighted average) confidence: float # Decision should_proceed: bool blockers: List[str] recommendations: List[str] def __repr__(self) -> str: status = "🟢 PROCEED" if self.should_proceed else "🔴 BLOCKED" return ( f"{status} | Confidence: {self.confidence:.0%}\n" + f" Clarity: {self.requirement_clarity}\n" + f" Mistakes: {self.mistake_check}\n" + f" Context: {self.context_ready}" ) class ReflectionEngine: """ 3-Stage Pre-Execution Reflection System Prevents wrong-direction execution by deep reflection before committing resources to implementation. Workflow: 1. Reflect on requirement clarity (what to build) 2. Reflect on past mistakes (what not to do) 3. Reflect on context readiness (can I do it) 4. Calculate overall confidence 5. BLOCK if <70%, PROCEED if ≥70% """ def __init__(self, repo_path: Path): self.repo_path = repo_path self.memory_path = repo_path / "docs" / "memory" self.memory_path.mkdir(parents=True, exist_ok=True) # Confidence threshold self.CONFIDENCE_THRESHOLD = 0.7 # Weights for confidence calculation self.WEIGHTS = { "clarity": 0.5, # Most important "mistakes": 0.3, # Learn from past "context": 0.2, # Least critical (can load more) } def reflect( self, task: str, context: Optional[Dict[str, Any]] = None ) -> ConfidenceScore: """ 3-Stage Reflection Process Returns confidence score with decision to proceed or block. """ print("🧠 Reflection Engine: 3-Stage Analysis") print("=" * 60) # Stage 1: Requirement Clarity clarity = self._reflect_clarity(task, context) print(f"1️⃣ {clarity}") # Stage 2: Past Mistakes mistakes = self._reflect_mistakes(task, context) print(f"2️⃣ {mistakes}") # Stage 3: Context Readiness context_ready = self._reflect_context(task, context) print(f"3️⃣ {context_ready}") # Calculate overall confidence confidence = ( clarity.score * self.WEIGHTS["clarity"] + mistakes.score * self.WEIGHTS["mistakes"] + context_ready.score * self.WEIGHTS["context"] ) # Decision logic should_proceed = confidence >= self.CONFIDENCE_THRESHOLD # Collect blockers and recommendations blockers = [] recommendations = [] if clarity.score < 0.7: blockers.extend(clarity.concerns) recommendations.append("Clarify requirements with user") if mistakes.score < 0.7: blockers.extend(mistakes.concerns) recommendations.append("Review past mistakes before proceeding") if context_ready.score < 0.7: blockers.extend(context_ready.concerns) recommendations.append("Load additional context files") result = ConfidenceScore( requirement_clarity=clarity, mistake_check=mistakes, context_ready=context_ready, confidence=confidence, should_proceed=should_proceed, blockers=blockers, recommendations=recommendations, ) print("=" * 60) print(result) print("=" * 60) return result def _reflect_clarity( self, task: str, context: Optional[Dict] = None ) -> ReflectionResult: """ Reflection 1: Requirement Clarity Analyzes if the task description is specific enough to proceed with implementation. """ evidence = [] concerns = [] score = 0.5 # Start neutral # Check for specificity indicators specific_verbs = [ "create", "fix", "add", "update", "delete", "refactor", "implement", ] vague_verbs = ["improve", "optimize", "enhance", "better", "something"] task_lower = task.lower() # Positive signals (increase score) if any(verb in task_lower for verb in specific_verbs): score += 0.2 evidence.append("Contains specific action verb") # Technical terms present if any( term in task_lower for term in ["function", "class", "file", "api", "endpoint"] ): score += 0.15 evidence.append("Includes technical specifics") # Has concrete targets if any(char in task for char in ["/", ".", "(", ")"]): score += 0.15 evidence.append("References concrete code elements") # Negative signals (decrease score) if any(verb in task_lower for verb in vague_verbs): score -= 0.2 concerns.append("Contains vague action verbs") # Too short (likely unclear) if len(task.split()) < 5: score -= 0.15 concerns.append("Task description too brief") # Clamp score to [0, 1] score = max(0.0, min(1.0, score)) return ReflectionResult( stage="Requirement Clarity", score=score, evidence=evidence, concerns=concerns, ) def _reflect_mistakes( self, task: str, context: Optional[Dict] = None ) -> ReflectionResult: """ Reflection 2: Past Mistake Check Searches for similar past mistakes and warns if detected. """ evidence = [] concerns = [] score = 1.0 # Start optimistic (no mistakes known) # Load reflexion memory reflexion_file = self.memory_path / "reflexion.json" if not reflexion_file.exists(): evidence.append("No past mistakes recorded") return ReflectionResult( stage="Past Mistakes", score=score, evidence=evidence, concerns=concerns ) try: with open(reflexion_file) as f: reflexion_data = json.load(f) past_mistakes = reflexion_data.get("mistakes", []) # Search for similar mistakes similar_mistakes = [] task_keywords = set(task.lower().split()) for mistake in past_mistakes: mistake_keywords = set(mistake.get("task", "").lower().split()) overlap = task_keywords & mistake_keywords if len(overlap) >= 2: # At least 2 common words similar_mistakes.append(mistake) if similar_mistakes: score -= 0.3 * min(len(similar_mistakes), 3) # Max -0.9 concerns.append(f"Found {len(similar_mistakes)} similar past mistakes") for mistake in similar_mistakes[:3]: # Show max 3 concerns.append(f" ⚠️ {mistake.get('mistake', 'Unknown')}") else: evidence.append( f"Checked {len(past_mistakes)} past mistakes - none similar" ) except Exception as e: concerns.append(f"Could not load reflexion memory: {e}") score = 0.7 # Neutral when can't check # Clamp score score = max(0.0, min(1.0, score)) return ReflectionResult( stage="Past Mistakes", score=score, evidence=evidence, concerns=concerns ) def _reflect_context( self, task: str, context: Optional[Dict] = None ) -> ReflectionResult: """ Reflection 3: Context Readiness Validates that sufficient context is loaded to proceed. """ evidence = [] concerns = [] score = 0.5 # Start neutral # Check if context provided if not context: concerns.append("No context provided") score = 0.3 return ReflectionResult( stage="Context Readiness", score=score, evidence=evidence, concerns=concerns, ) # Check for essential context elements essential_keys = ["project_index", "current_branch", "git_status"] loaded_keys = [key for key in essential_keys if key in context] if len(loaded_keys) == len(essential_keys): score += 0.3 evidence.append("All essential context loaded") else: missing = set(essential_keys) - set(loaded_keys) score -= 0.2 concerns.append(f"Missing context: {', '.join(missing)}") # Check project index exists and is fresh index_path = self.repo_path / "PROJECT_INDEX.md" if index_path.exists(): # Check age age_days = (datetime.now().timestamp() - index_path.stat().st_mtime) / 86400 if age_days < 7: score += 0.2 evidence.append(f"Project index is fresh ({age_days:.1f} days old)") else: concerns.append(f"Project index is stale ({age_days:.0f} days old)") else: score -= 0.2 concerns.append("Project index missing") # Clamp score score = max(0.0, min(1.0, score)) return ReflectionResult( stage="Context Readiness", score=score, evidence=evidence, concerns=concerns ) def record_reflection(self, task: str, confidence: ConfidenceScore, decision: str): """Record reflection results for future learning""" reflection_log = self.memory_path / "reflection_log.json" entry = { "timestamp": datetime.now().isoformat(), "task": task, "confidence": confidence.confidence, "decision": decision, "blockers": confidence.blockers, "recommendations": confidence.recommendations, } # Append to log try: if reflection_log.exists(): with open(reflection_log) as f: log_data = json.load(f) else: log_data = {"reflections": []} log_data["reflections"].append(entry) with open(reflection_log, "w") as f: json.dump(log_data, f, indent=2) except Exception as e: print(f"⚠️ Could not record reflection: {e}") # Singleton instance _reflection_engine: Optional[ReflectionEngine] = None def get_reflection_engine(repo_path: Optional[Path] = None) -> ReflectionEngine: """Get or create reflection engine singleton""" global _reflection_engine if _reflection_engine is None: if repo_path is None: repo_path = Path.cwd() _reflection_engine = ReflectionEngine(repo_path) return _reflection_engine # Convenience function def reflect_before_execution( task: str, context: Optional[Dict] = None ) -> ConfidenceScore: """ Perform 3-stage reflection before task execution Returns ConfidenceScore with decision to proceed or block. """ engine = get_reflection_engine() return engine.reflect(task, context)
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/execution/reflection.py", "license": "MIT License", "lines": 310, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/execution/self_correction.py
""" Self-Correction Engine - Learn from Mistakes Detects failures, analyzes root causes, and prevents recurrence through Reflexion-based learning. Key features: - Automatic failure detection - Root cause analysis - Pattern recognition across failures - Prevention rule generation - Persistent learning memory """ import hashlib import json from dataclasses import asdict, dataclass from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional @dataclass class RootCause: """Identified root cause of failure""" category: str # e.g., "validation", "dependency", "logic", "assumption" description: str evidence: List[str] prevention_rule: str validation_tests: List[str] def __repr__(self) -> str: return ( f"Root Cause: {self.category}\n" f" Description: {self.description}\n" f" Prevention: {self.prevention_rule}\n" f" Tests: {len(self.validation_tests)} validation checks" ) @dataclass class FailureEntry: """Single failure entry in Reflexion memory""" id: str timestamp: str task: str failure_type: str error_message: str root_cause: RootCause fixed: bool fix_description: Optional[str] = None recurrence_count: int = 0 def to_dict(self) -> dict: """Convert to JSON-serializable dict""" d = asdict(self) d["root_cause"] = asdict(self.root_cause) return d @classmethod def from_dict(cls, data: dict) -> "FailureEntry": """Create from dict""" root_cause_data = data.pop("root_cause") root_cause = RootCause(**root_cause_data) return cls(**data, root_cause=root_cause) class SelfCorrectionEngine: """ Self-Correction Engine with Reflexion Learning Workflow: 1. Detect failure 2. Analyze root cause 3. Store in Reflexion memory 4. Generate prevention rules 5. Apply automatically in future executions """ def __init__(self, repo_path: Path): self.repo_path = repo_path self.memory_path = repo_path / "docs" / "memory" self.memory_path.mkdir(parents=True, exist_ok=True) self.reflexion_file = self.memory_path / "reflexion.json" # Initialize reflexion memory if needed if not self.reflexion_file.exists(): self._init_reflexion_memory() def _init_reflexion_memory(self): """Initialize empty reflexion memory""" initial_data = { "version": "1.0", "created": datetime.now().isoformat(), "mistakes": [], "patterns": [], "prevention_rules": [], } with open(self.reflexion_file, "w") as f: json.dump(initial_data, f, indent=2) def detect_failure(self, execution_result: Dict[str, Any]) -> bool: """ Detect if execution failed Returns True if failure detected. """ status = execution_result.get("status", "unknown") return status in ["failed", "error", "exception"] def analyze_root_cause(self, task: str, failure: Dict[str, Any]) -> RootCause: """ Analyze root cause of failure Uses pattern matching and similarity search to identify the fundamental cause. """ print("🔍 Self-Correction: Analyzing root cause") print("=" * 60) error_msg = failure.get("error", "Unknown error") stack_trace = failure.get("stack_trace", "") # Pattern recognition category = self._categorize_failure(error_msg, stack_trace) # Load past similar failures similar = self._find_similar_failures(task, error_msg) if similar: print(f"Found {len(similar)} similar past failures") # Generate prevention rule prevention_rule = self._generate_prevention_rule(category, error_msg, similar) # Generate validation tests validation_tests = self._generate_validation_tests(category, error_msg) root_cause = RootCause( category=category, description=error_msg, evidence=[error_msg, stack_trace] if stack_trace else [error_msg], prevention_rule=prevention_rule, validation_tests=validation_tests, ) print(root_cause) print("=" * 60) return root_cause def _categorize_failure(self, error_msg: str, stack_trace: str) -> str: """Categorize failure type""" error_lower = error_msg.lower() # Validation failures if any( word in error_lower for word in ["invalid", "missing", "required", "must"] ): return "validation" # Dependency failures if any( word in error_lower for word in ["not found", "missing", "import", "module"] ): return "dependency" # Logic errors if any(word in error_lower for word in ["assertion", "expected", "actual"]): return "logic" # Assumption failures if any(word in error_lower for word in ["assume", "should", "expected"]): return "assumption" # Type errors if "type" in error_lower: return "type" return "unknown" def _find_similar_failures(self, task: str, error_msg: str) -> List[FailureEntry]: """Find similar past failures""" try: with open(self.reflexion_file) as f: data = json.load(f) past_failures = [ FailureEntry.from_dict(entry) for entry in data.get("mistakes", []) ] # Simple similarity: keyword overlap task_keywords = set(task.lower().split()) error_keywords = set(error_msg.lower().split()) similar = [] for failure in past_failures: failure_keywords = set(failure.task.lower().split()) error_keywords_past = set(failure.error_message.lower().split()) task_overlap = len(task_keywords & failure_keywords) error_overlap = len(error_keywords & error_keywords_past) if task_overlap >= 2 or error_overlap >= 2: similar.append(failure) return similar except Exception as e: print(f"⚠️ Could not load reflexion memory: {e}") return [] def _generate_prevention_rule( self, category: str, error_msg: str, similar: List[FailureEntry] ) -> str: """Generate prevention rule based on failure analysis""" rules = { "validation": "ALWAYS validate inputs before processing", "dependency": "ALWAYS check dependencies exist before importing", "logic": "ALWAYS verify assumptions with assertions", "assumption": "NEVER assume - always verify with checks", "type": "ALWAYS use type hints and runtime type checking", "unknown": "ALWAYS add error handling for unknown cases", } base_rule = rules.get(category, "ALWAYS add defensive checks") # If similar failures exist, reference them if similar: base_rule += f" (similar mistake occurred {len(similar)} times before)" return base_rule def _generate_validation_tests(self, category: str, error_msg: str) -> List[str]: """Generate validation tests to prevent recurrence""" tests = { "validation": [ "Check input is not None", "Verify input type matches expected", "Validate input range/constraints", ], "dependency": [ "Verify module exists before import", "Check file exists before reading", "Validate path is accessible", ], "logic": [ "Add assertion for pre-conditions", "Add assertion for post-conditions", "Verify intermediate results", ], "assumption": [ "Explicitly check assumed condition", "Add logging for assumption verification", "Document assumption with test", ], "type": [ "Add type hints", "Add runtime type checking", "Use dataclass with validation", ], } return tests.get(category, ["Add defensive check", "Add error handling"]) def learn_and_prevent( self, task: str, failure: Dict[str, Any], root_cause: RootCause, fixed: bool = False, fix_description: Optional[str] = None, ): """ Learn from failure and store prevention rules Updates Reflexion memory with new learning. """ print("📚 Self-Correction: Learning from failure") # Generate unique ID for this failure failure_id = hashlib.md5( f"{task}{failure.get('error', '')}".encode() ).hexdigest()[:8] # Create failure entry entry = FailureEntry( id=failure_id, timestamp=datetime.now().isoformat(), task=task, failure_type=failure.get("type", "unknown"), error_message=failure.get("error", "Unknown error"), root_cause=root_cause, fixed=fixed, fix_description=fix_description, recurrence_count=0, ) # Load current reflexion memory with open(self.reflexion_file) as f: data = json.load(f) # Check if similar failure exists (increment recurrence) existing_failures = data.get("mistakes", []) updated = False for existing in existing_failures: if existing.get("id") == failure_id: existing["recurrence_count"] += 1 existing["timestamp"] = entry.timestamp updated = True print(f"⚠️ Recurring failure (count: {existing['recurrence_count']})") break if not updated: # New failure - add to memory data["mistakes"].append(entry.to_dict()) print(f"✅ New failure recorded: {failure_id}") # Add prevention rule if not already present if root_cause.prevention_rule not in data.get("prevention_rules", []): if "prevention_rules" not in data: data["prevention_rules"] = [] data["prevention_rules"].append(root_cause.prevention_rule) print("📝 Prevention rule added") # Save updated memory with open(self.reflexion_file, "w") as f: json.dump(data, f, indent=2) print("💾 Reflexion memory updated") def get_prevention_rules(self) -> List[str]: """Get all active prevention rules""" try: with open(self.reflexion_file) as f: data = json.load(f) return data.get("prevention_rules", []) except Exception: return [] def check_against_past_mistakes(self, task: str) -> List[FailureEntry]: """ Check if task is similar to past mistakes Returns list of relevant past failures to warn about. """ try: with open(self.reflexion_file) as f: data = json.load(f) past_failures = [ FailureEntry.from_dict(entry) for entry in data.get("mistakes", []) ] # Find similar tasks task_keywords = set(task.lower().split()) relevant = [] for failure in past_failures: failure_keywords = set(failure.task.lower().split()) overlap = len(task_keywords & failure_keywords) if overlap >= 2: relevant.append(failure) return relevant except Exception: return [] # Singleton instance _self_correction_engine: Optional[SelfCorrectionEngine] = None def get_self_correction_engine( repo_path: Optional[Path] = None, ) -> SelfCorrectionEngine: """Get or create self-correction engine singleton""" global _self_correction_engine if _self_correction_engine is None: if repo_path is None: repo_path = Path.cwd() _self_correction_engine = SelfCorrectionEngine(repo_path) return _self_correction_engine # Convenience function def learn_from_failure( task: str, failure: Dict[str, Any], fixed: bool = False, fix_description: Optional[str] = None, ): """ Learn from execution failure Analyzes root cause and stores prevention rules. """ engine = get_self_correction_engine() # Analyze root cause root_cause = engine.analyze_root_cause(task, failure) # Store learning engine.learn_and_prevent(task, failure, root_cause, fixed, fix_description) return root_cause
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/execution/self_correction.py", "license": "MIT License", "lines": 329, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:src/superclaude/pm_agent/confidence.py
""" Pre-implementation Confidence Check Prevents wrong-direction execution by assessing confidence BEFORE starting. Token Budget: 100-200 tokens ROI: 25-250x token savings when stopping wrong direction Confidence Levels: - High (≥90%): Root cause identified, solution verified, no duplication, architecture-compliant - Medium (70-89%): Multiple approaches possible, trade-offs require consideration - Low (<70%): Investigation incomplete, unclear root cause, missing official docs Required Checks: 1. No duplicate implementations (check existing code first) 2. Architecture compliance (use existing tech stack, e.g., Supabase not custom API) 3. Official documentation verified 4. Working OSS implementations referenced 5. Root cause identified with high certainty """ from pathlib import Path from typing import Any, Dict class ConfidenceChecker: """ Pre-implementation confidence assessment Usage: checker = ConfidenceChecker() confidence = checker.assess(context) if confidence >= 0.9: # High confidence - proceed immediately elif confidence >= 0.7: # Medium confidence - present options to user else: # Low confidence - STOP and request clarification """ def assess(self, context: Dict[str, Any]) -> float: """ Assess confidence level (0.0 - 1.0) Investigation Phase Checks: 1. No duplicate implementations? (25%) 2. Architecture compliance? (25%) 3. Official documentation verified? (20%) 4. Working OSS implementations referenced? (15%) 5. Root cause identified? (15%) Args: context: Context dict with task details Returns: float: Confidence score (0.0 = no confidence, 1.0 = absolute certainty) """ score = 0.0 checks = [] # Check 1: No duplicate implementations (25%) if self._no_duplicates(context): score += 0.25 checks.append("✅ No duplicate implementations found") else: checks.append("❌ Check for existing implementations first") # Check 2: Architecture compliance (25%) if self._architecture_compliant(context): score += 0.25 checks.append("✅ Uses existing tech stack (e.g., Supabase)") else: checks.append("❌ Verify architecture compliance (avoid reinventing)") # Check 3: Official documentation verified (20%) if self._has_official_docs(context): score += 0.2 checks.append("✅ Official documentation verified") else: checks.append("❌ Read official docs first") # Check 4: Working OSS implementations referenced (15%) if self._has_oss_reference(context): score += 0.15 checks.append("✅ Working OSS implementation found") else: checks.append("❌ Search for OSS implementations") # Check 5: Root cause identified (15%) if self._root_cause_identified(context): score += 0.15 checks.append("✅ Root cause identified") else: checks.append("❌ Continue investigation to identify root cause") # Store check results for reporting context["confidence_checks"] = checks return score def _has_official_docs(self, context: Dict[str, Any]) -> bool: """ Check if official documentation exists Looks for: - README.md in project - CLAUDE.md with relevant patterns - docs/ directory with related content """ # Check context flag first (for testing) if "official_docs_verified" in context: return context.get("official_docs_verified", False) # Check for test file path test_file = context.get("test_file") if not test_file: return False project_root = Path(test_file).parent while project_root.parent != project_root: # Check for documentation files if (project_root / "README.md").exists(): return True if (project_root / "CLAUDE.md").exists(): return True if (project_root / "docs").exists(): return True project_root = project_root.parent return False def _no_duplicates(self, context: Dict[str, Any]) -> bool: """ Check for duplicate implementations Before implementing, verify: - No existing similar functions/modules (Glob/Grep) - No helper functions that solve the same problem - No libraries that provide this functionality Returns True if no duplicates found (investigation complete) """ # This is a placeholder - actual implementation should: # 1. Search codebase with Glob/Grep for similar patterns # 2. Check project dependencies for existing solutions # 3. Verify no helper modules provide this functionality duplicate_check = context.get("duplicate_check_complete", False) return duplicate_check def _architecture_compliant(self, context: Dict[str, Any]) -> bool: """ Check architecture compliance Verify solution uses existing tech stack: - Supabase project → Use Supabase APIs (not custom API) - Next.js project → Use Next.js patterns (not custom routing) - Turborepo → Use workspace patterns (not manual scripts) Returns True if solution aligns with project architecture """ # This is a placeholder - actual implementation should: # 1. Read CLAUDE.md for project tech stack # 2. Verify solution uses existing infrastructure # 3. Check not reinventing provided functionality architecture_check = context.get("architecture_check_complete", False) return architecture_check def _has_oss_reference(self, context: Dict[str, Any]) -> bool: """ Check if working OSS implementations referenced Search for: - Similar open-source solutions - Reference implementations in popular projects - Community best practices Returns True if OSS reference found and analyzed """ # This is a placeholder - actual implementation should: # 1. Search GitHub for similar implementations # 2. Read popular OSS projects solving same problem # 3. Verify approach matches community patterns oss_check = context.get("oss_reference_complete", False) return oss_check def _root_cause_identified(self, context: Dict[str, Any]) -> bool: """ Check if root cause is identified with high certainty Verify: - Problem source pinpointed (not guessing) - Solution addresses root cause (not symptoms) - Fix verified against official docs/OSS patterns Returns True if root cause clearly identified """ # This is a placeholder - actual implementation should: # 1. Verify problem analysis complete # 2. Check solution addresses root cause # 3. Confirm fix aligns with best practices root_cause_check = context.get("root_cause_identified", False) return root_cause_check def _has_existing_patterns(self, context: Dict[str, Any]) -> bool: """ Check if existing patterns can be followed Looks for: - Similar test files - Common naming conventions - Established directory structure """ test_file = context.get("test_file") if not test_file: return False test_path = Path(test_file) test_dir = test_path.parent # Check for other test files in same directory if test_dir.exists(): test_files = list(test_dir.glob("test_*.py")) return len(test_files) > 1 return False def _has_clear_path(self, context: Dict[str, Any]) -> bool: """ Check if implementation path is clear Considers: - Test name suggests clear purpose - Markers indicate test type - Context has sufficient information """ # Check test name clarity test_name = context.get("test_name", "") if not test_name or test_name == "test_example": return False # Check for markers indicating test type markers = context.get("markers", []) known_markers = { "unit", "integration", "hallucination", "performance", "confidence_check", "self_check", } has_markers = bool(set(markers) & known_markers) return has_markers or len(test_name) > 10 def get_recommendation(self, confidence: float) -> str: """ Get recommended action based on confidence level Args: confidence: Confidence score (0.0 - 1.0) Returns: str: Recommended action """ if confidence >= 0.9: return "✅ High confidence (≥90%) - Proceed with implementation" elif confidence >= 0.7: return "⚠️ Medium confidence (70-89%) - Continue investigation, DO NOT implement yet" else: return "❌ Low confidence (<70%) - STOP and continue investigation loop"
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/pm_agent/confidence.py", "license": "MIT License", "lines": 222, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
SuperClaude-Org/SuperClaude_Framework:src/superclaude/pm_agent/reflexion.py
""" Reflexion Error Learning Pattern Learn from past errors to prevent recurrence. Token Budget: - Cache hit: 0 tokens (known error → instant solution) - Cache miss: 1-2K tokens (new investigation) Performance: - Error recurrence rate: <10% - Solution reuse rate: >90% Storage Strategy: - Primary: docs/memory/solutions_learned.jsonl (local file) - Secondary: mindbase (if available, semantic search) - Fallback: grep-based text search Process: 1. Error detected → Check past errors (smart lookup) 2. IF similar found → Apply known solution (0 tokens) 3. ELSE → Investigate root cause → Document solution 4. Store for future reference (dual storage) """ import json from datetime import datetime from pathlib import Path from typing import Any, Dict, Optional class ReflexionPattern: """ Error learning and prevention through reflexion Usage: reflexion = ReflexionPattern() # When error occurs error_info = { "error_type": "AssertionError", "error_message": "Expected 5, got 3", "test_name": "test_calculation", } # Check for known solution solution = reflexion.get_solution(error_info) if solution: print(f"✅ Known error - Solution: {solution}") else: # New error - investigate and record reflexion.record_error(error_info) """ def __init__(self, memory_dir: Optional[Path] = None): """ Initialize reflexion pattern Args: memory_dir: Directory for storing error solutions (defaults to docs/memory/ in current project) """ if memory_dir is None: # Default to docs/memory/ in current working directory memory_dir = Path.cwd() / "docs" / "memory" self.memory_dir = memory_dir self.solutions_file = memory_dir / "solutions_learned.jsonl" self.mistakes_dir = memory_dir.parent / "mistakes" # Ensure directories exist self.memory_dir.mkdir(parents=True, exist_ok=True) self.mistakes_dir.mkdir(parents=True, exist_ok=True) def get_solution(self, error_info: Dict[str, Any]) -> Optional[Dict[str, Any]]: """ Get known solution for similar error Lookup strategy: 1. Try mindbase semantic search (if available) 2. Fallback to grep-based text search 3. Return None if no match found Args: error_info: Error information dict Returns: Solution dict if found, None otherwise """ error_signature = self._create_error_signature(error_info) # Try mindbase first (semantic search, 500 tokens) solution = self._search_mindbase(error_signature) if solution: return solution # Fallback to file-based search (0 tokens, local grep) solution = self._search_local_files(error_signature) return solution def record_error(self, error_info: Dict[str, Any]) -> None: """ Record error and solution for future learning Stores to: 1. docs/memory/solutions_learned.jsonl (append-only log) 2. docs/mistakes/[feature]-[date].md (detailed analysis) Args: error_info: Error information dict containing: - test_name: Name of failing test - error_type: Type of error (e.g., AssertionError) - error_message: Error message - traceback: Stack trace - solution (optional): Solution applied - root_cause (optional): Root cause analysis """ # Add timestamp error_info["timestamp"] = datetime.now().isoformat() # Append to solutions log (JSONL format) with self.solutions_file.open("a") as f: f.write(json.dumps(error_info) + "\n") # If this is a significant error with analysis, create mistake doc if error_info.get("root_cause") or error_info.get("solution"): self._create_mistake_doc(error_info) def _create_error_signature(self, error_info: Dict[str, Any]) -> str: """ Create error signature for matching Combines: - Error type - Key parts of error message - Test context Args: error_info: Error information dict Returns: str: Error signature for matching """ parts = [] if "error_type" in error_info: parts.append(error_info["error_type"]) if "error_message" in error_info: # Extract key words from error message message = error_info["error_message"] # Remove numbers (often varies between errors) import re message = re.sub(r"\d+", "N", message) parts.append(message[:100]) # First 100 chars if "test_name" in error_info: parts.append(error_info["test_name"]) return " | ".join(parts) def _search_mindbase(self, error_signature: str) -> Optional[Dict[str, Any]]: """ Search for similar error in mindbase (semantic search) Args: error_signature: Error signature to search Returns: Solution dict if found, None if mindbase unavailable or no match """ # TODO: Implement mindbase integration # For now, return None (fallback to file search) return None def _search_local_files(self, error_signature: str) -> Optional[Dict[str, Any]]: """ Search for similar error in local JSONL file Uses simple text matching on error signatures. Args: error_signature: Error signature to search Returns: Solution dict if found, None otherwise """ if not self.solutions_file.exists(): return None # Read JSONL file and search with self.solutions_file.open("r") as f: for line in f: try: record = json.loads(line) stored_signature = self._create_error_signature(record) # Simple similarity check if self._signatures_match(error_signature, stored_signature): return { "solution": record.get("solution"), "root_cause": record.get("root_cause"), "prevention": record.get("prevention"), "timestamp": record.get("timestamp"), } except json.JSONDecodeError: continue return None def _signatures_match(self, sig1: str, sig2: str, threshold: float = 0.7) -> bool: """ Check if two error signatures match Simple word overlap check (good enough for most cases). Args: sig1: First signature sig2: Second signature threshold: Minimum word overlap ratio (default: 0.7) Returns: bool: Whether signatures are similar enough """ words1 = set(sig1.lower().split()) words2 = set(sig2.lower().split()) if not words1 or not words2: return False overlap = len(words1 & words2) total = len(words1 | words2) return (overlap / total) >= threshold def _create_mistake_doc(self, error_info: Dict[str, Any]) -> None: """ Create detailed mistake documentation Format: docs/mistakes/[feature]-YYYY-MM-DD.md Structure: - What Happened - Root Cause - Why Missed - Fix Applied - Prevention Checklist - Lesson Learned Args: error_info: Error information with analysis """ # Generate filename test_name = error_info.get("test_name", "unknown") date = datetime.now().strftime("%Y-%m-%d") filename = f"{test_name}-{date}.md" filepath = self.mistakes_dir / filename # Create mistake document content = f"""# Mistake Record: {test_name} **Date**: {date} **Error Type**: {error_info.get("error_type", "Unknown")} --- ## ❌ What Happened {error_info.get("error_message", "No error message")} ``` {error_info.get("traceback", "No traceback")} ``` --- ## 🔍 Root Cause {error_info.get("root_cause", "Not analyzed")} --- ## 🤔 Why Missed {error_info.get("why_missed", "Not analyzed")} --- ## ✅ Fix Applied {error_info.get("solution", "Not documented")} --- ## 🛡️ Prevention Checklist {error_info.get("prevention", "Not documented")} --- ## 💡 Lesson Learned {error_info.get("lesson", "Not documented")} """ filepath.write_text(content) def get_statistics(self) -> Dict[str, Any]: """ Get reflexion pattern statistics Returns: Dict with statistics: - total_errors: Total errors recorded - errors_with_solutions: Errors with documented solutions - solution_reuse_rate: Percentage of reused solutions """ if not self.solutions_file.exists(): return { "total_errors": 0, "errors_with_solutions": 0, "solution_reuse_rate": 0.0, } total = 0 with_solutions = 0 with self.solutions_file.open("r") as f: for line in f: try: record = json.loads(line) total += 1 if record.get("solution"): with_solutions += 1 except json.JSONDecodeError: continue return { "total_errors": total, "errors_with_solutions": with_solutions, "solution_reuse_rate": (with_solutions / total * 100) if total > 0 else 0.0, }
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/pm_agent/reflexion.py", "license": "MIT License", "lines": 260, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
SuperClaude-Org/SuperClaude_Framework:src/superclaude/pm_agent/self_check.py
""" Post-implementation Self-Check Protocol Hallucination prevention through evidence-based validation. Token Budget: 200-2,500 tokens (complexity-dependent) Detection Rate: 94% (Reflexion benchmark) The Four Questions: 1. Are all tests passing? 2. Are all requirements met? 3. No assumptions without verification? 4. Is there evidence? """ from typing import Any, Dict, List, Tuple class SelfCheckProtocol: """ Post-implementation validation Mandatory Questions (The Four Questions): 1. Are all tests passing? → Run tests → Show ACTUAL results → IF any fail: NOT complete 2. Are all requirements met? → Compare implementation vs requirements → List: ✅ Done, ❌ Missing 3. No assumptions without verification? → Review: Assumptions verified? → Check: Official docs consulted? 4. Is there evidence? → Test results (actual output) → Code changes (file list) → Validation (lint, typecheck) Usage: protocol = SelfCheckProtocol() passed, issues = protocol.validate(implementation) if passed: print("✅ Implementation complete with evidence") else: print("❌ Issues detected:") for issue in issues: print(f" - {issue}") """ # 7 Red Flags for Hallucination Detection HALLUCINATION_RED_FLAGS = [ "tests pass", # without showing output "everything works", # without evidence "implementation complete", # with failing tests # Skipping error messages # Ignoring warnings # Hiding failures # "probably works" statements ] def validate(self, implementation: Dict[str, Any]) -> Tuple[bool, List[str]]: """ Run self-check validation Args: implementation: Implementation details dict containing: - tests_passed (bool): Whether tests passed - test_output (str): Actual test output - requirements (List[str]): List of requirements - requirements_met (List[str]): List of met requirements - assumptions (List[str]): List of assumptions made - assumptions_verified (List[str]): List of verified assumptions - evidence (Dict): Evidence dict with test_results, code_changes, validation Returns: Tuple of (passed: bool, issues: List[str]) """ issues = [] # Question 1: Tests passing? if not self._check_tests_passing(implementation): issues.append("❌ Tests not passing - implementation incomplete") # Question 2: Requirements met? unmet = self._check_requirements_met(implementation) if unmet: issues.append(f"❌ Requirements not fully met: {', '.join(unmet)}") # Question 3: Assumptions verified? unverified = self._check_assumptions_verified(implementation) if unverified: issues.append(f"❌ Unverified assumptions: {', '.join(unverified)}") # Question 4: Evidence provided? missing_evidence = self._check_evidence_exists(implementation) if missing_evidence: issues.append(f"❌ Missing evidence: {', '.join(missing_evidence)}") # Additional: Check for hallucination red flags hallucinations = self._detect_hallucinations(implementation) if hallucinations: issues.extend([f"🚨 Hallucination detected: {h}" for h in hallucinations]) return len(issues) == 0, issues def _check_tests_passing(self, impl: Dict[str, Any]) -> bool: """ Verify all tests pass WITH EVIDENCE Must have: - tests_passed = True - test_output (actual results, not just claim) """ if not impl.get("tests_passed", False): return False # Require actual test output (anti-hallucination) test_output = impl.get("test_output", "") if not test_output: return False # Check for passing indicators in output passing_indicators = ["passed", "OK", "✓", "✅"] return any(indicator in test_output for indicator in passing_indicators) def _check_requirements_met(self, impl: Dict[str, Any]) -> List[str]: """ Verify all requirements satisfied Returns: List of unmet requirements (empty if all met) """ requirements = impl.get("requirements", []) requirements_met = set(impl.get("requirements_met", [])) unmet = [] for req in requirements: if req not in requirements_met: unmet.append(req) return unmet def _check_assumptions_verified(self, impl: Dict[str, Any]) -> List[str]: """ Verify assumptions checked against official docs Returns: List of unverified assumptions (empty if all verified) """ assumptions = impl.get("assumptions", []) assumptions_verified = set(impl.get("assumptions_verified", [])) unverified = [] for assumption in assumptions: if assumption not in assumptions_verified: unverified.append(assumption) return unverified def _check_evidence_exists(self, impl: Dict[str, Any]) -> List[str]: """ Verify evidence provided (test results, code changes, validation) Returns: List of missing evidence types (empty if all present) """ evidence = impl.get("evidence", {}) missing = [] # Evidence requirement 1: Test Results if not evidence.get("test_results"): missing.append("test_results") # Evidence requirement 2: Code Changes if not evidence.get("code_changes"): missing.append("code_changes") # Evidence requirement 3: Validation (lint, typecheck, build) if not evidence.get("validation"): missing.append("validation") return missing def _detect_hallucinations(self, impl: Dict[str, Any]) -> List[str]: """ Detect hallucination red flags 7 Red Flags: 1. "Tests pass" without showing output 2. "Everything works" without evidence 3. "Implementation complete" with failing tests 4. Skipping error messages 5. Ignoring warnings 6. Hiding failures 7. "Probably works" statements Returns: List of detected hallucination patterns """ detected = [] # Red Flag 1: "Tests pass" without output if impl.get("tests_passed") and not impl.get("test_output"): detected.append("Claims tests pass without showing output") # Red Flag 2: "Everything works" without evidence if impl.get("status") == "complete" and not impl.get("evidence"): detected.append("Claims completion without evidence") # Red Flag 3: "Complete" with failing tests if impl.get("status") == "complete" and not impl.get("tests_passed"): detected.append("Claims completion despite failing tests") # Red Flag 4-6: Check for ignored errors/warnings errors = impl.get("errors", []) warnings = impl.get("warnings", []) if (errors or warnings) and impl.get("status") == "complete": detected.append("Ignored errors/warnings") # Red Flag 7: Uncertainty language description = impl.get("description", "").lower() uncertainty_words = ["probably", "maybe", "should work", "might work"] if any(word in description for word in uncertainty_words): detected.append(f"Uncertainty language detected: {description}") return detected def format_report(self, passed: bool, issues: List[str]) -> str: """ Format validation report Args: passed: Whether validation passed issues: List of issues detected Returns: str: Formatted report """ if passed: return "✅ Self-Check PASSED - Implementation complete with evidence" report = ["❌ Self-Check FAILED - Issues detected:\n"] for issue in issues: report.append(f" {issue}") return "\n".join(report)
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/pm_agent/self_check.py", "license": "MIT License", "lines": 195, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
SuperClaude-Org/SuperClaude_Framework:src/superclaude/pm_agent/token_budget.py
""" Token Budget Manager Manages token allocation based on task complexity. Token Budget by Complexity: - simple: 200 tokens (typo fix, trivial change) - medium: 1,000 tokens (bug fix, small feature) - complex: 2,500 tokens (large feature, refactoring) """ from typing import Literal ComplexityLevel = Literal["simple", "medium", "complex"] class TokenBudgetManager: """ Token budget management for tasks Usage: manager = TokenBudgetManager(complexity="medium") print(f"Budget: {manager.limit} tokens") """ # Token limits by complexity LIMITS = { "simple": 200, "medium": 1000, "complex": 2500, } def __init__(self, complexity: ComplexityLevel = "medium"): """ Initialize token budget manager Args: complexity: Task complexity level (simple, medium, complex) """ # Validate complexity and default to "medium" if invalid if complexity not in self.LIMITS: complexity = "medium" self.complexity = complexity self.limit = self.LIMITS[complexity] self.used = 0 def allocate(self, amount: int) -> bool: """ Allocate tokens from budget Args: amount: Number of tokens to allocate Returns: bool: True if allocation successful, False if budget exceeded """ if self.used + amount <= self.limit: self.used += amount return True return False def use(self, amount: int) -> bool: """ Consume tokens from the budget. Convenience wrapper around allocate() to match historical CLI usage. """ return self.allocate(amount) @property def remaining(self) -> int: """Number of tokens still available.""" return self.limit - self.used def remaining_tokens(self) -> int: """Backward compatible helper that mirrors the remaining property.""" return self.remaining def reset(self) -> None: """Reset used tokens counter""" self.used = 0 def __repr__(self) -> str: return f"TokenBudgetManager(complexity={self.complexity!r}, limit={self.limit}, used={self.used})"
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/pm_agent/token_budget.py", "license": "MIT License", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
SuperClaude-Org/SuperClaude_Framework:src/superclaude/pytest_plugin.py
""" SuperClaude pytest plugin Auto-loaded when superclaude is installed. Provides PM Agent fixtures and hooks for enhanced testing. Entry point registered in pyproject.toml: [project.entry-points.pytest11] superclaude = "superclaude.pytest_plugin" """ import pytest from .pm_agent.confidence import ConfidenceChecker from .pm_agent.reflexion import ReflexionPattern from .pm_agent.self_check import SelfCheckProtocol from .pm_agent.token_budget import TokenBudgetManager def pytest_configure(config): """ Register SuperClaude plugin and custom markers Markers: - confidence_check: Pre-execution confidence assessment - self_check: Post-implementation validation - reflexion: Error learning and prevention - complexity(level): Set test complexity (simple, medium, complex) """ config.addinivalue_line( "markers", "confidence_check: Pre-execution confidence assessment (min 70%)" ) config.addinivalue_line( "markers", "self_check: Post-implementation validation with evidence requirement", ) config.addinivalue_line( "markers", "reflexion: Error learning and prevention pattern" ) config.addinivalue_line( "markers", "complexity(level): Set test complexity (simple, medium, complex)" ) @pytest.fixture def confidence_checker(): """ Fixture for pre-execution confidence checking Usage: def test_example(confidence_checker): confidence = confidence_checker.assess(context) assert confidence >= 0.7 """ return ConfidenceChecker() @pytest.fixture def self_check_protocol(): """ Fixture for post-implementation self-check protocol Usage: def test_example(self_check_protocol): passed, issues = self_check_protocol.validate(implementation) assert passed """ return SelfCheckProtocol() @pytest.fixture def reflexion_pattern(): """ Fixture for reflexion error learning pattern Usage: def test_example(reflexion_pattern): reflexion_pattern.record_error(...) solution = reflexion_pattern.get_solution(error_signature) """ return ReflexionPattern() @pytest.fixture def token_budget(request): """ Fixture for token budget management Complexity levels: - simple: 200 tokens (typo fix) - medium: 1,000 tokens (bug fix) - complex: 2,500 tokens (feature implementation) Usage: @pytest.mark.complexity("medium") def test_example(token_budget): assert token_budget.limit == 1000 """ # Get test complexity from marker marker = request.node.get_closest_marker("complexity") complexity = marker.args[0] if marker else "medium" return TokenBudgetManager(complexity=complexity) @pytest.fixture def pm_context(tmp_path): """ Fixture providing PM Agent context for testing Creates temporary memory directory structure: - docs/memory/pm_context.md - docs/memory/last_session.md - docs/memory/next_actions.md Usage: def test_example(pm_context): assert pm_context["memory_dir"].exists() pm_context["pm_context"].write_text("# Context") """ memory_dir = tmp_path / "docs" / "memory" memory_dir.mkdir(parents=True) # Create empty memory files (memory_dir / "pm_context.md").touch() (memory_dir / "last_session.md").touch() (memory_dir / "next_actions.md").touch() return { "memory_dir": memory_dir, "pm_context": memory_dir / "pm_context.md", "last_session": memory_dir / "last_session.md", "next_actions": memory_dir / "next_actions.md", } def pytest_runtest_setup(item): """ Pre-test hook for confidence checking If test is marked with @pytest.mark.confidence_check, run pre-execution confidence assessment and skip if < 70%. """ marker = item.get_closest_marker("confidence_check") if marker: checker = ConfidenceChecker() # Build context from test context = { "test_name": item.name, "test_file": str(item.fspath), "markers": [m.name for m in item.iter_markers()], } confidence = checker.assess(context) if confidence < 0.7: pytest.skip(f"Confidence too low: {confidence:.0%} (minimum: 70%)") def pytest_runtest_makereport(item, call): """ Post-test hook for self-check and reflexion Records test outcomes for reflexion learning. Stores error information for future pattern matching. """ if call.when == "call": # Check for reflexion marker marker = item.get_closest_marker("reflexion") if marker and call.excinfo is not None: # Test failed - apply reflexion pattern reflexion = ReflexionPattern() # Record error for future learning error_info = { "test_name": item.name, "test_file": str(item.fspath), "error_type": type(call.excinfo.value).__name__, "error_message": str(call.excinfo.value), "traceback": str(call.excinfo.traceback), } reflexion.record_error(error_info) def pytest_report_header(config): """Add SuperClaude version to pytest header""" from . import __version__ return f"SuperClaude: {__version__}" def pytest_collection_modifyitems(config, items): """ Modify test collection to add automatic markers - Adds 'unit' marker to test files in tests/unit/ - Adds 'integration' marker to test files in tests/integration/ - Adds 'hallucination' marker to test files matching *hallucination* - Adds 'performance' marker to test files matching *performance* """ for item in items: test_path = str(item.fspath) # Auto-mark by directory if "/unit/" in test_path: item.add_marker(pytest.mark.unit) elif "/integration/" in test_path: item.add_marker(pytest.mark.integration) # Auto-mark by filename if "hallucination" in test_path: item.add_marker(pytest.mark.hallucination) elif "performance" in test_path or "benchmark" in test_path: item.add_marker(pytest.mark.performance)
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "src/superclaude/pytest_plugin.py", "license": "MIT License", "lines": 170, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
SuperClaude-Org/SuperClaude_Framework:scripts/ab_test_workflows.py
#!/usr/bin/env python3 """ A/B Testing Framework for Workflow Variants Compares two workflow variants with statistical significance testing. Usage: python scripts/ab_test_workflows.py \\ --variant-a progressive_v3_layer2 \\ --variant-b experimental_eager_layer3 \\ --metric tokens_used """ import argparse import json import statistics from pathlib import Path from typing import Dict, List, Tuple from scipy import stats class ABTestAnalyzer: """A/B testing framework for workflow optimization""" def __init__(self, metrics_file: Path): self.metrics_file = metrics_file self.metrics: List[Dict] = [] self._load_metrics() def _load_metrics(self): """Load metrics from JSONL file""" if not self.metrics_file.exists(): print(f"Error: {self.metrics_file} not found") return with open(self.metrics_file, 'r') as f: for line in f: if line.strip(): self.metrics.append(json.loads(line)) def get_variant_metrics(self, workflow_id: str) -> List[Dict]: """Get all metrics for a specific workflow variant""" return [m for m in self.metrics if m['workflow_id'] == workflow_id] def extract_metric_values(self, metrics: List[Dict], metric: str) -> List[float]: """Extract specific metric values from metrics list""" values = [] for m in metrics: if metric in m: value = m[metric] # Handle boolean metrics if isinstance(value, bool): value = 1.0 if value else 0.0 values.append(float(value)) return values def calculate_statistics(self, values: List[float]) -> Dict: """Calculate statistical measures""" if not values: return { 'count': 0, 'mean': 0, 'median': 0, 'stdev': 0, 'min': 0, 'max': 0 } return { 'count': len(values), 'mean': statistics.mean(values), 'median': statistics.median(values), 'stdev': statistics.stdev(values) if len(values) > 1 else 0, 'min': min(values), 'max': max(values) } def perform_ttest( self, variant_a_values: List[float], variant_b_values: List[float] ) -> Tuple[float, float]: """ Perform independent t-test between two variants. Returns: (t_statistic, p_value) """ if len(variant_a_values) < 2 or len(variant_b_values) < 2: return 0.0, 1.0 # Not enough data t_stat, p_value = stats.ttest_ind(variant_a_values, variant_b_values) return t_stat, p_value def determine_winner( self, variant_a_stats: Dict, variant_b_stats: Dict, p_value: float, metric: str, lower_is_better: bool = True ) -> str: """ Determine winning variant based on statistics. Args: variant_a_stats: Statistics for variant A variant_b_stats: Statistics for variant B p_value: Statistical significance (p-value) metric: Metric being compared lower_is_better: True if lower values are better (e.g., tokens_used) Returns: Winner description """ # Require statistical significance (p < 0.05) if p_value >= 0.05: return "No significant difference (p ≥ 0.05)" # Require minimum sample size (20 trials per variant) if variant_a_stats['count'] < 20 or variant_b_stats['count'] < 20: return f"Insufficient data (need 20 trials, have {variant_a_stats['count']}/{variant_b_stats['count']})" # Compare means a_mean = variant_a_stats['mean'] b_mean = variant_b_stats['mean'] if lower_is_better: if a_mean < b_mean: improvement = ((b_mean - a_mean) / b_mean) * 100 return f"Variant A wins ({improvement:.1f}% better)" else: improvement = ((a_mean - b_mean) / a_mean) * 100 return f"Variant B wins ({improvement:.1f}% better)" else: if a_mean > b_mean: improvement = ((a_mean - b_mean) / b_mean) * 100 return f"Variant A wins ({improvement:.1f}% better)" else: improvement = ((b_mean - a_mean) / a_mean) * 100 return f"Variant B wins ({improvement:.1f}% better)" def generate_recommendation( self, winner: str, variant_a_stats: Dict, variant_b_stats: Dict, p_value: float ) -> str: """Generate actionable recommendation""" if "No significant difference" in winner: return "⚖️ Keep current workflow (no improvement detected)" if "Insufficient data" in winner: return "📊 Continue testing (need more trials)" if "Variant A wins" in winner: return "✅ Keep Variant A as standard (statistically better)" if "Variant B wins" in winner: if variant_b_stats['mean'] > variant_a_stats['mean'] * 0.8: # At least 20% better return "🚀 Promote Variant B to standard (significant improvement)" else: return "⚠️ Marginal improvement - continue testing before promotion" return "🤔 Manual review recommended" def compare_variants( self, variant_a_id: str, variant_b_id: str, metric: str = 'tokens_used', lower_is_better: bool = True ) -> str: """ Compare two workflow variants on a specific metric. Args: variant_a_id: Workflow ID for variant A variant_b_id: Workflow ID for variant B metric: Metric to compare (default: tokens_used) lower_is_better: True if lower values are better Returns: Comparison report """ # Get metrics for each variant variant_a_metrics = self.get_variant_metrics(variant_a_id) variant_b_metrics = self.get_variant_metrics(variant_b_id) if not variant_a_metrics: return f"Error: No data for variant A ({variant_a_id})" if not variant_b_metrics: return f"Error: No data for variant B ({variant_b_id})" # Extract metric values a_values = self.extract_metric_values(variant_a_metrics, metric) b_values = self.extract_metric_values(variant_b_metrics, metric) # Calculate statistics a_stats = self.calculate_statistics(a_values) b_stats = self.calculate_statistics(b_values) # Perform t-test t_stat, p_value = self.perform_ttest(a_values, b_values) # Determine winner winner = self.determine_winner(a_stats, b_stats, p_value, metric, lower_is_better) # Generate recommendation recommendation = self.generate_recommendation(winner, a_stats, b_stats, p_value) # Format report report = [] report.append("=" * 80) report.append("A/B TEST COMPARISON REPORT") report.append("=" * 80) report.append("") report.append(f"Metric: {metric}") report.append(f"Better: {'Lower' if lower_is_better else 'Higher'} values") report.append("") report.append(f"## Variant A: {variant_a_id}") report.append(f" Trials: {a_stats['count']}") report.append(f" Mean: {a_stats['mean']:.2f}") report.append(f" Median: {a_stats['median']:.2f}") report.append(f" Std Dev: {a_stats['stdev']:.2f}") report.append(f" Range: {a_stats['min']:.2f} - {a_stats['max']:.2f}") report.append("") report.append(f"## Variant B: {variant_b_id}") report.append(f" Trials: {b_stats['count']}") report.append(f" Mean: {b_stats['mean']:.2f}") report.append(f" Median: {b_stats['median']:.2f}") report.append(f" Std Dev: {b_stats['stdev']:.2f}") report.append(f" Range: {b_stats['min']:.2f} - {b_stats['max']:.2f}") report.append("") report.append("## Statistical Significance") report.append(f" t-statistic: {t_stat:.4f}") report.append(f" p-value: {p_value:.4f}") if p_value < 0.01: report.append(" Significance: *** (p < 0.01) - Highly significant") elif p_value < 0.05: report.append(" Significance: ** (p < 0.05) - Significant") elif p_value < 0.10: report.append(" Significance: * (p < 0.10) - Marginally significant") else: report.append(" Significance: n.s. (p ≥ 0.10) - Not significant") report.append("") report.append(f"## Result: {winner}") report.append(f"## Recommendation: {recommendation}") report.append("") report.append("=" * 80) return "\n".join(report) def main(): parser = argparse.ArgumentParser(description="A/B test workflow variants") parser.add_argument( '--variant-a', required=True, help='Workflow ID for variant A' ) parser.add_argument( '--variant-b', required=True, help='Workflow ID for variant B' ) parser.add_argument( '--metric', default='tokens_used', help='Metric to compare (default: tokens_used)' ) parser.add_argument( '--higher-is-better', action='store_true', help='Higher values are better (default: lower is better)' ) parser.add_argument( '--output', help='Output file (default: stdout)' ) args = parser.parse_args() # Find metrics file metrics_file = Path('docs/memory/workflow_metrics.jsonl') analyzer = ABTestAnalyzer(metrics_file) report = analyzer.compare_variants( args.variant_a, args.variant_b, args.metric, lower_is_better=not args.higher_is_better ) if args.output: with open(args.output, 'w') as f: f.write(report) print(f"Report written to {args.output}") else: print(report) if __name__ == '__main__': main()
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "scripts/ab_test_workflows.py", "license": "MIT License", "lines": 260, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
SuperClaude-Org/SuperClaude_Framework:scripts/analyze_workflow_metrics.py
#!/usr/bin/env python3 """ Workflow Metrics Analysis Script Analyzes workflow_metrics.jsonl for continuous optimization and A/B testing. Usage: python scripts/analyze_workflow_metrics.py --period week python scripts/analyze_workflow_metrics.py --period month python scripts/analyze_workflow_metrics.py --task-type bug_fix """ import argparse import json import statistics from collections import defaultdict from datetime import datetime, timedelta from pathlib import Path from typing import Dict, List class WorkflowMetricsAnalyzer: """Analyze workflow metrics for optimization""" def __init__(self, metrics_file: Path): self.metrics_file = metrics_file self.metrics: List[Dict] = [] self._load_metrics() def _load_metrics(self): """Load metrics from JSONL file""" if not self.metrics_file.exists(): print(f"Warning: {self.metrics_file} not found") return with open(self.metrics_file, 'r') as f: for line in f: if line.strip(): self.metrics.append(json.loads(line)) print(f"Loaded {len(self.metrics)} metric records") def filter_by_period(self, period: str) -> List[Dict]: """Filter metrics by time period""" now = datetime.now() if period == "week": cutoff = now - timedelta(days=7) elif period == "month": cutoff = now - timedelta(days=30) elif period == "all": return self.metrics else: raise ValueError(f"Invalid period: {period}") filtered = [ m for m in self.metrics if datetime.fromisoformat(m['timestamp']) >= cutoff ] print(f"Filtered to {len(filtered)} records in last {period}") return filtered def analyze_by_task_type(self, metrics: List[Dict]) -> Dict: """Analyze metrics grouped by task type""" by_task = defaultdict(list) for m in metrics: by_task[m['task_type']].append(m) results = {} for task_type, task_metrics in by_task.items(): results[task_type] = { 'count': len(task_metrics), 'avg_tokens': statistics.mean(m['tokens_used'] for m in task_metrics), 'avg_time_ms': statistics.mean(m['time_ms'] for m in task_metrics), 'success_rate': sum(m['success'] for m in task_metrics) / len(task_metrics) * 100, 'avg_files_read': statistics.mean(m.get('files_read', 0) for m in task_metrics), } return results def analyze_by_complexity(self, metrics: List[Dict]) -> Dict: """Analyze metrics grouped by complexity level""" by_complexity = defaultdict(list) for m in metrics: by_complexity[m['complexity']].append(m) results = {} for complexity, comp_metrics in by_complexity.items(): results[complexity] = { 'count': len(comp_metrics), 'avg_tokens': statistics.mean(m['tokens_used'] for m in comp_metrics), 'avg_time_ms': statistics.mean(m['time_ms'] for m in comp_metrics), 'success_rate': sum(m['success'] for m in comp_metrics) / len(comp_metrics) * 100, } return results def analyze_by_workflow(self, metrics: List[Dict]) -> Dict: """Analyze metrics grouped by workflow variant""" by_workflow = defaultdict(list) for m in metrics: by_workflow[m['workflow_id']].append(m) results = {} for workflow_id, wf_metrics in by_workflow.items(): results[workflow_id] = { 'count': len(wf_metrics), 'avg_tokens': statistics.mean(m['tokens_used'] for m in wf_metrics), 'median_tokens': statistics.median(m['tokens_used'] for m in wf_metrics), 'avg_time_ms': statistics.mean(m['time_ms'] for m in wf_metrics), 'success_rate': sum(m['success'] for m in wf_metrics) / len(wf_metrics) * 100, } return results def identify_best_workflows(self, metrics: List[Dict]) -> Dict[str, str]: """Identify best workflow for each task type""" by_task_workflow = defaultdict(lambda: defaultdict(list)) for m in metrics: by_task_workflow[m['task_type']][m['workflow_id']].append(m) best_workflows = {} for task_type, workflows in by_task_workflow.items(): best_workflow = None best_score = float('inf') for workflow_id, wf_metrics in workflows.items(): # Score = avg_tokens (lower is better) avg_tokens = statistics.mean(m['tokens_used'] for m in wf_metrics) success_rate = sum(m['success'] for m in wf_metrics) / len(wf_metrics) # Only consider if success rate >= 95% if success_rate >= 0.95: if avg_tokens < best_score: best_score = avg_tokens best_workflow = workflow_id if best_workflow: best_workflows[task_type] = best_workflow return best_workflows def identify_inefficiencies(self, metrics: List[Dict]) -> List[Dict]: """Identify inefficient patterns""" inefficiencies = [] # Expected token budgets by complexity budgets = { 'ultra-light': 800, 'light': 2000, 'medium': 5000, 'heavy': 20000, 'ultra-heavy': 50000 } for m in metrics: issues = [] # Check token budget overrun expected_budget = budgets.get(m['complexity'], 5000) if m['tokens_used'] > expected_budget * 1.3: # 30% over budget issues.append(f"Token overrun: {m['tokens_used']} vs {expected_budget}") # Check success rate if not m['success']: issues.append("Task failed") # Check time performance (light tasks should be fast) if m['complexity'] in ['ultra-light', 'light'] and m['time_ms'] > 10000: issues.append(f"Slow execution: {m['time_ms']}ms for {m['complexity']} task") if issues: inefficiencies.append({ 'timestamp': m['timestamp'], 'task_type': m['task_type'], 'complexity': m['complexity'], 'workflow_id': m['workflow_id'], 'issues': issues }) return inefficiencies def calculate_token_savings(self, metrics: List[Dict]) -> Dict: """Calculate token savings vs unlimited baseline""" # Unlimited baseline estimates baseline = { 'ultra-light': 1000, 'light': 2500, 'medium': 7500, 'heavy': 30000, 'ultra-heavy': 100000 } total_actual = 0 total_baseline = 0 for m in metrics: total_actual += m['tokens_used'] total_baseline += baseline.get(m['complexity'], 7500) savings = total_baseline - total_actual savings_percent = (savings / total_baseline * 100) if total_baseline > 0 else 0 return { 'total_actual': total_actual, 'total_baseline': total_baseline, 'total_savings': savings, 'savings_percent': savings_percent } def generate_report(self, period: str) -> str: """Generate comprehensive analysis report""" metrics = self.filter_by_period(period) if not metrics: return "No metrics available for analysis" report = [] report.append("=" * 80) report.append(f"WORKFLOW METRICS ANALYSIS REPORT - Last {period}") report.append("=" * 80) report.append("") # Overall statistics report.append("## Overall Statistics") report.append(f"Total Tasks: {len(metrics)}") report.append(f"Success Rate: {sum(m['success'] for m in metrics) / len(metrics) * 100:.1f}%") report.append(f"Avg Tokens: {statistics.mean(m['tokens_used'] for m in metrics):.0f}") report.append(f"Avg Time: {statistics.mean(m['time_ms'] for m in metrics):.0f}ms") report.append("") # Token savings savings = self.calculate_token_savings(metrics) report.append("## Token Efficiency") report.append(f"Actual Usage: {savings['total_actual']:,} tokens") report.append(f"Unlimited Baseline: {savings['total_baseline']:,} tokens") report.append(f"Total Savings: {savings['total_savings']:,} tokens ({savings['savings_percent']:.1f}%)") report.append("") # By task type report.append("## Analysis by Task Type") by_task = self.analyze_by_task_type(metrics) for task_type, stats in sorted(by_task.items()): report.append(f"\n### {task_type}") report.append(f" Count: {stats['count']}") report.append(f" Avg Tokens: {stats['avg_tokens']:.0f}") report.append(f" Avg Time: {stats['avg_time_ms']:.0f}ms") report.append(f" Success Rate: {stats['success_rate']:.1f}%") report.append(f" Avg Files Read: {stats['avg_files_read']:.1f}") report.append("") # By complexity report.append("## Analysis by Complexity") by_complexity = self.analyze_by_complexity(metrics) for complexity in ['ultra-light', 'light', 'medium', 'heavy', 'ultra-heavy']: if complexity in by_complexity: stats = by_complexity[complexity] report.append(f"\n### {complexity}") report.append(f" Count: {stats['count']}") report.append(f" Avg Tokens: {stats['avg_tokens']:.0f}") report.append(f" Success Rate: {stats['success_rate']:.1f}%") report.append("") # Best workflows report.append("## Best Workflows per Task Type") best = self.identify_best_workflows(metrics) for task_type, workflow_id in sorted(best.items()): report.append(f" {task_type}: {workflow_id}") report.append("") # Inefficiencies inefficiencies = self.identify_inefficiencies(metrics) if inefficiencies: report.append("## Inefficiencies Detected") report.append(f"Total Issues: {len(inefficiencies)}") for issue in inefficiencies[:5]: # Show top 5 report.append(f"\n {issue['timestamp']}") report.append(f" Task: {issue['task_type']} ({issue['complexity']})") report.append(f" Workflow: {issue['workflow_id']}") for problem in issue['issues']: report.append(f" - {problem}") report.append("") report.append("=" * 80) return "\n".join(report) def main(): parser = argparse.ArgumentParser(description="Analyze workflow metrics") parser.add_argument( '--period', choices=['week', 'month', 'all'], default='week', help='Analysis time period' ) parser.add_argument( '--task-type', help='Filter by specific task type' ) parser.add_argument( '--output', help='Output file (default: stdout)' ) args = parser.parse_args() # Find metrics file metrics_file = Path('docs/memory/workflow_metrics.jsonl') analyzer = WorkflowMetricsAnalyzer(metrics_file) report = analyzer.generate_report(args.period) if args.output: with open(args.output, 'w') as f: f.write(report) print(f"Report written to {args.output}") else: print(report) if __name__ == '__main__': main()
{ "repo_id": "SuperClaude-Org/SuperClaude_Framework", "file_path": "scripts/analyze_workflow_metrics.py", "license": "MIT License", "lines": 264, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:cli/announcements.py
import getpass import requests from rich.console import Console from rich.panel import Panel from cli.config import CLI_CONFIG def fetch_announcements(url: str = None, timeout: float = None) -> dict: """Fetch announcements from endpoint. Returns dict with announcements and settings.""" endpoint = url or CLI_CONFIG["announcements_url"] timeout = timeout or CLI_CONFIG["announcements_timeout"] fallback = CLI_CONFIG["announcements_fallback"] try: response = requests.get(endpoint, timeout=timeout) response.raise_for_status() data = response.json() return { "announcements": data.get("announcements", [fallback]), "require_attention": data.get("require_attention", False), } except Exception: return { "announcements": [fallback], "require_attention": False, } def display_announcements(console: Console, data: dict) -> None: """Display announcements panel. Prompts for Enter if require_attention is True.""" announcements = data.get("announcements", []) require_attention = data.get("require_attention", False) if not announcements: return content = "\n".join(announcements) panel = Panel( content, border_style="cyan", padding=(1, 2), title="Announcements", ) console.print(panel) if require_attention: getpass.getpass("Press Enter to continue...") else: console.print()
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "cli/announcements.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:cli/config.py
CLI_CONFIG = { # Announcements "announcements_url": "https://api.tauric.ai/v1/announcements", "announcements_timeout": 1.0, "announcements_fallback": "[cyan]For more information, please visit[/cyan] [link=https://github.com/TauricResearch]https://github.com/TauricResearch[/link]", }
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "cli/config.py", "license": "Apache License 2.0", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:cli/stats_handler.py
import threading from typing import Any, Dict, List, Union from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_core.messages import AIMessage class StatsCallbackHandler(BaseCallbackHandler): """Callback handler that tracks LLM calls, tool calls, and token usage.""" def __init__(self) -> None: super().__init__() self._lock = threading.Lock() self.llm_calls = 0 self.tool_calls = 0 self.tokens_in = 0 self.tokens_out = 0 def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any, ) -> None: """Increment LLM call counter when an LLM starts.""" with self._lock: self.llm_calls += 1 def on_chat_model_start( self, serialized: Dict[str, Any], messages: List[List[Any]], **kwargs: Any, ) -> None: """Increment LLM call counter when a chat model starts.""" with self._lock: self.llm_calls += 1 def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Extract token usage from LLM response.""" try: generation = response.generations[0][0] except (IndexError, TypeError): return usage_metadata = None if hasattr(generation, "message"): message = generation.message if isinstance(message, AIMessage) and hasattr(message, "usage_metadata"): usage_metadata = message.usage_metadata if usage_metadata: with self._lock: self.tokens_in += usage_metadata.get("input_tokens", 0) self.tokens_out += usage_metadata.get("output_tokens", 0) def on_tool_start( self, serialized: Dict[str, Any], input_str: str, **kwargs: Any, ) -> None: """Increment tool call counter when a tool starts.""" with self._lock: self.tool_calls += 1 def get_stats(self) -> Dict[str, Any]: """Return current statistics.""" with self._lock: return { "llm_calls": self.llm_calls, "tool_calls": self.tool_calls, "tokens_in": self.tokens_in, "tokens_out": self.tokens_out, }
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "cli/stats_handler.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/dataflows/yfinance_news.py
"""yfinance-based news data fetching functions.""" import yfinance as yf from datetime import datetime from dateutil.relativedelta import relativedelta def _extract_article_data(article: dict) -> dict: """Extract article data from yfinance news format (handles nested 'content' structure).""" # Handle nested content structure if "content" in article: content = article["content"] title = content.get("title", "No title") summary = content.get("summary", "") provider = content.get("provider", {}) publisher = provider.get("displayName", "Unknown") # Get URL from canonicalUrl or clickThroughUrl url_obj = content.get("canonicalUrl") or content.get("clickThroughUrl") or {} link = url_obj.get("url", "") # Get publish date pub_date_str = content.get("pubDate", "") pub_date = None if pub_date_str: try: pub_date = datetime.fromisoformat(pub_date_str.replace("Z", "+00:00")) except (ValueError, AttributeError): pass return { "title": title, "summary": summary, "publisher": publisher, "link": link, "pub_date": pub_date, } else: # Fallback for flat structure return { "title": article.get("title", "No title"), "summary": article.get("summary", ""), "publisher": article.get("publisher", "Unknown"), "link": article.get("link", ""), "pub_date": None, } def get_news_yfinance( ticker: str, start_date: str, end_date: str, ) -> str: """ Retrieve news for a specific stock ticker using yfinance. Args: ticker: Stock ticker symbol (e.g., "AAPL") start_date: Start date in yyyy-mm-dd format end_date: End date in yyyy-mm-dd format Returns: Formatted string containing news articles """ try: stock = yf.Ticker(ticker) news = stock.get_news(count=20) if not news: return f"No news found for {ticker}" # Parse date range for filtering start_dt = datetime.strptime(start_date, "%Y-%m-%d") end_dt = datetime.strptime(end_date, "%Y-%m-%d") news_str = "" filtered_count = 0 for article in news: data = _extract_article_data(article) # Filter by date if publish time is available if data["pub_date"]: pub_date_naive = data["pub_date"].replace(tzinfo=None) if not (start_dt <= pub_date_naive <= end_dt + relativedelta(days=1)): continue news_str += f"### {data['title']} (source: {data['publisher']})\n" if data["summary"]: news_str += f"{data['summary']}\n" if data["link"]: news_str += f"Link: {data['link']}\n" news_str += "\n" filtered_count += 1 if filtered_count == 0: return f"No news found for {ticker} between {start_date} and {end_date}" return f"## {ticker} News, from {start_date} to {end_date}:\n\n{news_str}" except Exception as e: return f"Error fetching news for {ticker}: {str(e)}" def get_global_news_yfinance( curr_date: str, look_back_days: int = 7, limit: int = 10, ) -> str: """ Retrieve global/macro economic news using yfinance Search. Args: curr_date: Current date in yyyy-mm-dd format look_back_days: Number of days to look back limit: Maximum number of articles to return Returns: Formatted string containing global news articles """ # Search queries for macro/global news search_queries = [ "stock market economy", "Federal Reserve interest rates", "inflation economic outlook", "global markets trading", ] all_news = [] seen_titles = set() try: for query in search_queries: search = yf.Search( query=query, news_count=limit, enable_fuzzy_query=True, ) if search.news: for article in search.news: # Handle both flat and nested structures if "content" in article: data = _extract_article_data(article) title = data["title"] else: title = article.get("title", "") # Deduplicate by title if title and title not in seen_titles: seen_titles.add(title) all_news.append(article) if len(all_news) >= limit: break if not all_news: return f"No global news found for {curr_date}" # Calculate date range curr_dt = datetime.strptime(curr_date, "%Y-%m-%d") start_dt = curr_dt - relativedelta(days=look_back_days) start_date = start_dt.strftime("%Y-%m-%d") news_str = "" for article in all_news[:limit]: # Handle both flat and nested structures if "content" in article: data = _extract_article_data(article) title = data["title"] publisher = data["publisher"] link = data["link"] summary = data["summary"] else: title = article.get("title", "No title") publisher = article.get("publisher", "Unknown") link = article.get("link", "") summary = "" news_str += f"### {title} (source: {publisher})\n" if summary: news_str += f"{summary}\n" if link: news_str += f"Link: {link}\n" news_str += "\n" return f"## Global Market News, from {start_date} to {curr_date}:\n\n{news_str}" except Exception as e: return f"Error fetching global news: {str(e)}"
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/yfinance_news.py", "license": "Apache License 2.0", "lines": 156, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/llm_clients/anthropic_client.py
from typing import Any, Optional from langchain_anthropic import ChatAnthropic from .base_client import BaseLLMClient from .validators import validate_model class AnthropicClient(BaseLLMClient): """Client for Anthropic Claude models.""" def __init__(self, model: str, base_url: Optional[str] = None, **kwargs): super().__init__(model, base_url, **kwargs) def get_llm(self) -> Any: """Return configured ChatAnthropic instance.""" llm_kwargs = {"model": self.model} for key in ("timeout", "max_retries", "api_key", "max_tokens", "callbacks"): if key in self.kwargs: llm_kwargs[key] = self.kwargs[key] return ChatAnthropic(**llm_kwargs) def validate_model(self) -> bool: """Validate model for Anthropic.""" return validate_model("anthropic", self.model)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/llm_clients/anthropic_client.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/llm_clients/base_client.py
from abc import ABC, abstractmethod from typing import Any, Optional class BaseLLMClient(ABC): """Abstract base class for LLM clients.""" def __init__(self, model: str, base_url: Optional[str] = None, **kwargs): self.model = model self.base_url = base_url self.kwargs = kwargs @abstractmethod def get_llm(self) -> Any: """Return the configured LLM instance.""" pass @abstractmethod def validate_model(self) -> bool: """Validate that the model is supported by this client.""" pass
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/llm_clients/base_client.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/llm_clients/factory.py
from typing import Optional from .base_client import BaseLLMClient from .openai_client import OpenAIClient from .anthropic_client import AnthropicClient from .google_client import GoogleClient def create_llm_client( provider: str, model: str, base_url: Optional[str] = None, **kwargs, ) -> BaseLLMClient: """Create an LLM client for the specified provider. Args: provider: LLM provider (openai, anthropic, google, xai, ollama, openrouter) model: Model name/identifier base_url: Optional base URL for API endpoint **kwargs: Additional provider-specific arguments Returns: Configured BaseLLMClient instance Raises: ValueError: If provider is not supported """ provider_lower = provider.lower() if provider_lower in ("openai", "ollama", "openrouter"): return OpenAIClient(model, base_url, provider=provider_lower, **kwargs) if provider_lower == "xai": return OpenAIClient(model, base_url, provider="xai", **kwargs) if provider_lower == "anthropic": return AnthropicClient(model, base_url, **kwargs) if provider_lower == "google": return GoogleClient(model, base_url, **kwargs) raise ValueError(f"Unsupported LLM provider: {provider}")
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/llm_clients/factory.py", "license": "Apache License 2.0", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/llm_clients/google_client.py
from typing import Any, Optional from langchain_google_genai import ChatGoogleGenerativeAI from .base_client import BaseLLMClient from .validators import validate_model class NormalizedChatGoogleGenerativeAI(ChatGoogleGenerativeAI): """ChatGoogleGenerativeAI with normalized content output. Gemini 3 models return content as list: [{'type': 'text', 'text': '...'}] This normalizes to string for consistent downstream handling. """ def _normalize_content(self, response): content = response.content if isinstance(content, list): texts = [ item.get("text", "") if isinstance(item, dict) and item.get("type") == "text" else item if isinstance(item, str) else "" for item in content ] response.content = "\n".join(t for t in texts if t) return response def invoke(self, input, config=None, **kwargs): return self._normalize_content(super().invoke(input, config, **kwargs)) class GoogleClient(BaseLLMClient): """Client for Google Gemini models.""" def __init__(self, model: str, base_url: Optional[str] = None, **kwargs): super().__init__(model, base_url, **kwargs) def get_llm(self) -> Any: """Return configured ChatGoogleGenerativeAI instance.""" llm_kwargs = {"model": self.model} for key in ("timeout", "max_retries", "google_api_key", "callbacks"): if key in self.kwargs: llm_kwargs[key] = self.kwargs[key] # Map thinking_level to appropriate API param based on model # Gemini 3 Pro: low, high # Gemini 3 Flash: minimal, low, medium, high # Gemini 2.5: thinking_budget (0=disable, -1=dynamic) thinking_level = self.kwargs.get("thinking_level") if thinking_level: model_lower = self.model.lower() if "gemini-3" in model_lower: # Gemini 3 Pro doesn't support "minimal", use "low" instead if "pro" in model_lower and thinking_level == "minimal": thinking_level = "low" llm_kwargs["thinking_level"] = thinking_level else: # Gemini 2.5: map to thinking_budget llm_kwargs["thinking_budget"] = -1 if thinking_level == "high" else 0 return NormalizedChatGoogleGenerativeAI(**llm_kwargs) def validate_model(self) -> bool: """Validate model for Google.""" return validate_model("google", self.model)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/llm_clients/google_client.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/llm_clients/openai_client.py
import os from typing import Any, Optional from langchain_openai import ChatOpenAI from .base_client import BaseLLMClient from .validators import validate_model class UnifiedChatOpenAI(ChatOpenAI): """ChatOpenAI subclass that strips incompatible params for certain models.""" def __init__(self, **kwargs): model = kwargs.get("model", "") if self._is_reasoning_model(model): kwargs.pop("temperature", None) kwargs.pop("top_p", None) super().__init__(**kwargs) @staticmethod def _is_reasoning_model(model: str) -> bool: """Check if model is a reasoning model that doesn't support temperature.""" model_lower = model.lower() return ( model_lower.startswith("o1") or model_lower.startswith("o3") or "gpt-5" in model_lower ) class OpenAIClient(BaseLLMClient): """Client for OpenAI, Ollama, OpenRouter, and xAI providers.""" def __init__( self, model: str, base_url: Optional[str] = None, provider: str = "openai", **kwargs, ): super().__init__(model, base_url, **kwargs) self.provider = provider.lower() def get_llm(self) -> Any: """Return configured ChatOpenAI instance.""" llm_kwargs = {"model": self.model} if self.provider == "xai": llm_kwargs["base_url"] = "https://api.x.ai/v1" api_key = os.environ.get("XAI_API_KEY") if api_key: llm_kwargs["api_key"] = api_key elif self.provider == "openrouter": llm_kwargs["base_url"] = "https://openrouter.ai/api/v1" api_key = os.environ.get("OPENROUTER_API_KEY") if api_key: llm_kwargs["api_key"] = api_key elif self.provider == "ollama": llm_kwargs["base_url"] = "http://localhost:11434/v1" llm_kwargs["api_key"] = "ollama" # Ollama doesn't require auth elif self.base_url: llm_kwargs["base_url"] = self.base_url for key in ("timeout", "max_retries", "reasoning_effort", "api_key", "callbacks"): if key in self.kwargs: llm_kwargs[key] = self.kwargs[key] return UnifiedChatOpenAI(**llm_kwargs) def validate_model(self) -> bool: """Validate model for the provider.""" return validate_model(self.provider, self.model)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/llm_clients/openai_client.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/llm_clients/validators.py
"""Model name validators for each provider. Only validates model names - does NOT enforce limits. Let LLM providers use their own defaults for unspecified params. """ VALID_MODELS = { "openai": [ # GPT-5 series (2025) "gpt-5.2", "gpt-5.1", "gpt-5", "gpt-5-mini", "gpt-5-nano", # GPT-4.1 series (2025) "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", # o-series reasoning models "o4-mini", "o3", "o3-mini", "o1", "o1-preview", # GPT-4o series (legacy but still supported) "gpt-4o", "gpt-4o-mini", ], "anthropic": [ # Claude 4.5 series (2025) "claude-opus-4-5", "claude-sonnet-4-5", "claude-haiku-4-5", # Claude 4.x series "claude-opus-4-1-20250805", "claude-sonnet-4-20250514", # Claude 3.7 series "claude-3-7-sonnet-20250219", # Claude 3.5 series (legacy) "claude-3-5-haiku-20241022", "claude-3-5-sonnet-20241022", ], "google": [ # Gemini 3 series (preview) "gemini-3-pro-preview", "gemini-3-flash-preview", # Gemini 2.5 series "gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.5-flash-lite", # Gemini 2.0 series "gemini-2.0-flash", "gemini-2.0-flash-lite", ], "xai": [ # Grok 4.1 series "grok-4-1-fast", "grok-4-1-fast-reasoning", "grok-4-1-fast-non-reasoning", # Grok 4 series "grok-4", "grok-4-0709", "grok-4-fast-reasoning", "grok-4-fast-non-reasoning", ], } def validate_model(provider: str, model: str) -> bool: """Check if model name is valid for the given provider. For ollama, openrouter - any model is accepted. """ provider_lower = provider.lower() if provider_lower in ("ollama", "openrouter"): return True if provider_lower not in VALID_MODELS: return True return model in VALID_MODELS[provider_lower]
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/llm_clients/validators.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:test.py
import time from tradingagents.dataflows.y_finance import get_YFin_data_online, get_stock_stats_indicators_window, get_balance_sheet as get_yfinance_balance_sheet, get_cashflow as get_yfinance_cashflow, get_income_statement as get_yfinance_income_statement, get_insider_transactions as get_yfinance_insider_transactions print("Testing optimized implementation with 30-day lookback:") start_time = time.time() result = get_stock_stats_indicators_window("AAPL", "macd", "2024-11-01", 30) end_time = time.time() print(f"Execution time: {end_time - start_time:.2f} seconds") print(f"Result length: {len(result)} characters") print(result)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "test.py", "license": "Apache License 2.0", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/utils/core_stock_tools.py
from langchain_core.tools import tool from typing import Annotated from tradingagents.dataflows.interface import route_to_vendor @tool def get_stock_data( symbol: Annotated[str, "ticker symbol of the company"], start_date: Annotated[str, "Start date in yyyy-mm-dd format"], end_date: Annotated[str, "End date in yyyy-mm-dd format"], ) -> str: """ Retrieve stock price data (OHLCV) for a given ticker symbol. Uses the configured core_stock_apis vendor. Args: symbol (str): Ticker symbol of the company, e.g. AAPL, TSM start_date (str): Start date in yyyy-mm-dd format end_date (str): End date in yyyy-mm-dd format Returns: str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range. """ return route_to_vendor("get_stock_data", symbol, start_date, end_date)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/utils/core_stock_tools.py", "license": "Apache License 2.0", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TauricResearch/TradingAgents:tradingagents/agents/utils/fundamental_data_tools.py
from langchain_core.tools import tool from typing import Annotated from tradingagents.dataflows.interface import route_to_vendor @tool def get_fundamentals( ticker: Annotated[str, "ticker symbol"], curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"], ) -> str: """ Retrieve comprehensive fundamental data for a given ticker symbol. Uses the configured fundamental_data vendor. Args: ticker (str): Ticker symbol of the company curr_date (str): Current date you are trading at, yyyy-mm-dd Returns: str: A formatted report containing comprehensive fundamental data """ return route_to_vendor("get_fundamentals", ticker, curr_date) @tool def get_balance_sheet( ticker: Annotated[str, "ticker symbol"], freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly", curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None, ) -> str: """ Retrieve balance sheet data for a given ticker symbol. Uses the configured fundamental_data vendor. Args: ticker (str): Ticker symbol of the company freq (str): Reporting frequency: annual/quarterly (default quarterly) curr_date (str): Current date you are trading at, yyyy-mm-dd Returns: str: A formatted report containing balance sheet data """ return route_to_vendor("get_balance_sheet", ticker, freq, curr_date) @tool def get_cashflow( ticker: Annotated[str, "ticker symbol"], freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly", curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None, ) -> str: """ Retrieve cash flow statement data for a given ticker symbol. Uses the configured fundamental_data vendor. Args: ticker (str): Ticker symbol of the company freq (str): Reporting frequency: annual/quarterly (default quarterly) curr_date (str): Current date you are trading at, yyyy-mm-dd Returns: str: A formatted report containing cash flow statement data """ return route_to_vendor("get_cashflow", ticker, freq, curr_date) @tool def get_income_statement( ticker: Annotated[str, "ticker symbol"], freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly", curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None, ) -> str: """ Retrieve income statement data for a given ticker symbol. Uses the configured fundamental_data vendor. Args: ticker (str): Ticker symbol of the company freq (str): Reporting frequency: annual/quarterly (default quarterly) curr_date (str): Current date you are trading at, yyyy-mm-dd Returns: str: A formatted report containing income statement data """ return route_to_vendor("get_income_statement", ticker, freq, curr_date)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/utils/fundamental_data_tools.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TauricResearch/TradingAgents:tradingagents/agents/utils/news_data_tools.py
from langchain_core.tools import tool from typing import Annotated from tradingagents.dataflows.interface import route_to_vendor @tool def get_news( ticker: Annotated[str, "Ticker symbol"], start_date: Annotated[str, "Start date in yyyy-mm-dd format"], end_date: Annotated[str, "End date in yyyy-mm-dd format"], ) -> str: """ Retrieve news data for a given ticker symbol. Uses the configured news_data vendor. Args: ticker (str): Ticker symbol start_date (str): Start date in yyyy-mm-dd format end_date (str): End date in yyyy-mm-dd format Returns: str: A formatted string containing news data """ return route_to_vendor("get_news", ticker, start_date, end_date) @tool def get_global_news( curr_date: Annotated[str, "Current date in yyyy-mm-dd format"], look_back_days: Annotated[int, "Number of days to look back"] = 7, limit: Annotated[int, "Maximum number of articles to return"] = 5, ) -> str: """ Retrieve global news data. Uses the configured news_data vendor. Args: curr_date (str): Current date in yyyy-mm-dd format look_back_days (int): Number of days to look back (default 7) limit (int): Maximum number of articles to return (default 5) Returns: str: A formatted string containing global news data """ return route_to_vendor("get_global_news", curr_date, look_back_days, limit) @tool def get_insider_transactions( ticker: Annotated[str, "ticker symbol"], ) -> str: """ Retrieve insider transaction information about a company. Uses the configured news_data vendor. Args: ticker (str): Ticker symbol of the company Returns: str: A report of insider transaction data """ return route_to_vendor("get_insider_transactions", ticker)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/utils/news_data_tools.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TauricResearch/TradingAgents:tradingagents/agents/utils/technical_indicators_tools.py
from langchain_core.tools import tool from typing import Annotated from tradingagents.dataflows.interface import route_to_vendor @tool def get_indicators( symbol: Annotated[str, "ticker symbol of the company"], indicator: Annotated[str, "technical indicator to get the analysis and report of"], curr_date: Annotated[str, "The current trading date you are trading on, YYYY-mm-dd"], look_back_days: Annotated[int, "how many days to look back"] = 30, ) -> str: """ Retrieve technical indicators for a given ticker symbol. Uses the configured technical_indicators vendor. Args: symbol (str): Ticker symbol of the company, e.g. AAPL, TSM indicator (str): Technical indicator to get the analysis and report of curr_date (str): The current trading date you are trading on, YYYY-mm-dd look_back_days (int): How many days to look back, default is 30 Returns: str: A formatted dataframe containing the technical indicators for the specified ticker symbol and indicator. """ return route_to_vendor("get_indicators", symbol, indicator, curr_date, look_back_days)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/utils/technical_indicators_tools.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TauricResearch/TradingAgents:tradingagents/dataflows/alpha_vantage.py
# Import functions from specialized modules from .alpha_vantage_stock import get_stock from .alpha_vantage_indicator import get_indicator from .alpha_vantage_fundamentals import get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement from .alpha_vantage_news import get_news, get_global_news, get_insider_transactions
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/alpha_vantage.py", "license": "Apache License 2.0", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/dataflows/alpha_vantage_common.py
import os import requests import pandas as pd import json from datetime import datetime from io import StringIO API_BASE_URL = "https://www.alphavantage.co/query" def get_api_key() -> str: """Retrieve the API key for Alpha Vantage from environment variables.""" api_key = os.getenv("ALPHA_VANTAGE_API_KEY") if not api_key: raise ValueError("ALPHA_VANTAGE_API_KEY environment variable is not set.") return api_key def format_datetime_for_api(date_input) -> str: """Convert various date formats to YYYYMMDDTHHMM format required by Alpha Vantage API.""" if isinstance(date_input, str): # If already in correct format, return as-is if len(date_input) == 13 and 'T' in date_input: return date_input # Try to parse common date formats try: dt = datetime.strptime(date_input, "%Y-%m-%d") return dt.strftime("%Y%m%dT0000") except ValueError: try: dt = datetime.strptime(date_input, "%Y-%m-%d %H:%M") return dt.strftime("%Y%m%dT%H%M") except ValueError: raise ValueError(f"Unsupported date format: {date_input}") elif isinstance(date_input, datetime): return date_input.strftime("%Y%m%dT%H%M") else: raise ValueError(f"Date must be string or datetime object, got {type(date_input)}") class AlphaVantageRateLimitError(Exception): """Exception raised when Alpha Vantage API rate limit is exceeded.""" pass def _make_api_request(function_name: str, params: dict) -> dict | str: """Helper function to make API requests and handle responses. Raises: AlphaVantageRateLimitError: When API rate limit is exceeded """ # Create a copy of params to avoid modifying the original api_params = params.copy() api_params.update({ "function": function_name, "apikey": get_api_key(), "source": "trading_agents", }) # Handle entitlement parameter if present in params or global variable current_entitlement = globals().get('_current_entitlement') entitlement = api_params.get("entitlement") or current_entitlement if entitlement: api_params["entitlement"] = entitlement elif "entitlement" in api_params: # Remove entitlement if it's None or empty api_params.pop("entitlement", None) response = requests.get(API_BASE_URL, params=api_params) response.raise_for_status() response_text = response.text # Check if response is JSON (error responses are typically JSON) try: response_json = json.loads(response_text) # Check for rate limit error if "Information" in response_json: info_message = response_json["Information"] if "rate limit" in info_message.lower() or "api key" in info_message.lower(): raise AlphaVantageRateLimitError(f"Alpha Vantage rate limit exceeded: {info_message}") except json.JSONDecodeError: # Response is not JSON (likely CSV data), which is normal pass return response_text def _filter_csv_by_date_range(csv_data: str, start_date: str, end_date: str) -> str: """ Filter CSV data to include only rows within the specified date range. Args: csv_data: CSV string from Alpha Vantage API start_date: Start date in yyyy-mm-dd format end_date: End date in yyyy-mm-dd format Returns: Filtered CSV string """ if not csv_data or csv_data.strip() == "": return csv_data try: # Parse CSV data df = pd.read_csv(StringIO(csv_data)) # Assume the first column is the date column (timestamp) date_col = df.columns[0] df[date_col] = pd.to_datetime(df[date_col]) # Filter by date range start_dt = pd.to_datetime(start_date) end_dt = pd.to_datetime(end_date) filtered_df = df[(df[date_col] >= start_dt) & (df[date_col] <= end_dt)] # Convert back to CSV string return filtered_df.to_csv(index=False) except Exception as e: # If filtering fails, return original data with a warning print(f"Warning: Failed to filter CSV data by date range: {e}") return csv_data
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/alpha_vantage_common.py", "license": "Apache License 2.0", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/dataflows/alpha_vantage_fundamentals.py
from .alpha_vantage_common import _make_api_request def get_fundamentals(ticker: str, curr_date: str = None) -> str: """ Retrieve comprehensive fundamental data for a given ticker symbol using Alpha Vantage. Args: ticker (str): Ticker symbol of the company curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage) Returns: str: Company overview data including financial ratios and key metrics """ params = { "symbol": ticker, } return _make_api_request("OVERVIEW", params) def get_balance_sheet(ticker: str, freq: str = "quarterly", curr_date: str = None) -> str: """ Retrieve balance sheet data for a given ticker symbol using Alpha Vantage. Args: ticker (str): Ticker symbol of the company freq (str): Reporting frequency: annual/quarterly (default quarterly) - not used for Alpha Vantage curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage) Returns: str: Balance sheet data with normalized fields """ params = { "symbol": ticker, } return _make_api_request("BALANCE_SHEET", params) def get_cashflow(ticker: str, freq: str = "quarterly", curr_date: str = None) -> str: """ Retrieve cash flow statement data for a given ticker symbol using Alpha Vantage. Args: ticker (str): Ticker symbol of the company freq (str): Reporting frequency: annual/quarterly (default quarterly) - not used for Alpha Vantage curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage) Returns: str: Cash flow statement data with normalized fields """ params = { "symbol": ticker, } return _make_api_request("CASH_FLOW", params) def get_income_statement(ticker: str, freq: str = "quarterly", curr_date: str = None) -> str: """ Retrieve income statement data for a given ticker symbol using Alpha Vantage. Args: ticker (str): Ticker symbol of the company freq (str): Reporting frequency: annual/quarterly (default quarterly) - not used for Alpha Vantage curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage) Returns: str: Income statement data with normalized fields """ params = { "symbol": ticker, } return _make_api_request("INCOME_STATEMENT", params)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/alpha_vantage_fundamentals.py", "license": "Apache License 2.0", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TauricResearch/TradingAgents:tradingagents/dataflows/alpha_vantage_indicator.py
from .alpha_vantage_common import _make_api_request def get_indicator( symbol: str, indicator: str, curr_date: str, look_back_days: int, interval: str = "daily", time_period: int = 14, series_type: str = "close" ) -> str: """ Returns Alpha Vantage technical indicator values over a time window. Args: symbol: ticker symbol of the company indicator: technical indicator to get the analysis and report of curr_date: The current trading date you are trading on, YYYY-mm-dd look_back_days: how many days to look back interval: Time interval (daily, weekly, monthly) time_period: Number of data points for calculation series_type: The desired price type (close, open, high, low) Returns: String containing indicator values and description """ from datetime import datetime from dateutil.relativedelta import relativedelta supported_indicators = { "close_50_sma": ("50 SMA", "close"), "close_200_sma": ("200 SMA", "close"), "close_10_ema": ("10 EMA", "close"), "macd": ("MACD", "close"), "macds": ("MACD Signal", "close"), "macdh": ("MACD Histogram", "close"), "rsi": ("RSI", "close"), "boll": ("Bollinger Middle", "close"), "boll_ub": ("Bollinger Upper Band", "close"), "boll_lb": ("Bollinger Lower Band", "close"), "atr": ("ATR", None), "vwma": ("VWMA", "close") } indicator_descriptions = { "close_50_sma": "50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals.", "close_200_sma": "200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries.", "close_10_ema": "10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals.", "macd": "MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets.", "macds": "MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives.", "macdh": "MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets.", "rsi": "RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis.", "boll": "Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals.", "boll_ub": "Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends.", "boll_lb": "Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals.", "atr": "ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy.", "vwma": "VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses." } if indicator not in supported_indicators: raise ValueError( f"Indicator {indicator} is not supported. Please choose from: {list(supported_indicators.keys())}" ) curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d") before = curr_date_dt - relativedelta(days=look_back_days) # Get the full data for the period instead of making individual calls _, required_series_type = supported_indicators[indicator] # Use the provided series_type or fall back to the required one if required_series_type: series_type = required_series_type try: # Get indicator data for the period if indicator == "close_50_sma": data = _make_api_request("SMA", { "symbol": symbol, "interval": interval, "time_period": "50", "series_type": series_type, "datatype": "csv" }) elif indicator == "close_200_sma": data = _make_api_request("SMA", { "symbol": symbol, "interval": interval, "time_period": "200", "series_type": series_type, "datatype": "csv" }) elif indicator == "close_10_ema": data = _make_api_request("EMA", { "symbol": symbol, "interval": interval, "time_period": "10", "series_type": series_type, "datatype": "csv" }) elif indicator == "macd": data = _make_api_request("MACD", { "symbol": symbol, "interval": interval, "series_type": series_type, "datatype": "csv" }) elif indicator == "macds": data = _make_api_request("MACD", { "symbol": symbol, "interval": interval, "series_type": series_type, "datatype": "csv" }) elif indicator == "macdh": data = _make_api_request("MACD", { "symbol": symbol, "interval": interval, "series_type": series_type, "datatype": "csv" }) elif indicator == "rsi": data = _make_api_request("RSI", { "symbol": symbol, "interval": interval, "time_period": str(time_period), "series_type": series_type, "datatype": "csv" }) elif indicator in ["boll", "boll_ub", "boll_lb"]: data = _make_api_request("BBANDS", { "symbol": symbol, "interval": interval, "time_period": "20", "series_type": series_type, "datatype": "csv" }) elif indicator == "atr": data = _make_api_request("ATR", { "symbol": symbol, "interval": interval, "time_period": str(time_period), "datatype": "csv" }) elif indicator == "vwma": # Alpha Vantage doesn't have direct VWMA, so we'll return an informative message # In a real implementation, this would need to be calculated from OHLCV data return f"## VWMA (Volume Weighted Moving Average) for {symbol}:\n\nVWMA calculation requires OHLCV data and is not directly available from Alpha Vantage API.\nThis indicator would need to be calculated from the raw stock data using volume-weighted price averaging.\n\n{indicator_descriptions.get('vwma', 'No description available.')}" else: return f"Error: Indicator {indicator} not implemented yet." # Parse CSV data and extract values for the date range lines = data.strip().split('\n') if len(lines) < 2: return f"Error: No data returned for {indicator}" # Parse header and data header = [col.strip() for col in lines[0].split(',')] try: date_col_idx = header.index('time') except ValueError: return f"Error: 'time' column not found in data for {indicator}. Available columns: {header}" # Map internal indicator names to expected CSV column names from Alpha Vantage col_name_map = { "macd": "MACD", "macds": "MACD_Signal", "macdh": "MACD_Hist", "boll": "Real Middle Band", "boll_ub": "Real Upper Band", "boll_lb": "Real Lower Band", "rsi": "RSI", "atr": "ATR", "close_10_ema": "EMA", "close_50_sma": "SMA", "close_200_sma": "SMA" } target_col_name = col_name_map.get(indicator) if not target_col_name: # Default to the second column if no specific mapping exists value_col_idx = 1 else: try: value_col_idx = header.index(target_col_name) except ValueError: return f"Error: Column '{target_col_name}' not found for indicator '{indicator}'. Available columns: {header}" result_data = [] for line in lines[1:]: if not line.strip(): continue values = line.split(',') if len(values) > value_col_idx: try: date_str = values[date_col_idx].strip() # Parse the date date_dt = datetime.strptime(date_str, "%Y-%m-%d") # Check if date is in our range if before <= date_dt <= curr_date_dt: value = values[value_col_idx].strip() result_data.append((date_dt, value)) except (ValueError, IndexError): continue # Sort by date and format output result_data.sort(key=lambda x: x[0]) ind_string = "" for date_dt, value in result_data: ind_string += f"{date_dt.strftime('%Y-%m-%d')}: {value}\n" if not ind_string: ind_string = "No data available for the specified date range.\n" result_str = ( f"## {indicator.upper()} values from {before.strftime('%Y-%m-%d')} to {curr_date}:\n\n" + ind_string + "\n\n" + indicator_descriptions.get(indicator, "No description available.") ) return result_str except Exception as e: print(f"Error getting Alpha Vantage indicator data for {indicator}: {e}") return f"Error retrieving {indicator} data: {str(e)}"
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/alpha_vantage_indicator.py", "license": "Apache License 2.0", "lines": 199, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/dataflows/alpha_vantage_news.py
from .alpha_vantage_common import _make_api_request, format_datetime_for_api def get_news(ticker, start_date, end_date) -> dict[str, str] | str: """Returns live and historical market news & sentiment data from premier news outlets worldwide. Covers stocks, cryptocurrencies, forex, and topics like fiscal policy, mergers & acquisitions, IPOs. Args: ticker: Stock symbol for news articles. start_date: Start date for news search. end_date: End date for news search. Returns: Dictionary containing news sentiment data or JSON string. """ params = { "tickers": ticker, "time_from": format_datetime_for_api(start_date), "time_to": format_datetime_for_api(end_date), } return _make_api_request("NEWS_SENTIMENT", params) def get_global_news(curr_date, look_back_days: int = 7, limit: int = 50) -> dict[str, str] | str: """Returns global market news & sentiment data without ticker-specific filtering. Covers broad market topics like financial markets, economy, and more. Args: curr_date: Current date in yyyy-mm-dd format. look_back_days: Number of days to look back (default 7). limit: Maximum number of articles (default 50). Returns: Dictionary containing global news sentiment data or JSON string. """ from datetime import datetime, timedelta # Calculate start date curr_dt = datetime.strptime(curr_date, "%Y-%m-%d") start_dt = curr_dt - timedelta(days=look_back_days) start_date = start_dt.strftime("%Y-%m-%d") params = { "topics": "financial_markets,economy_macro,economy_monetary", "time_from": format_datetime_for_api(start_date), "time_to": format_datetime_for_api(curr_date), "limit": str(limit), } return _make_api_request("NEWS_SENTIMENT", params) def get_insider_transactions(symbol: str) -> dict[str, str] | str: """Returns latest and historical insider transactions by key stakeholders. Covers transactions by founders, executives, board members, etc. Args: symbol: Ticker symbol. Example: "IBM". Returns: Dictionary containing insider transaction data or JSON string. """ params = { "symbol": symbol, } return _make_api_request("INSIDER_TRANSACTIONS", params)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/alpha_vantage_news.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
TauricResearch/TradingAgents:tradingagents/dataflows/alpha_vantage_stock.py
from datetime import datetime from .alpha_vantage_common import _make_api_request, _filter_csv_by_date_range def get_stock( symbol: str, start_date: str, end_date: str ) -> str: """ Returns raw daily OHLCV values, adjusted close values, and historical split/dividend events filtered to the specified date range. Args: symbol: The name of the equity. For example: symbol=IBM start_date: Start date in yyyy-mm-dd format end_date: End date in yyyy-mm-dd format Returns: CSV string containing the daily adjusted time series data filtered to the date range. """ # Parse dates to determine the range start_dt = datetime.strptime(start_date, "%Y-%m-%d") today = datetime.now() # Choose outputsize based on whether the requested range is within the latest 100 days # Compact returns latest 100 data points, so check if start_date is recent enough days_from_today_to_start = (today - start_dt).days outputsize = "compact" if days_from_today_to_start < 100 else "full" params = { "symbol": symbol, "outputsize": outputsize, "datatype": "csv", } response = _make_api_request("TIME_SERIES_DAILY_ADJUSTED", params) return _filter_csv_by_date_range(response, start_date, end_date)
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/alpha_vantage_stock.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/dataflows/y_finance.py
from typing import Annotated from datetime import datetime from dateutil.relativedelta import relativedelta import yfinance as yf import os from .stockstats_utils import StockstatsUtils def get_YFin_data_online( symbol: Annotated[str, "ticker symbol of the company"], start_date: Annotated[str, "Start date in yyyy-mm-dd format"], end_date: Annotated[str, "End date in yyyy-mm-dd format"], ): datetime.strptime(start_date, "%Y-%m-%d") datetime.strptime(end_date, "%Y-%m-%d") # Create ticker object ticker = yf.Ticker(symbol.upper()) # Fetch historical data for the specified date range data = ticker.history(start=start_date, end=end_date) # Check if data is empty if data.empty: return ( f"No data found for symbol '{symbol}' between {start_date} and {end_date}" ) # Remove timezone info from index for cleaner output if data.index.tz is not None: data.index = data.index.tz_localize(None) # Round numerical values to 2 decimal places for cleaner display numeric_columns = ["Open", "High", "Low", "Close", "Adj Close"] for col in numeric_columns: if col in data.columns: data[col] = data[col].round(2) # Convert DataFrame to CSV string csv_string = data.to_csv() # Add header information header = f"# Stock data for {symbol.upper()} from {start_date} to {end_date}\n" header += f"# Total records: {len(data)}\n" header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" return header + csv_string def get_stock_stats_indicators_window( symbol: Annotated[str, "ticker symbol of the company"], indicator: Annotated[str, "technical indicator to get the analysis and report of"], curr_date: Annotated[ str, "The current trading date you are trading on, YYYY-mm-dd" ], look_back_days: Annotated[int, "how many days to look back"], ) -> str: best_ind_params = { # Moving Averages "close_50_sma": ( "50 SMA: A medium-term trend indicator. " "Usage: Identify trend direction and serve as dynamic support/resistance. " "Tips: It lags price; combine with faster indicators for timely signals." ), "close_200_sma": ( "200 SMA: A long-term trend benchmark. " "Usage: Confirm overall market trend and identify golden/death cross setups. " "Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries." ), "close_10_ema": ( "10 EMA: A responsive short-term average. " "Usage: Capture quick shifts in momentum and potential entry points. " "Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals." ), # MACD Related "macd": ( "MACD: Computes momentum via differences of EMAs. " "Usage: Look for crossovers and divergence as signals of trend changes. " "Tips: Confirm with other indicators in low-volatility or sideways markets." ), "macds": ( "MACD Signal: An EMA smoothing of the MACD line. " "Usage: Use crossovers with the MACD line to trigger trades. " "Tips: Should be part of a broader strategy to avoid false positives." ), "macdh": ( "MACD Histogram: Shows the gap between the MACD line and its signal. " "Usage: Visualize momentum strength and spot divergence early. " "Tips: Can be volatile; complement with additional filters in fast-moving markets." ), # Momentum Indicators "rsi": ( "RSI: Measures momentum to flag overbought/oversold conditions. " "Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. " "Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis." ), # Volatility Indicators "boll": ( "Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. " "Usage: Acts as a dynamic benchmark for price movement. " "Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals." ), "boll_ub": ( "Bollinger Upper Band: Typically 2 standard deviations above the middle line. " "Usage: Signals potential overbought conditions and breakout zones. " "Tips: Confirm signals with other tools; prices may ride the band in strong trends." ), "boll_lb": ( "Bollinger Lower Band: Typically 2 standard deviations below the middle line. " "Usage: Indicates potential oversold conditions. " "Tips: Use additional analysis to avoid false reversal signals." ), "atr": ( "ATR: Averages true range to measure volatility. " "Usage: Set stop-loss levels and adjust position sizes based on current market volatility. " "Tips: It's a reactive measure, so use it as part of a broader risk management strategy." ), # Volume-Based Indicators "vwma": ( "VWMA: A moving average weighted by volume. " "Usage: Confirm trends by integrating price action with volume data. " "Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses." ), "mfi": ( "MFI: The Money Flow Index is a momentum indicator that uses both price and volume to measure buying and selling pressure. " "Usage: Identify overbought (>80) or oversold (<20) conditions and confirm the strength of trends or reversals. " "Tips: Use alongside RSI or MACD to confirm signals; divergence between price and MFI can indicate potential reversals." ), } if indicator not in best_ind_params: raise ValueError( f"Indicator {indicator} is not supported. Please choose from: {list(best_ind_params.keys())}" ) end_date = curr_date curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d") before = curr_date_dt - relativedelta(days=look_back_days) # Optimized: Get stock data once and calculate indicators for all dates try: indicator_data = _get_stock_stats_bulk(symbol, indicator, curr_date) # Generate the date range we need current_dt = curr_date_dt date_values = [] while current_dt >= before: date_str = current_dt.strftime('%Y-%m-%d') # Look up the indicator value for this date if date_str in indicator_data: indicator_value = indicator_data[date_str] else: indicator_value = "N/A: Not a trading day (weekend or holiday)" date_values.append((date_str, indicator_value)) current_dt = current_dt - relativedelta(days=1) # Build the result string ind_string = "" for date_str, value in date_values: ind_string += f"{date_str}: {value}\n" except Exception as e: print(f"Error getting bulk stockstats data: {e}") # Fallback to original implementation if bulk method fails ind_string = "" curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d") while curr_date_dt >= before: indicator_value = get_stockstats_indicator( symbol, indicator, curr_date_dt.strftime("%Y-%m-%d") ) ind_string += f"{curr_date_dt.strftime('%Y-%m-%d')}: {indicator_value}\n" curr_date_dt = curr_date_dt - relativedelta(days=1) result_str = ( f"## {indicator} values from {before.strftime('%Y-%m-%d')} to {end_date}:\n\n" + ind_string + "\n\n" + best_ind_params.get(indicator, "No description available.") ) return result_str def _get_stock_stats_bulk( symbol: Annotated[str, "ticker symbol of the company"], indicator: Annotated[str, "technical indicator to calculate"], curr_date: Annotated[str, "current date for reference"] ) -> dict: """ Optimized bulk calculation of stock stats indicators. Fetches data once and calculates indicator for all available dates. Returns dict mapping date strings to indicator values. """ from .config import get_config import pandas as pd from stockstats import wrap import os config = get_config() online = config["data_vendors"]["technical_indicators"] != "local" if not online: # Local data path try: data = pd.read_csv( os.path.join( config.get("data_cache_dir", "data"), f"{symbol}-YFin-data-2015-01-01-2025-03-25.csv", ) ) df = wrap(data) except FileNotFoundError: raise Exception("Stockstats fail: Yahoo Finance data not fetched yet!") else: # Online data fetching with caching today_date = pd.Timestamp.today() curr_date_dt = pd.to_datetime(curr_date) end_date = today_date start_date = today_date - pd.DateOffset(years=15) start_date_str = start_date.strftime("%Y-%m-%d") end_date_str = end_date.strftime("%Y-%m-%d") os.makedirs(config["data_cache_dir"], exist_ok=True) data_file = os.path.join( config["data_cache_dir"], f"{symbol}-YFin-data-{start_date_str}-{end_date_str}.csv", ) if os.path.exists(data_file): data = pd.read_csv(data_file) data["Date"] = pd.to_datetime(data["Date"]) else: data = yf.download( symbol, start=start_date_str, end=end_date_str, multi_level_index=False, progress=False, auto_adjust=True, ) data = data.reset_index() data.to_csv(data_file, index=False) df = wrap(data) df["Date"] = df["Date"].dt.strftime("%Y-%m-%d") # Calculate the indicator for all rows at once df[indicator] # This triggers stockstats to calculate the indicator # Create a dictionary mapping date strings to indicator values result_dict = {} for _, row in df.iterrows(): date_str = row["Date"] indicator_value = row[indicator] # Handle NaN/None values if pd.isna(indicator_value): result_dict[date_str] = "N/A" else: result_dict[date_str] = str(indicator_value) return result_dict def get_stockstats_indicator( symbol: Annotated[str, "ticker symbol of the company"], indicator: Annotated[str, "technical indicator to get the analysis and report of"], curr_date: Annotated[ str, "The current trading date you are trading on, YYYY-mm-dd" ], ) -> str: curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d") curr_date = curr_date_dt.strftime("%Y-%m-%d") try: indicator_value = StockstatsUtils.get_stock_stats( symbol, indicator, curr_date, ) except Exception as e: print( f"Error getting stockstats indicator data for indicator {indicator} on {curr_date}: {e}" ) return "" return str(indicator_value) def get_fundamentals( ticker: Annotated[str, "ticker symbol of the company"], curr_date: Annotated[str, "current date (not used for yfinance)"] = None ): """Get company fundamentals overview from yfinance.""" try: ticker_obj = yf.Ticker(ticker.upper()) info = ticker_obj.info if not info: return f"No fundamentals data found for symbol '{ticker}'" fields = [ ("Name", info.get("longName")), ("Sector", info.get("sector")), ("Industry", info.get("industry")), ("Market Cap", info.get("marketCap")), ("PE Ratio (TTM)", info.get("trailingPE")), ("Forward PE", info.get("forwardPE")), ("PEG Ratio", info.get("pegRatio")), ("Price to Book", info.get("priceToBook")), ("EPS (TTM)", info.get("trailingEps")), ("Forward EPS", info.get("forwardEps")), ("Dividend Yield", info.get("dividendYield")), ("Beta", info.get("beta")), ("52 Week High", info.get("fiftyTwoWeekHigh")), ("52 Week Low", info.get("fiftyTwoWeekLow")), ("50 Day Average", info.get("fiftyDayAverage")), ("200 Day Average", info.get("twoHundredDayAverage")), ("Revenue (TTM)", info.get("totalRevenue")), ("Gross Profit", info.get("grossProfits")), ("EBITDA", info.get("ebitda")), ("Net Income", info.get("netIncomeToCommon")), ("Profit Margin", info.get("profitMargins")), ("Operating Margin", info.get("operatingMargins")), ("Return on Equity", info.get("returnOnEquity")), ("Return on Assets", info.get("returnOnAssets")), ("Debt to Equity", info.get("debtToEquity")), ("Current Ratio", info.get("currentRatio")), ("Book Value", info.get("bookValue")), ("Free Cash Flow", info.get("freeCashflow")), ] lines = [] for label, value in fields: if value is not None: lines.append(f"{label}: {value}") header = f"# Company Fundamentals for {ticker.upper()}\n" header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" return header + "\n".join(lines) except Exception as e: return f"Error retrieving fundamentals for {ticker}: {str(e)}" def get_balance_sheet( ticker: Annotated[str, "ticker symbol of the company"], freq: Annotated[str, "frequency of data: 'annual' or 'quarterly'"] = "quarterly", curr_date: Annotated[str, "current date (not used for yfinance)"] = None ): """Get balance sheet data from yfinance.""" try: ticker_obj = yf.Ticker(ticker.upper()) if freq.lower() == "quarterly": data = ticker_obj.quarterly_balance_sheet else: data = ticker_obj.balance_sheet if data.empty: return f"No balance sheet data found for symbol '{ticker}'" # Convert to CSV string for consistency with other functions csv_string = data.to_csv() # Add header information header = f"# Balance Sheet data for {ticker.upper()} ({freq})\n" header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" return header + csv_string except Exception as e: return f"Error retrieving balance sheet for {ticker}: {str(e)}" def get_cashflow( ticker: Annotated[str, "ticker symbol of the company"], freq: Annotated[str, "frequency of data: 'annual' or 'quarterly'"] = "quarterly", curr_date: Annotated[str, "current date (not used for yfinance)"] = None ): """Get cash flow data from yfinance.""" try: ticker_obj = yf.Ticker(ticker.upper()) if freq.lower() == "quarterly": data = ticker_obj.quarterly_cashflow else: data = ticker_obj.cashflow if data.empty: return f"No cash flow data found for symbol '{ticker}'" # Convert to CSV string for consistency with other functions csv_string = data.to_csv() # Add header information header = f"# Cash Flow data for {ticker.upper()} ({freq})\n" header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" return header + csv_string except Exception as e: return f"Error retrieving cash flow for {ticker}: {str(e)}" def get_income_statement( ticker: Annotated[str, "ticker symbol of the company"], freq: Annotated[str, "frequency of data: 'annual' or 'quarterly'"] = "quarterly", curr_date: Annotated[str, "current date (not used for yfinance)"] = None ): """Get income statement data from yfinance.""" try: ticker_obj = yf.Ticker(ticker.upper()) if freq.lower() == "quarterly": data = ticker_obj.quarterly_income_stmt else: data = ticker_obj.income_stmt if data.empty: return f"No income statement data found for symbol '{ticker}'" # Convert to CSV string for consistency with other functions csv_string = data.to_csv() # Add header information header = f"# Income Statement data for {ticker.upper()} ({freq})\n" header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" return header + csv_string except Exception as e: return f"Error retrieving income statement for {ticker}: {str(e)}" def get_insider_transactions( ticker: Annotated[str, "ticker symbol of the company"] ): """Get insider transactions data from yfinance.""" try: ticker_obj = yf.Ticker(ticker.upper()) data = ticker_obj.insider_transactions if data is None or data.empty: return f"No insider transactions data found for symbol '{ticker}'" # Convert to CSV string for consistency with other functions csv_string = data.to_csv() # Add header information header = f"# Insider Transactions data for {ticker.upper()}\n" header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" return header + csv_string except Exception as e: return f"Error retrieving insider transactions for {ticker}: {str(e)}"
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/y_finance.py", "license": "Apache License 2.0", "lines": 384, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:cli/main.py
from typing import Optional import datetime import typer from pathlib import Path from functools import wraps from rich.console import Console from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() from rich.panel import Panel from rich.spinner import Spinner from rich.live import Live from rich.columns import Columns from rich.markdown import Markdown from rich.layout import Layout from rich.text import Text from rich.table import Table from collections import deque import time from rich.tree import Tree from rich import box from rich.align import Align from rich.rule import Rule from tradingagents.graph.trading_graph import TradingAgentsGraph from tradingagents.default_config import DEFAULT_CONFIG from cli.models import AnalystType from cli.utils import * from cli.announcements import fetch_announcements, display_announcements from cli.stats_handler import StatsCallbackHandler console = Console() app = typer.Typer( name="TradingAgents", help="TradingAgents CLI: Multi-Agents LLM Financial Trading Framework", add_completion=True, # Enable shell completion ) # Create a deque to store recent messages with a maximum length class MessageBuffer: # Fixed teams that always run (not user-selectable) FIXED_AGENTS = { "Research Team": ["Bull Researcher", "Bear Researcher", "Research Manager"], "Trading Team": ["Trader"], "Risk Management": ["Aggressive Analyst", "Neutral Analyst", "Conservative Analyst"], "Portfolio Management": ["Portfolio Manager"], } # Analyst name mapping ANALYST_MAPPING = { "market": "Market Analyst", "social": "Social Analyst", "news": "News Analyst", "fundamentals": "Fundamentals Analyst", } # Report section mapping: section -> (analyst_key for filtering, finalizing_agent) # analyst_key: which analyst selection controls this section (None = always included) # finalizing_agent: which agent must be "completed" for this report to count as done REPORT_SECTIONS = { "market_report": ("market", "Market Analyst"), "sentiment_report": ("social", "Social Analyst"), "news_report": ("news", "News Analyst"), "fundamentals_report": ("fundamentals", "Fundamentals Analyst"), "investment_plan": (None, "Research Manager"), "trader_investment_plan": (None, "Trader"), "final_trade_decision": (None, "Portfolio Manager"), } def __init__(self, max_length=100): self.messages = deque(maxlen=max_length) self.tool_calls = deque(maxlen=max_length) self.current_report = None self.final_report = None # Store the complete final report self.agent_status = {} self.current_agent = None self.report_sections = {} self.selected_analysts = [] self._last_message_id = None def init_for_analysis(self, selected_analysts): """Initialize agent status and report sections based on selected analysts. Args: selected_analysts: List of analyst type strings (e.g., ["market", "news"]) """ self.selected_analysts = [a.lower() for a in selected_analysts] # Build agent_status dynamically self.agent_status = {} # Add selected analysts for analyst_key in self.selected_analysts: if analyst_key in self.ANALYST_MAPPING: self.agent_status[self.ANALYST_MAPPING[analyst_key]] = "pending" # Add fixed teams for team_agents in self.FIXED_AGENTS.values(): for agent in team_agents: self.agent_status[agent] = "pending" # Build report_sections dynamically self.report_sections = {} for section, (analyst_key, _) in self.REPORT_SECTIONS.items(): if analyst_key is None or analyst_key in self.selected_analysts: self.report_sections[section] = None # Reset other state self.current_report = None self.final_report = None self.current_agent = None self.messages.clear() self.tool_calls.clear() self._last_message_id = None def get_completed_reports_count(self): """Count reports that are finalized (their finalizing agent is completed). A report is considered complete when: 1. The report section has content (not None), AND 2. The agent responsible for finalizing that report has status "completed" This prevents interim updates (like debate rounds) from counting as completed. """ count = 0 for section in self.report_sections: if section not in self.REPORT_SECTIONS: continue _, finalizing_agent = self.REPORT_SECTIONS[section] # Report is complete if it has content AND its finalizing agent is done has_content = self.report_sections.get(section) is not None agent_done = self.agent_status.get(finalizing_agent) == "completed" if has_content and agent_done: count += 1 return count def add_message(self, message_type, content): timestamp = datetime.datetime.now().strftime("%H:%M:%S") self.messages.append((timestamp, message_type, content)) def add_tool_call(self, tool_name, args): timestamp = datetime.datetime.now().strftime("%H:%M:%S") self.tool_calls.append((timestamp, tool_name, args)) def update_agent_status(self, agent, status): if agent in self.agent_status: self.agent_status[agent] = status self.current_agent = agent def update_report_section(self, section_name, content): if section_name in self.report_sections: self.report_sections[section_name] = content self._update_current_report() def _update_current_report(self): # For the panel display, only show the most recently updated section latest_section = None latest_content = None # Find the most recently updated section for section, content in self.report_sections.items(): if content is not None: latest_section = section latest_content = content if latest_section and latest_content: # Format the current section for display section_titles = { "market_report": "Market Analysis", "sentiment_report": "Social Sentiment", "news_report": "News Analysis", "fundamentals_report": "Fundamentals Analysis", "investment_plan": "Research Team Decision", "trader_investment_plan": "Trading Team Plan", "final_trade_decision": "Portfolio Management Decision", } self.current_report = ( f"### {section_titles[latest_section]}\n{latest_content}" ) # Update the final complete report self._update_final_report() def _update_final_report(self): report_parts = [] # Analyst Team Reports - use .get() to handle missing sections analyst_sections = ["market_report", "sentiment_report", "news_report", "fundamentals_report"] if any(self.report_sections.get(section) for section in analyst_sections): report_parts.append("## Analyst Team Reports") if self.report_sections.get("market_report"): report_parts.append( f"### Market Analysis\n{self.report_sections['market_report']}" ) if self.report_sections.get("sentiment_report"): report_parts.append( f"### Social Sentiment\n{self.report_sections['sentiment_report']}" ) if self.report_sections.get("news_report"): report_parts.append( f"### News Analysis\n{self.report_sections['news_report']}" ) if self.report_sections.get("fundamentals_report"): report_parts.append( f"### Fundamentals Analysis\n{self.report_sections['fundamentals_report']}" ) # Research Team Reports if self.report_sections.get("investment_plan"): report_parts.append("## Research Team Decision") report_parts.append(f"{self.report_sections['investment_plan']}") # Trading Team Reports if self.report_sections.get("trader_investment_plan"): report_parts.append("## Trading Team Plan") report_parts.append(f"{self.report_sections['trader_investment_plan']}") # Portfolio Management Decision if self.report_sections.get("final_trade_decision"): report_parts.append("## Portfolio Management Decision") report_parts.append(f"{self.report_sections['final_trade_decision']}") self.final_report = "\n\n".join(report_parts) if report_parts else None message_buffer = MessageBuffer() def create_layout(): layout = Layout() layout.split_column( Layout(name="header", size=3), Layout(name="main"), Layout(name="footer", size=3), ) layout["main"].split_column( Layout(name="upper", ratio=3), Layout(name="analysis", ratio=5) ) layout["upper"].split_row( Layout(name="progress", ratio=2), Layout(name="messages", ratio=3) ) return layout def format_tokens(n): """Format token count for display.""" if n >= 1000: return f"{n/1000:.1f}k" return str(n) def update_display(layout, spinner_text=None, stats_handler=None, start_time=None): # Header with welcome message layout["header"].update( Panel( "[bold green]Welcome to TradingAgents CLI[/bold green]\n" "[dim]© [Tauric Research](https://github.com/TauricResearch)[/dim]", title="Welcome to TradingAgents", border_style="green", padding=(1, 2), expand=True, ) ) # Progress panel showing agent status progress_table = Table( show_header=True, header_style="bold magenta", show_footer=False, box=box.SIMPLE_HEAD, # Use simple header with horizontal lines title=None, # Remove the redundant Progress title padding=(0, 2), # Add horizontal padding expand=True, # Make table expand to fill available space ) progress_table.add_column("Team", style="cyan", justify="center", width=20) progress_table.add_column("Agent", style="green", justify="center", width=20) progress_table.add_column("Status", style="yellow", justify="center", width=20) # Group agents by team - filter to only include agents in agent_status all_teams = { "Analyst Team": [ "Market Analyst", "Social Analyst", "News Analyst", "Fundamentals Analyst", ], "Research Team": ["Bull Researcher", "Bear Researcher", "Research Manager"], "Trading Team": ["Trader"], "Risk Management": ["Aggressive Analyst", "Neutral Analyst", "Conservative Analyst"], "Portfolio Management": ["Portfolio Manager"], } # Filter teams to only include agents that are in agent_status teams = {} for team, agents in all_teams.items(): active_agents = [a for a in agents if a in message_buffer.agent_status] if active_agents: teams[team] = active_agents for team, agents in teams.items(): # Add first agent with team name first_agent = agents[0] status = message_buffer.agent_status.get(first_agent, "pending") if status == "in_progress": spinner = Spinner( "dots", text="[blue]in_progress[/blue]", style="bold cyan" ) status_cell = spinner else: status_color = { "pending": "yellow", "completed": "green", "error": "red", }.get(status, "white") status_cell = f"[{status_color}]{status}[/{status_color}]" progress_table.add_row(team, first_agent, status_cell) # Add remaining agents in team for agent in agents[1:]: status = message_buffer.agent_status.get(agent, "pending") if status == "in_progress": spinner = Spinner( "dots", text="[blue]in_progress[/blue]", style="bold cyan" ) status_cell = spinner else: status_color = { "pending": "yellow", "completed": "green", "error": "red", }.get(status, "white") status_cell = f"[{status_color}]{status}[/{status_color}]" progress_table.add_row("", agent, status_cell) # Add horizontal line after each team progress_table.add_row("─" * 20, "─" * 20, "─" * 20, style="dim") layout["progress"].update( Panel(progress_table, title="Progress", border_style="cyan", padding=(1, 2)) ) # Messages panel showing recent messages and tool calls messages_table = Table( show_header=True, header_style="bold magenta", show_footer=False, expand=True, # Make table expand to fill available space box=box.MINIMAL, # Use minimal box style for a lighter look show_lines=True, # Keep horizontal lines padding=(0, 1), # Add some padding between columns ) messages_table.add_column("Time", style="cyan", width=8, justify="center") messages_table.add_column("Type", style="green", width=10, justify="center") messages_table.add_column( "Content", style="white", no_wrap=False, ratio=1 ) # Make content column expand # Combine tool calls and messages all_messages = [] # Add tool calls for timestamp, tool_name, args in message_buffer.tool_calls: formatted_args = format_tool_args(args) all_messages.append((timestamp, "Tool", f"{tool_name}: {formatted_args}")) # Add regular messages for timestamp, msg_type, content in message_buffer.messages: content_str = str(content) if content else "" if len(content_str) > 200: content_str = content_str[:197] + "..." all_messages.append((timestamp, msg_type, content_str)) # Sort by timestamp descending (newest first) all_messages.sort(key=lambda x: x[0], reverse=True) # Calculate how many messages we can show based on available space max_messages = 12 # Get the first N messages (newest ones) recent_messages = all_messages[:max_messages] # Add messages to table (already in newest-first order) for timestamp, msg_type, content in recent_messages: # Format content with word wrapping wrapped_content = Text(content, overflow="fold") messages_table.add_row(timestamp, msg_type, wrapped_content) layout["messages"].update( Panel( messages_table, title="Messages & Tools", border_style="blue", padding=(1, 2), ) ) # Analysis panel showing current report if message_buffer.current_report: layout["analysis"].update( Panel( Markdown(message_buffer.current_report), title="Current Report", border_style="green", padding=(1, 2), ) ) else: layout["analysis"].update( Panel( "[italic]Waiting for analysis report...[/italic]", title="Current Report", border_style="green", padding=(1, 2), ) ) # Footer with statistics # Agent progress - derived from agent_status dict agents_completed = sum( 1 for status in message_buffer.agent_status.values() if status == "completed" ) agents_total = len(message_buffer.agent_status) # Report progress - based on agent completion (not just content existence) reports_completed = message_buffer.get_completed_reports_count() reports_total = len(message_buffer.report_sections) # Build stats parts stats_parts = [f"Agents: {agents_completed}/{agents_total}"] # LLM and tool stats from callback handler if stats_handler: stats = stats_handler.get_stats() stats_parts.append(f"LLM: {stats['llm_calls']}") stats_parts.append(f"Tools: {stats['tool_calls']}") # Token display with graceful fallback if stats["tokens_in"] > 0 or stats["tokens_out"] > 0: tokens_str = f"Tokens: {format_tokens(stats['tokens_in'])}\u2191 {format_tokens(stats['tokens_out'])}\u2193" else: tokens_str = "Tokens: --" stats_parts.append(tokens_str) stats_parts.append(f"Reports: {reports_completed}/{reports_total}") # Elapsed time if start_time: elapsed = time.time() - start_time elapsed_str = f"\u23f1 {int(elapsed // 60):02d}:{int(elapsed % 60):02d}" stats_parts.append(elapsed_str) stats_table = Table(show_header=False, box=None, padding=(0, 2), expand=True) stats_table.add_column("Stats", justify="center") stats_table.add_row(" | ".join(stats_parts)) layout["footer"].update(Panel(stats_table, border_style="grey50")) def get_user_selections(): """Get all user selections before starting the analysis display.""" # Display ASCII art welcome message with open("./cli/static/welcome.txt", "r") as f: welcome_ascii = f.read() # Create welcome box content welcome_content = f"{welcome_ascii}\n" welcome_content += "[bold green]TradingAgents: Multi-Agents LLM Financial Trading Framework - CLI[/bold green]\n\n" welcome_content += "[bold]Workflow Steps:[/bold]\n" welcome_content += "I. Analyst Team → II. Research Team → III. Trader → IV. Risk Management → V. Portfolio Management\n\n" welcome_content += ( "[dim]Built by [Tauric Research](https://github.com/TauricResearch)[/dim]" ) # Create and center the welcome box welcome_box = Panel( welcome_content, border_style="green", padding=(1, 2), title="Welcome to TradingAgents", subtitle="Multi-Agents LLM Financial Trading Framework", ) console.print(Align.center(welcome_box)) console.print() console.print() # Add vertical space before announcements # Fetch and display announcements (silent on failure) announcements = fetch_announcements() display_announcements(console, announcements) # Create a boxed questionnaire for each step def create_question_box(title, prompt, default=None): box_content = f"[bold]{title}[/bold]\n" box_content += f"[dim]{prompt}[/dim]" if default: box_content += f"\n[dim]Default: {default}[/dim]" return Panel(box_content, border_style="blue", padding=(1, 2)) # Step 1: Ticker symbol console.print( create_question_box( "Step 1: Ticker Symbol", "Enter the ticker symbol to analyze", "SPY" ) ) selected_ticker = get_ticker() # Step 2: Analysis date default_date = datetime.datetime.now().strftime("%Y-%m-%d") console.print( create_question_box( "Step 2: Analysis Date", "Enter the analysis date (YYYY-MM-DD)", default_date, ) ) analysis_date = get_analysis_date() # Step 3: Select analysts console.print( create_question_box( "Step 3: Analysts Team", "Select your LLM analyst agents for the analysis" ) ) selected_analysts = select_analysts() console.print( f"[green]Selected analysts:[/green] {', '.join(analyst.value for analyst in selected_analysts)}" ) # Step 4: Research depth console.print( create_question_box( "Step 4: Research Depth", "Select your research depth level" ) ) selected_research_depth = select_research_depth() # Step 5: OpenAI backend console.print( create_question_box( "Step 5: OpenAI backend", "Select which service to talk to" ) ) selected_llm_provider, backend_url = select_llm_provider() # Step 6: Thinking agents console.print( create_question_box( "Step 6: Thinking Agents", "Select your thinking agents for analysis" ) ) selected_shallow_thinker = select_shallow_thinking_agent(selected_llm_provider) selected_deep_thinker = select_deep_thinking_agent(selected_llm_provider) # Step 7: Provider-specific thinking configuration thinking_level = None reasoning_effort = None provider_lower = selected_llm_provider.lower() if provider_lower == "google": console.print( create_question_box( "Step 7: Thinking Mode", "Configure Gemini thinking mode" ) ) thinking_level = ask_gemini_thinking_config() elif provider_lower == "openai": console.print( create_question_box( "Step 7: Reasoning Effort", "Configure OpenAI reasoning effort level" ) ) reasoning_effort = ask_openai_reasoning_effort() return { "ticker": selected_ticker, "analysis_date": analysis_date, "analysts": selected_analysts, "research_depth": selected_research_depth, "llm_provider": selected_llm_provider.lower(), "backend_url": backend_url, "shallow_thinker": selected_shallow_thinker, "deep_thinker": selected_deep_thinker, "google_thinking_level": thinking_level, "openai_reasoning_effort": reasoning_effort, } def get_ticker(): """Get ticker symbol from user input.""" return typer.prompt("", default="SPY") def get_analysis_date(): """Get the analysis date from user input.""" while True: date_str = typer.prompt( "", default=datetime.datetime.now().strftime("%Y-%m-%d") ) try: # Validate date format and ensure it's not in the future analysis_date = datetime.datetime.strptime(date_str, "%Y-%m-%d") if analysis_date.date() > datetime.datetime.now().date(): console.print("[red]Error: Analysis date cannot be in the future[/red]") continue return date_str except ValueError: console.print( "[red]Error: Invalid date format. Please use YYYY-MM-DD[/red]" ) def save_report_to_disk(final_state, ticker: str, save_path: Path): """Save complete analysis report to disk with organized subfolders.""" save_path.mkdir(parents=True, exist_ok=True) sections = [] # 1. Analysts analysts_dir = save_path / "1_analysts" analyst_parts = [] if final_state.get("market_report"): analysts_dir.mkdir(exist_ok=True) (analysts_dir / "market.md").write_text(final_state["market_report"]) analyst_parts.append(("Market Analyst", final_state["market_report"])) if final_state.get("sentiment_report"): analysts_dir.mkdir(exist_ok=True) (analysts_dir / "sentiment.md").write_text(final_state["sentiment_report"]) analyst_parts.append(("Social Analyst", final_state["sentiment_report"])) if final_state.get("news_report"): analysts_dir.mkdir(exist_ok=True) (analysts_dir / "news.md").write_text(final_state["news_report"]) analyst_parts.append(("News Analyst", final_state["news_report"])) if final_state.get("fundamentals_report"): analysts_dir.mkdir(exist_ok=True) (analysts_dir / "fundamentals.md").write_text(final_state["fundamentals_report"]) analyst_parts.append(("Fundamentals Analyst", final_state["fundamentals_report"])) if analyst_parts: content = "\n\n".join(f"### {name}\n{text}" for name, text in analyst_parts) sections.append(f"## I. Analyst Team Reports\n\n{content}") # 2. Research if final_state.get("investment_debate_state"): research_dir = save_path / "2_research" debate = final_state["investment_debate_state"] research_parts = [] if debate.get("bull_history"): research_dir.mkdir(exist_ok=True) (research_dir / "bull.md").write_text(debate["bull_history"]) research_parts.append(("Bull Researcher", debate["bull_history"])) if debate.get("bear_history"): research_dir.mkdir(exist_ok=True) (research_dir / "bear.md").write_text(debate["bear_history"]) research_parts.append(("Bear Researcher", debate["bear_history"])) if debate.get("judge_decision"): research_dir.mkdir(exist_ok=True) (research_dir / "manager.md").write_text(debate["judge_decision"]) research_parts.append(("Research Manager", debate["judge_decision"])) if research_parts: content = "\n\n".join(f"### {name}\n{text}" for name, text in research_parts) sections.append(f"## II. Research Team Decision\n\n{content}") # 3. Trading if final_state.get("trader_investment_plan"): trading_dir = save_path / "3_trading" trading_dir.mkdir(exist_ok=True) (trading_dir / "trader.md").write_text(final_state["trader_investment_plan"]) sections.append(f"## III. Trading Team Plan\n\n### Trader\n{final_state['trader_investment_plan']}") # 4. Risk Management if final_state.get("risk_debate_state"): risk_dir = save_path / "4_risk" risk = final_state["risk_debate_state"] risk_parts = [] if risk.get("aggressive_history"): risk_dir.mkdir(exist_ok=True) (risk_dir / "aggressive.md").write_text(risk["aggressive_history"]) risk_parts.append(("Aggressive Analyst", risk["aggressive_history"])) if risk.get("conservative_history"): risk_dir.mkdir(exist_ok=True) (risk_dir / "conservative.md").write_text(risk["conservative_history"]) risk_parts.append(("Conservative Analyst", risk["conservative_history"])) if risk.get("neutral_history"): risk_dir.mkdir(exist_ok=True) (risk_dir / "neutral.md").write_text(risk["neutral_history"]) risk_parts.append(("Neutral Analyst", risk["neutral_history"])) if risk_parts: content = "\n\n".join(f"### {name}\n{text}" for name, text in risk_parts) sections.append(f"## IV. Risk Management Team Decision\n\n{content}") # 5. Portfolio Manager if risk.get("judge_decision"): portfolio_dir = save_path / "5_portfolio" portfolio_dir.mkdir(exist_ok=True) (portfolio_dir / "decision.md").write_text(risk["judge_decision"]) sections.append(f"## V. Portfolio Manager Decision\n\n### Portfolio Manager\n{risk['judge_decision']}") # Write consolidated report header = f"# Trading Analysis Report: {ticker}\n\nGenerated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" (save_path / "complete_report.md").write_text(header + "\n\n".join(sections)) return save_path / "complete_report.md" def display_complete_report(final_state): """Display the complete analysis report sequentially (avoids truncation).""" console.print() console.print(Rule("Complete Analysis Report", style="bold green")) # I. Analyst Team Reports analysts = [] if final_state.get("market_report"): analysts.append(("Market Analyst", final_state["market_report"])) if final_state.get("sentiment_report"): analysts.append(("Social Analyst", final_state["sentiment_report"])) if final_state.get("news_report"): analysts.append(("News Analyst", final_state["news_report"])) if final_state.get("fundamentals_report"): analysts.append(("Fundamentals Analyst", final_state["fundamentals_report"])) if analysts: console.print(Panel("[bold]I. Analyst Team Reports[/bold]", border_style="cyan")) for title, content in analysts: console.print(Panel(Markdown(content), title=title, border_style="blue", padding=(1, 2))) # II. Research Team Reports if final_state.get("investment_debate_state"): debate = final_state["investment_debate_state"] research = [] if debate.get("bull_history"): research.append(("Bull Researcher", debate["bull_history"])) if debate.get("bear_history"): research.append(("Bear Researcher", debate["bear_history"])) if debate.get("judge_decision"): research.append(("Research Manager", debate["judge_decision"])) if research: console.print(Panel("[bold]II. Research Team Decision[/bold]", border_style="magenta")) for title, content in research: console.print(Panel(Markdown(content), title=title, border_style="blue", padding=(1, 2))) # III. Trading Team if final_state.get("trader_investment_plan"): console.print(Panel("[bold]III. Trading Team Plan[/bold]", border_style="yellow")) console.print(Panel(Markdown(final_state["trader_investment_plan"]), title="Trader", border_style="blue", padding=(1, 2))) # IV. Risk Management Team if final_state.get("risk_debate_state"): risk = final_state["risk_debate_state"] risk_reports = [] if risk.get("aggressive_history"): risk_reports.append(("Aggressive Analyst", risk["aggressive_history"])) if risk.get("conservative_history"): risk_reports.append(("Conservative Analyst", risk["conservative_history"])) if risk.get("neutral_history"): risk_reports.append(("Neutral Analyst", risk["neutral_history"])) if risk_reports: console.print(Panel("[bold]IV. Risk Management Team Decision[/bold]", border_style="red")) for title, content in risk_reports: console.print(Panel(Markdown(content), title=title, border_style="blue", padding=(1, 2))) # V. Portfolio Manager Decision if risk.get("judge_decision"): console.print(Panel("[bold]V. Portfolio Manager Decision[/bold]", border_style="green")) console.print(Panel(Markdown(risk["judge_decision"]), title="Portfolio Manager", border_style="blue", padding=(1, 2))) def update_research_team_status(status): """Update status for research team members (not Trader).""" research_team = ["Bull Researcher", "Bear Researcher", "Research Manager"] for agent in research_team: message_buffer.update_agent_status(agent, status) # Ordered list of analysts for status transitions ANALYST_ORDER = ["market", "social", "news", "fundamentals"] ANALYST_AGENT_NAMES = { "market": "Market Analyst", "social": "Social Analyst", "news": "News Analyst", "fundamentals": "Fundamentals Analyst", } ANALYST_REPORT_MAP = { "market": "market_report", "social": "sentiment_report", "news": "news_report", "fundamentals": "fundamentals_report", } def update_analyst_statuses(message_buffer, chunk): """Update all analyst statuses based on current report state. Logic: - Analysts with reports = completed - First analyst without report = in_progress - Remaining analysts without reports = pending - When all analysts done, set Bull Researcher to in_progress """ selected = message_buffer.selected_analysts found_active = False for analyst_key in ANALYST_ORDER: if analyst_key not in selected: continue agent_name = ANALYST_AGENT_NAMES[analyst_key] report_key = ANALYST_REPORT_MAP[analyst_key] has_report = bool(chunk.get(report_key)) if has_report: message_buffer.update_agent_status(agent_name, "completed") message_buffer.update_report_section(report_key, chunk[report_key]) elif not found_active: message_buffer.update_agent_status(agent_name, "in_progress") found_active = True else: message_buffer.update_agent_status(agent_name, "pending") # When all analysts complete, transition research team to in_progress if not found_active and selected: if message_buffer.agent_status.get("Bull Researcher") == "pending": message_buffer.update_agent_status("Bull Researcher", "in_progress") def extract_content_string(content): """Extract string content from various message formats. Returns None if no meaningful text content is found. """ import ast def is_empty(val): """Check if value is empty using Python's truthiness.""" if val is None or val == '': return True if isinstance(val, str): s = val.strip() if not s: return True try: return not bool(ast.literal_eval(s)) except (ValueError, SyntaxError): return False # Can't parse = real text return not bool(val) if is_empty(content): return None if isinstance(content, str): return content.strip() if isinstance(content, dict): text = content.get('text', '') return text.strip() if not is_empty(text) else None if isinstance(content, list): text_parts = [ item.get('text', '').strip() if isinstance(item, dict) and item.get('type') == 'text' else (item.strip() if isinstance(item, str) else '') for item in content ] result = ' '.join(t for t in text_parts if t and not is_empty(t)) return result if result else None return str(content).strip() if not is_empty(content) else None def classify_message_type(message) -> tuple[str, str | None]: """Classify LangChain message into display type and extract content. Returns: (type, content) - type is one of: User, Agent, Data, Control - content is extracted string or None """ from langchain_core.messages import AIMessage, HumanMessage, ToolMessage content = extract_content_string(getattr(message, 'content', None)) if isinstance(message, HumanMessage): if content and content.strip() == "Continue": return ("Control", content) return ("User", content) if isinstance(message, ToolMessage): return ("Data", content) if isinstance(message, AIMessage): return ("Agent", content) # Fallback for unknown types return ("System", content) def format_tool_args(args, max_length=80) -> str: """Format tool arguments for terminal display.""" result = str(args) if len(result) > max_length: return result[:max_length - 3] + "..." return result def run_analysis(): # First get all user selections selections = get_user_selections() # Create config with selected research depth config = DEFAULT_CONFIG.copy() config["max_debate_rounds"] = selections["research_depth"] config["max_risk_discuss_rounds"] = selections["research_depth"] config["quick_think_llm"] = selections["shallow_thinker"] config["deep_think_llm"] = selections["deep_thinker"] config["backend_url"] = selections["backend_url"] config["llm_provider"] = selections["llm_provider"].lower() # Provider-specific thinking configuration config["google_thinking_level"] = selections.get("google_thinking_level") config["openai_reasoning_effort"] = selections.get("openai_reasoning_effort") # Create stats callback handler for tracking LLM/tool calls stats_handler = StatsCallbackHandler() # Normalize analyst selection to predefined order (selection is a 'set', order is fixed) selected_set = {analyst.value for analyst in selections["analysts"]} selected_analyst_keys = [a for a in ANALYST_ORDER if a in selected_set] # Initialize the graph with callbacks bound to LLMs graph = TradingAgentsGraph( selected_analyst_keys, config=config, debug=True, callbacks=[stats_handler], ) # Initialize message buffer with selected analysts message_buffer.init_for_analysis(selected_analyst_keys) # Track start time for elapsed display start_time = time.time() # Create result directory results_dir = Path(config["results_dir"]) / selections["ticker"] / selections["analysis_date"] results_dir.mkdir(parents=True, exist_ok=True) report_dir = results_dir / "reports" report_dir.mkdir(parents=True, exist_ok=True) log_file = results_dir / "message_tool.log" log_file.touch(exist_ok=True) def save_message_decorator(obj, func_name): func = getattr(obj, func_name) @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) timestamp, message_type, content = obj.messages[-1] content = content.replace("\n", " ") # Replace newlines with spaces with open(log_file, "a") as f: f.write(f"{timestamp} [{message_type}] {content}\n") return wrapper def save_tool_call_decorator(obj, func_name): func = getattr(obj, func_name) @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) timestamp, tool_name, args = obj.tool_calls[-1] args_str = ", ".join(f"{k}={v}" for k, v in args.items()) with open(log_file, "a") as f: f.write(f"{timestamp} [Tool Call] {tool_name}({args_str})\n") return wrapper def save_report_section_decorator(obj, func_name): func = getattr(obj, func_name) @wraps(func) def wrapper(section_name, content): func(section_name, content) if section_name in obj.report_sections and obj.report_sections[section_name] is not None: content = obj.report_sections[section_name] if content: file_name = f"{section_name}.md" with open(report_dir / file_name, "w") as f: f.write(content) return wrapper message_buffer.add_message = save_message_decorator(message_buffer, "add_message") message_buffer.add_tool_call = save_tool_call_decorator(message_buffer, "add_tool_call") message_buffer.update_report_section = save_report_section_decorator(message_buffer, "update_report_section") # Now start the display layout layout = create_layout() with Live(layout, refresh_per_second=4) as live: # Initial display update_display(layout, stats_handler=stats_handler, start_time=start_time) # Add initial messages message_buffer.add_message("System", f"Selected ticker: {selections['ticker']}") message_buffer.add_message( "System", f"Analysis date: {selections['analysis_date']}" ) message_buffer.add_message( "System", f"Selected analysts: {', '.join(analyst.value for analyst in selections['analysts'])}", ) update_display(layout, stats_handler=stats_handler, start_time=start_time) # Update agent status to in_progress for the first analyst first_analyst = f"{selections['analysts'][0].value.capitalize()} Analyst" message_buffer.update_agent_status(first_analyst, "in_progress") update_display(layout, stats_handler=stats_handler, start_time=start_time) # Create spinner text spinner_text = ( f"Analyzing {selections['ticker']} on {selections['analysis_date']}..." ) update_display(layout, spinner_text, stats_handler=stats_handler, start_time=start_time) # Initialize state and get graph args with callbacks init_agent_state = graph.propagator.create_initial_state( selections["ticker"], selections["analysis_date"] ) # Pass callbacks to graph config for tool execution tracking # (LLM tracking is handled separately via LLM constructor) args = graph.propagator.get_graph_args(callbacks=[stats_handler]) # Stream the analysis trace = [] for chunk in graph.graph.stream(init_agent_state, **args): # Process messages if present (skip duplicates via message ID) if len(chunk["messages"]) > 0: last_message = chunk["messages"][-1] msg_id = getattr(last_message, "id", None) if msg_id != message_buffer._last_message_id: message_buffer._last_message_id = msg_id # Add message to buffer msg_type, content = classify_message_type(last_message) if content and content.strip(): message_buffer.add_message(msg_type, content) # Handle tool calls if hasattr(last_message, "tool_calls") and last_message.tool_calls: for tool_call in last_message.tool_calls: if isinstance(tool_call, dict): message_buffer.add_tool_call( tool_call["name"], tool_call["args"] ) else: message_buffer.add_tool_call(tool_call.name, tool_call.args) # Update analyst statuses based on report state (runs on every chunk) update_analyst_statuses(message_buffer, chunk) # Research Team - Handle Investment Debate State if chunk.get("investment_debate_state"): debate_state = chunk["investment_debate_state"] bull_hist = debate_state.get("bull_history", "").strip() bear_hist = debate_state.get("bear_history", "").strip() judge = debate_state.get("judge_decision", "").strip() # Only update status when there's actual content if bull_hist or bear_hist: update_research_team_status("in_progress") if bull_hist: message_buffer.update_report_section( "investment_plan", f"### Bull Researcher Analysis\n{bull_hist}" ) if bear_hist: message_buffer.update_report_section( "investment_plan", f"### Bear Researcher Analysis\n{bear_hist}" ) if judge: message_buffer.update_report_section( "investment_plan", f"### Research Manager Decision\n{judge}" ) update_research_team_status("completed") message_buffer.update_agent_status("Trader", "in_progress") # Trading Team if chunk.get("trader_investment_plan"): message_buffer.update_report_section( "trader_investment_plan", chunk["trader_investment_plan"] ) if message_buffer.agent_status.get("Trader") != "completed": message_buffer.update_agent_status("Trader", "completed") message_buffer.update_agent_status("Aggressive Analyst", "in_progress") # Risk Management Team - Handle Risk Debate State if chunk.get("risk_debate_state"): risk_state = chunk["risk_debate_state"] agg_hist = risk_state.get("aggressive_history", "").strip() con_hist = risk_state.get("conservative_history", "").strip() neu_hist = risk_state.get("neutral_history", "").strip() judge = risk_state.get("judge_decision", "").strip() if agg_hist: if message_buffer.agent_status.get("Aggressive Analyst") != "completed": message_buffer.update_agent_status("Aggressive Analyst", "in_progress") message_buffer.update_report_section( "final_trade_decision", f"### Aggressive Analyst Analysis\n{agg_hist}" ) if con_hist: if message_buffer.agent_status.get("Conservative Analyst") != "completed": message_buffer.update_agent_status("Conservative Analyst", "in_progress") message_buffer.update_report_section( "final_trade_decision", f"### Conservative Analyst Analysis\n{con_hist}" ) if neu_hist: if message_buffer.agent_status.get("Neutral Analyst") != "completed": message_buffer.update_agent_status("Neutral Analyst", "in_progress") message_buffer.update_report_section( "final_trade_decision", f"### Neutral Analyst Analysis\n{neu_hist}" ) if judge: if message_buffer.agent_status.get("Portfolio Manager") != "completed": message_buffer.update_agent_status("Portfolio Manager", "in_progress") message_buffer.update_report_section( "final_trade_decision", f"### Portfolio Manager Decision\n{judge}" ) message_buffer.update_agent_status("Aggressive Analyst", "completed") message_buffer.update_agent_status("Conservative Analyst", "completed") message_buffer.update_agent_status("Neutral Analyst", "completed") message_buffer.update_agent_status("Portfolio Manager", "completed") # Update the display update_display(layout, stats_handler=stats_handler, start_time=start_time) trace.append(chunk) # Get final state and decision final_state = trace[-1] decision = graph.process_signal(final_state["final_trade_decision"]) # Update all agent statuses to completed for agent in message_buffer.agent_status: message_buffer.update_agent_status(agent, "completed") message_buffer.add_message( "System", f"Completed analysis for {selections['analysis_date']}" ) # Update final report sections for section in message_buffer.report_sections.keys(): if section in final_state: message_buffer.update_report_section(section, final_state[section]) update_display(layout, stats_handler=stats_handler, start_time=start_time) # Post-analysis prompts (outside Live context for clean interaction) console.print("\n[bold cyan]Analysis Complete![/bold cyan]\n") # Prompt to save report save_choice = typer.prompt("Save report?", default="Y").strip().upper() if save_choice in ("Y", "YES", ""): timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") default_path = Path.cwd() / "reports" / f"{selections['ticker']}_{timestamp}" save_path_str = typer.prompt( "Save path (press Enter for default)", default=str(default_path) ).strip() save_path = Path(save_path_str) try: report_file = save_report_to_disk(final_state, selections["ticker"], save_path) console.print(f"\n[green]✓ Report saved to:[/green] {save_path.resolve()}") console.print(f" [dim]Complete report:[/dim] {report_file.name}") except Exception as e: console.print(f"[red]Error saving report: {e}[/red]") # Prompt to display full report display_choice = typer.prompt("\nDisplay full report on screen?", default="Y").strip().upper() if display_choice in ("Y", "YES", ""): display_complete_report(final_state) @app.command() def analyze(): run_analysis() if __name__ == "__main__": app()
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "cli/main.py", "license": "Apache License 2.0", "lines": 1005, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:cli/models.py
from enum import Enum from typing import List, Optional, Dict from pydantic import BaseModel class AnalystType(str, Enum): MARKET = "market" SOCIAL = "social" NEWS = "news" FUNDAMENTALS = "fundamentals"
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "cli/models.py", "license": "Apache License 2.0", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:cli/utils.py
import questionary from typing import List, Optional, Tuple, Dict from cli.models import AnalystType ANALYST_ORDER = [ ("Market Analyst", AnalystType.MARKET), ("Social Media Analyst", AnalystType.SOCIAL), ("News Analyst", AnalystType.NEWS), ("Fundamentals Analyst", AnalystType.FUNDAMENTALS), ] def get_ticker() -> str: """Prompt the user to enter a ticker symbol.""" ticker = questionary.text( "Enter the ticker symbol to analyze:", validate=lambda x: len(x.strip()) > 0 or "Please enter a valid ticker symbol.", style=questionary.Style( [ ("text", "fg:green"), ("highlighted", "noinherit"), ] ), ).ask() if not ticker: console.print("\n[red]No ticker symbol provided. Exiting...[/red]") exit(1) return ticker.strip().upper() def get_analysis_date() -> str: """Prompt the user to enter a date in YYYY-MM-DD format.""" import re from datetime import datetime def validate_date(date_str: str) -> bool: if not re.match(r"^\d{4}-\d{2}-\d{2}$", date_str): return False try: datetime.strptime(date_str, "%Y-%m-%d") return True except ValueError: return False date = questionary.text( "Enter the analysis date (YYYY-MM-DD):", validate=lambda x: validate_date(x.strip()) or "Please enter a valid date in YYYY-MM-DD format.", style=questionary.Style( [ ("text", "fg:green"), ("highlighted", "noinherit"), ] ), ).ask() if not date: console.print("\n[red]No date provided. Exiting...[/red]") exit(1) return date.strip() def select_analysts() -> List[AnalystType]: """Select analysts using an interactive checkbox.""" choices = questionary.checkbox( "Select Your [Analysts Team]:", choices=[ questionary.Choice(display, value=value) for display, value in ANALYST_ORDER ], instruction="\n- Press Space to select/unselect analysts\n- Press 'a' to select/unselect all\n- Press Enter when done", validate=lambda x: len(x) > 0 or "You must select at least one analyst.", style=questionary.Style( [ ("checkbox-selected", "fg:green"), ("selected", "fg:green noinherit"), ("highlighted", "noinherit"), ("pointer", "noinherit"), ] ), ).ask() if not choices: console.print("\n[red]No analysts selected. Exiting...[/red]") exit(1) return choices def select_research_depth() -> int: """Select research depth using an interactive selection.""" # Define research depth options with their corresponding values DEPTH_OPTIONS = [ ("Shallow - Quick research, few debate and strategy discussion rounds", 1), ("Medium - Middle ground, moderate debate rounds and strategy discussion", 3), ("Deep - Comprehensive research, in depth debate and strategy discussion", 5), ] choice = questionary.select( "Select Your [Research Depth]:", choices=[ questionary.Choice(display, value=value) for display, value in DEPTH_OPTIONS ], instruction="\n- Use arrow keys to navigate\n- Press Enter to select", style=questionary.Style( [ ("selected", "fg:yellow noinherit"), ("highlighted", "fg:yellow noinherit"), ("pointer", "fg:yellow noinherit"), ] ), ).ask() if choice is None: console.print("\n[red]No research depth selected. Exiting...[/red]") exit(1) return choice def select_shallow_thinking_agent(provider) -> str: """Select shallow thinking llm engine using an interactive selection.""" # Define shallow thinking llm engine options with their corresponding model names SHALLOW_AGENT_OPTIONS = { "openai": [ ("GPT-5 Mini - Cost-optimized reasoning", "gpt-5-mini"), ("GPT-5 Nano - Ultra-fast, high-throughput", "gpt-5-nano"), ("GPT-5.2 - Latest flagship", "gpt-5.2"), ("GPT-5.1 - Flexible reasoning", "gpt-5.1"), ("GPT-4.1 - Smartest non-reasoning, 1M context", "gpt-4.1"), ], "anthropic": [ ("Claude Haiku 4.5 - Fast + extended thinking", "claude-haiku-4-5"), ("Claude Sonnet 4.5 - Best for agents/coding", "claude-sonnet-4-5"), ("Claude Sonnet 4 - High-performance", "claude-sonnet-4-20250514"), ], "google": [ ("Gemini 3 Flash - Next-gen fast", "gemini-3-flash-preview"), ("Gemini 2.5 Flash - Balanced, recommended", "gemini-2.5-flash"), ("Gemini 3 Pro - Reasoning-first", "gemini-3-pro-preview"), ("Gemini 2.5 Flash Lite - Fast, low-cost", "gemini-2.5-flash-lite"), ], "xai": [ ("Grok 4.1 Fast (Non-Reasoning) - Speed optimized, 2M ctx", "grok-4-1-fast-non-reasoning"), ("Grok 4 Fast (Non-Reasoning) - Speed optimized", "grok-4-fast-non-reasoning"), ("Grok 4.1 Fast (Reasoning) - High-performance, 2M ctx", "grok-4-1-fast-reasoning"), ("Grok 4 Fast (Reasoning) - High-performance", "grok-4-fast-reasoning"), ], "openrouter": [ ("NVIDIA Nemotron 3 Nano 30B (free)", "nvidia/nemotron-3-nano-30b-a3b:free"), ("Z.AI GLM 4.5 Air (free)", "z-ai/glm-4.5-air:free"), ], "ollama": [ ("Qwen3:latest (8B, local)", "qwen3:latest"), ("GPT-OSS:latest (20B, local)", "gpt-oss:latest"), ("GLM-4.7-Flash:latest (30B, local)", "glm-4.7-flash:latest"), ], } choice = questionary.select( "Select Your [Quick-Thinking LLM Engine]:", choices=[ questionary.Choice(display, value=value) for display, value in SHALLOW_AGENT_OPTIONS[provider.lower()] ], instruction="\n- Use arrow keys to navigate\n- Press Enter to select", style=questionary.Style( [ ("selected", "fg:magenta noinherit"), ("highlighted", "fg:magenta noinherit"), ("pointer", "fg:magenta noinherit"), ] ), ).ask() if choice is None: console.print( "\n[red]No shallow thinking llm engine selected. Exiting...[/red]" ) exit(1) return choice def select_deep_thinking_agent(provider) -> str: """Select deep thinking llm engine using an interactive selection.""" # Define deep thinking llm engine options with their corresponding model names DEEP_AGENT_OPTIONS = { "openai": [ ("GPT-5.2 - Latest flagship", "gpt-5.2"), ("GPT-5.1 - Flexible reasoning", "gpt-5.1"), ("GPT-5 - Advanced reasoning", "gpt-5"), ("GPT-4.1 - Smartest non-reasoning, 1M context", "gpt-4.1"), ("GPT-5 Mini - Cost-optimized reasoning", "gpt-5-mini"), ("GPT-5 Nano - Ultra-fast, high-throughput", "gpt-5-nano"), ], "anthropic": [ ("Claude Sonnet 4.5 - Best for agents/coding", "claude-sonnet-4-5"), ("Claude Opus 4.5 - Premium, max intelligence", "claude-opus-4-5"), ("Claude Opus 4.1 - Most capable model", "claude-opus-4-1-20250805"), ("Claude Haiku 4.5 - Fast + extended thinking", "claude-haiku-4-5"), ("Claude Sonnet 4 - High-performance", "claude-sonnet-4-20250514"), ], "google": [ ("Gemini 3 Pro - Reasoning-first", "gemini-3-pro-preview"), ("Gemini 3 Flash - Next-gen fast", "gemini-3-flash-preview"), ("Gemini 2.5 Flash - Balanced, recommended", "gemini-2.5-flash"), ], "xai": [ ("Grok 4.1 Fast (Reasoning) - High-performance, 2M ctx", "grok-4-1-fast-reasoning"), ("Grok 4 Fast (Reasoning) - High-performance", "grok-4-fast-reasoning"), ("Grok 4 - Flagship model", "grok-4-0709"), ("Grok 4.1 Fast (Non-Reasoning) - Speed optimized, 2M ctx", "grok-4-1-fast-non-reasoning"), ("Grok 4 Fast (Non-Reasoning) - Speed optimized", "grok-4-fast-non-reasoning"), ], "openrouter": [ ("Z.AI GLM 4.5 Air (free)", "z-ai/glm-4.5-air:free"), ("NVIDIA Nemotron 3 Nano 30B (free)", "nvidia/nemotron-3-nano-30b-a3b:free"), ], "ollama": [ ("GLM-4.7-Flash:latest (30B, local)", "glm-4.7-flash:latest"), ("GPT-OSS:latest (20B, local)", "gpt-oss:latest"), ("Qwen3:latest (8B, local)", "qwen3:latest"), ], } choice = questionary.select( "Select Your [Deep-Thinking LLM Engine]:", choices=[ questionary.Choice(display, value=value) for display, value in DEEP_AGENT_OPTIONS[provider.lower()] ], instruction="\n- Use arrow keys to navigate\n- Press Enter to select", style=questionary.Style( [ ("selected", "fg:magenta noinherit"), ("highlighted", "fg:magenta noinherit"), ("pointer", "fg:magenta noinherit"), ] ), ).ask() if choice is None: console.print("\n[red]No deep thinking llm engine selected. Exiting...[/red]") exit(1) return choice def select_llm_provider() -> tuple[str, str]: """Select the OpenAI api url using interactive selection.""" # Define OpenAI api options with their corresponding endpoints BASE_URLS = [ ("OpenAI", "https://api.openai.com/v1"), ("Google", "https://generativelanguage.googleapis.com/v1"), ("Anthropic", "https://api.anthropic.com/"), ("xAI", "https://api.x.ai/v1"), ("Openrouter", "https://openrouter.ai/api/v1"), ("Ollama", "http://localhost:11434/v1"), ] choice = questionary.select( "Select your LLM Provider:", choices=[ questionary.Choice(display, value=(display, value)) for display, value in BASE_URLS ], instruction="\n- Use arrow keys to navigate\n- Press Enter to select", style=questionary.Style( [ ("selected", "fg:magenta noinherit"), ("highlighted", "fg:magenta noinherit"), ("pointer", "fg:magenta noinherit"), ] ), ).ask() if choice is None: console.print("\n[red]no OpenAI backend selected. Exiting...[/red]") exit(1) display_name, url = choice print(f"You selected: {display_name}\tURL: {url}") return display_name, url def ask_openai_reasoning_effort() -> str: """Ask for OpenAI reasoning effort level.""" choices = [ questionary.Choice("Medium (Default)", "medium"), questionary.Choice("High (More thorough)", "high"), questionary.Choice("Low (Faster)", "low"), ] return questionary.select( "Select Reasoning Effort:", choices=choices, style=questionary.Style([ ("selected", "fg:cyan noinherit"), ("highlighted", "fg:cyan noinherit"), ("pointer", "fg:cyan noinherit"), ]), ).ask() def ask_gemini_thinking_config() -> str | None: """Ask for Gemini thinking configuration. Returns thinking_level: "high" or "minimal". Client maps to appropriate API param based on model series. """ return questionary.select( "Select Thinking Mode:", choices=[ questionary.Choice("Enable Thinking (recommended)", "high"), questionary.Choice("Minimal/Disable Thinking", "minimal"), ], style=questionary.Style([ ("selected", "fg:green noinherit"), ("highlighted", "fg:green noinherit"), ("pointer", "fg:green noinherit"), ]), ).ask()
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "cli/utils.py", "license": "Apache License 2.0", "lines": 284, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:main.py
from tradingagents.graph.trading_graph import TradingAgentsGraph from tradingagents.default_config import DEFAULT_CONFIG from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Create a custom config config = DEFAULT_CONFIG.copy() config["deep_think_llm"] = "gpt-5-mini" # Use a different model config["quick_think_llm"] = "gpt-5-mini" # Use a different model config["max_debate_rounds"] = 1 # Increase debate rounds # Configure data vendors (default uses yfinance, no extra API keys needed) config["data_vendors"] = { "core_stock_apis": "yfinance", # Options: alpha_vantage, yfinance "technical_indicators": "yfinance", # Options: alpha_vantage, yfinance "fundamental_data": "yfinance", # Options: alpha_vantage, yfinance "news_data": "yfinance", # Options: alpha_vantage, yfinance } # Initialize with custom config ta = TradingAgentsGraph(debug=True, config=config) # forward propagate _, decision = ta.propagate("NVDA", "2024-05-10") print(decision) # Memorize mistakes and reflect # ta.reflect_and_remember(1000) # parameter is the position returns
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "main.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/analysts/fundamentals_analyst.py
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder import time import json from tradingagents.agents.utils.agent_utils import get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement, get_insider_transactions from tradingagents.dataflows.config import get_config def create_fundamentals_analyst(llm): def fundamentals_analyst_node(state): current_date = state["trade_date"] ticker = state["company_of_interest"] company_name = state["company_of_interest"] tools = [ get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement, ] system_message = ( "You are a researcher tasked with analyzing fundamental information over the past week about a company. Please write a comprehensive report of the company's fundamental information such as financial documents, company profile, basic company financials, and company financial history to gain a full view of the company's fundamental information to inform traders. Make sure to include as much detail as possible. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions." + " Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read." + " Use the available tools: `get_fundamentals` for comprehensive company analysis, `get_balance_sheet`, `get_cashflow`, and `get_income_statement` for specific financial statements.", ) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful AI assistant, collaborating with other assistants." " Use the provided tools to progress towards answering the question." " If you are unable to fully answer, that's OK; another assistant with different tools" " will help where you left off. Execute what you can to make progress." " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable," " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop." " You have access to the following tools: {tool_names}.\n{system_message}" "For your reference, the current date is {current_date}. The company we want to look at is {ticker}", ), MessagesPlaceholder(variable_name="messages"), ] ) prompt = prompt.partial(system_message=system_message) prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) prompt = prompt.partial(current_date=current_date) prompt = prompt.partial(ticker=ticker) chain = prompt | llm.bind_tools(tools) result = chain.invoke(state["messages"]) report = "" if len(result.tool_calls) == 0: report = result.content return { "messages": [result], "fundamentals_report": report, } return fundamentals_analyst_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/analysts/fundamentals_analyst.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/analysts/market_analyst.py
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder import time import json from tradingagents.agents.utils.agent_utils import get_stock_data, get_indicators from tradingagents.dataflows.config import get_config def create_market_analyst(llm): def market_analyst_node(state): current_date = state["trade_date"] ticker = state["company_of_interest"] company_name = state["company_of_interest"] tools = [ get_stock_data, get_indicators, ] system_message = ( """You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy. Categories and each category's indicators are: Moving Averages: - close_50_sma: 50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals. - close_200_sma: 200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries. - close_10_ema: 10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals. MACD Related: - macd: MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets. - macds: MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives. - macdh: MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets. Momentum Indicators: - rsi: RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis. Volatility Indicators: - boll: Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals. - boll_ub: Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends. - boll_lb: Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals. - atr: ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy. Volume-Based Indicators: - vwma: VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses. - Select indicators that provide diverse and complementary information. Avoid redundancy (e.g., do not select both rsi and stochrsi). Also briefly explain why they are suitable for the given market context. When you tool call, please use the exact name of the indicators provided above as they are defined parameters, otherwise your call will fail. Please make sure to call get_stock_data first to retrieve the CSV that is needed to generate indicators. Then use get_indicators with the specific indicator names. Write a very detailed and nuanced report of the trends you observe. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.""" + """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful AI assistant, collaborating with other assistants." " Use the provided tools to progress towards answering the question." " If you are unable to fully answer, that's OK; another assistant with different tools" " will help where you left off. Execute what you can to make progress." " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable," " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop." " You have access to the following tools: {tool_names}.\n{system_message}" "For your reference, the current date is {current_date}. The company we want to look at is {ticker}", ), MessagesPlaceholder(variable_name="messages"), ] ) prompt = prompt.partial(system_message=system_message) prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) prompt = prompt.partial(current_date=current_date) prompt = prompt.partial(ticker=ticker) chain = prompt | llm.bind_tools(tools) result = chain.invoke(state["messages"]) report = "" if len(result.tool_calls) == 0: report = result.content return { "messages": [result], "market_report": report, } return market_analyst_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/analysts/market_analyst.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/agents/analysts/news_analyst.py
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder import time import json from tradingagents.agents.utils.agent_utils import get_news, get_global_news from tradingagents.dataflows.config import get_config def create_news_analyst(llm): def news_analyst_node(state): current_date = state["trade_date"] ticker = state["company_of_interest"] tools = [ get_news, get_global_news, ] system_message = ( "You are a news researcher tasked with analyzing recent news and trends over the past week. Please write a comprehensive report of the current state of the world that is relevant for trading and macroeconomics. Use the available tools: get_news(query, start_date, end_date) for company-specific or targeted news searches, and get_global_news(curr_date, look_back_days, limit) for broader macroeconomic news. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions." + """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""" ) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful AI assistant, collaborating with other assistants." " Use the provided tools to progress towards answering the question." " If you are unable to fully answer, that's OK; another assistant with different tools" " will help where you left off. Execute what you can to make progress." " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable," " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop." " You have access to the following tools: {tool_names}.\n{system_message}" "For your reference, the current date is {current_date}. We are looking at the company {ticker}", ), MessagesPlaceholder(variable_name="messages"), ] ) prompt = prompt.partial(system_message=system_message) prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) prompt = prompt.partial(current_date=current_date) prompt = prompt.partial(ticker=ticker) chain = prompt | llm.bind_tools(tools) result = chain.invoke(state["messages"]) report = "" if len(result.tool_calls) == 0: report = result.content return { "messages": [result], "news_report": report, } return news_analyst_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/analysts/news_analyst.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/analysts/social_media_analyst.py
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder import time import json from tradingagents.agents.utils.agent_utils import get_news from tradingagents.dataflows.config import get_config def create_social_media_analyst(llm): def social_media_analyst_node(state): current_date = state["trade_date"] ticker = state["company_of_interest"] company_name = state["company_of_interest"] tools = [ get_news, ] system_message = ( "You are a social media and company specific news researcher/analyst tasked with analyzing social media posts, recent company news, and public sentiment for a specific company over the past week. You will be given a company's name your objective is to write a comprehensive long report detailing your analysis, insights, and implications for traders and investors on this company's current state after looking at social media and what people are saying about that company, analyzing sentiment data of what people feel each day about the company, and looking at recent company news. Use the get_news(query, start_date, end_date) tool to search for company-specific news and social media discussions. Try to look at all sources possible from social media to sentiment to news. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions." + """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""", ) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are a helpful AI assistant, collaborating with other assistants." " Use the provided tools to progress towards answering the question." " If you are unable to fully answer, that's OK; another assistant with different tools" " will help where you left off. Execute what you can to make progress." " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable," " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop." " You have access to the following tools: {tool_names}.\n{system_message}" "For your reference, the current date is {current_date}. The current company we want to analyze is {ticker}", ), MessagesPlaceholder(variable_name="messages"), ] ) prompt = prompt.partial(system_message=system_message) prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) prompt = prompt.partial(current_date=current_date) prompt = prompt.partial(ticker=ticker) chain = prompt | llm.bind_tools(tools) result = chain.invoke(state["messages"]) report = "" if len(result.tool_calls) == 0: report = result.content return { "messages": [result], "sentiment_report": report, } return social_media_analyst_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/analysts/social_media_analyst.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/managers/research_manager.py
import time import json def create_research_manager(llm, memory): def research_manager_node(state) -> dict: history = state["investment_debate_state"].get("history", "") market_research_report = state["market_report"] sentiment_report = state["sentiment_report"] news_report = state["news_report"] fundamentals_report = state["fundamentals_report"] investment_debate_state = state["investment_debate_state"] curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for i, rec in enumerate(past_memories, 1): past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""As the portfolio manager and debate facilitator, your role is to critically evaluate this round of debate and make a definitive decision: align with the bear analyst, the bull analyst, or choose Hold only if it is strongly justified based on the arguments presented. Summarize the key points from both sides concisely, focusing on the most compelling evidence or reasoning. Your recommendation—Buy, Sell, or Hold—must be clear and actionable. Avoid defaulting to Hold simply because both sides have valid points; commit to a stance grounded in the debate's strongest arguments. Additionally, develop a detailed investment plan for the trader. This should include: Your Recommendation: A decisive stance supported by the most convincing arguments. Rationale: An explanation of why these arguments lead to your conclusion. Strategic Actions: Concrete steps for implementing the recommendation. Take into account your past mistakes on similar situations. Use these insights to refine your decision-making and ensure you are learning and improving. Present your analysis conversationally, as if speaking naturally, without special formatting. Here are your past reflections on mistakes: \"{past_memory_str}\" Here is the debate: Debate History: {history}""" response = llm.invoke(prompt) new_investment_debate_state = { "judge_decision": response.content, "history": investment_debate_state.get("history", ""), "bear_history": investment_debate_state.get("bear_history", ""), "bull_history": investment_debate_state.get("bull_history", ""), "current_response": response.content, "count": investment_debate_state["count"], } return { "investment_debate_state": new_investment_debate_state, "investment_plan": response.content, } return research_manager_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/managers/research_manager.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/managers/risk_manager.py
import time import json def create_risk_manager(llm, memory): def risk_manager_node(state) -> dict: company_name = state["company_of_interest"] history = state["risk_debate_state"]["history"] risk_debate_state = state["risk_debate_state"] market_research_report = state["market_report"] news_report = state["news_report"] fundamentals_report = state["fundamentals_report"] sentiment_report = state["sentiment_report"] trader_plan = state["investment_plan"] curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for i, rec in enumerate(past_memories, 1): past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""As the Risk Management Judge and Debate Facilitator, your goal is to evaluate the debate between three risk analysts—Aggressive, Neutral, and Conservative—and determine the best course of action for the trader. Your decision must result in a clear recommendation: Buy, Sell, or Hold. Choose Hold only if strongly justified by specific arguments, not as a fallback when all sides seem valid. Strive for clarity and decisiveness. Guidelines for Decision-Making: 1. **Summarize Key Arguments**: Extract the strongest points from each analyst, focusing on relevance to the context. 2. **Provide Rationale**: Support your recommendation with direct quotes and counterarguments from the debate. 3. **Refine the Trader's Plan**: Start with the trader's original plan, **{trader_plan}**, and adjust it based on the analysts' insights. 4. **Learn from Past Mistakes**: Use lessons from **{past_memory_str}** to address prior misjudgments and improve the decision you are making now to make sure you don't make a wrong BUY/SELL/HOLD call that loses money. Deliverables: - A clear and actionable recommendation: Buy, Sell, or Hold. - Detailed reasoning anchored in the debate and past reflections. --- **Analysts Debate History:** {history} --- Focus on actionable insights and continuous improvement. Build on past lessons, critically evaluate all perspectives, and ensure each decision advances better outcomes.""" response = llm.invoke(prompt) new_risk_debate_state = { "judge_decision": response.content, "history": risk_debate_state["history"], "aggressive_history": risk_debate_state["aggressive_history"], "conservative_history": risk_debate_state["conservative_history"], "neutral_history": risk_debate_state["neutral_history"], "latest_speaker": "Judge", "current_aggressive_response": risk_debate_state["current_aggressive_response"], "current_conservative_response": risk_debate_state["current_conservative_response"], "current_neutral_response": risk_debate_state["current_neutral_response"], "count": risk_debate_state["count"], } return { "risk_debate_state": new_risk_debate_state, "final_trade_decision": response.content, } return risk_manager_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/managers/risk_manager.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/researchers/bear_researcher.py
from langchain_core.messages import AIMessage import time import json def create_bear_researcher(llm, memory): def bear_node(state) -> dict: investment_debate_state = state["investment_debate_state"] history = investment_debate_state.get("history", "") bear_history = investment_debate_state.get("bear_history", "") current_response = investment_debate_state.get("current_response", "") market_research_report = state["market_report"] sentiment_report = state["sentiment_report"] news_report = state["news_report"] fundamentals_report = state["fundamentals_report"] curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for i, rec in enumerate(past_memories, 1): past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""You are a Bear Analyst making the case against investing in the stock. Your goal is to present a well-reasoned argument emphasizing risks, challenges, and negative indicators. Leverage the provided research and data to highlight potential downsides and counter bullish arguments effectively. Key points to focus on: - Risks and Challenges: Highlight factors like market saturation, financial instability, or macroeconomic threats that could hinder the stock's performance. - Competitive Weaknesses: Emphasize vulnerabilities such as weaker market positioning, declining innovation, or threats from competitors. - Negative Indicators: Use evidence from financial data, market trends, or recent adverse news to support your position. - Bull Counterpoints: Critically analyze the bull argument with specific data and sound reasoning, exposing weaknesses or over-optimistic assumptions. - Engagement: Present your argument in a conversational style, directly engaging with the bull analyst's points and debating effectively rather than simply listing facts. Resources available: Market research report: {market_research_report} Social media sentiment report: {sentiment_report} Latest world affairs news: {news_report} Company fundamentals report: {fundamentals_report} Conversation history of the debate: {history} Last bull argument: {current_response} Reflections from similar situations and lessons learned: {past_memory_str} Use this information to deliver a compelling bear argument, refute the bull's claims, and engage in a dynamic debate that demonstrates the risks and weaknesses of investing in the stock. You must also address reflections and learn from lessons and mistakes you made in the past. """ response = llm.invoke(prompt) argument = f"Bear Analyst: {response.content}" new_investment_debate_state = { "history": history + "\n" + argument, "bear_history": bear_history + "\n" + argument, "bull_history": investment_debate_state.get("bull_history", ""), "current_response": argument, "count": investment_debate_state["count"] + 1, } return {"investment_debate_state": new_investment_debate_state} return bear_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/researchers/bear_researcher.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/researchers/bull_researcher.py
from langchain_core.messages import AIMessage import time import json def create_bull_researcher(llm, memory): def bull_node(state) -> dict: investment_debate_state = state["investment_debate_state"] history = investment_debate_state.get("history", "") bull_history = investment_debate_state.get("bull_history", "") current_response = investment_debate_state.get("current_response", "") market_research_report = state["market_report"] sentiment_report = state["sentiment_report"] news_report = state["news_report"] fundamentals_report = state["fundamentals_report"] curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" for i, rec in enumerate(past_memories, 1): past_memory_str += rec["recommendation"] + "\n\n" prompt = f"""You are a Bull Analyst advocating for investing in the stock. Your task is to build a strong, evidence-based case emphasizing growth potential, competitive advantages, and positive market indicators. Leverage the provided research and data to address concerns and counter bearish arguments effectively. Key points to focus on: - Growth Potential: Highlight the company's market opportunities, revenue projections, and scalability. - Competitive Advantages: Emphasize factors like unique products, strong branding, or dominant market positioning. - Positive Indicators: Use financial health, industry trends, and recent positive news as evidence. - Bear Counterpoints: Critically analyze the bear argument with specific data and sound reasoning, addressing concerns thoroughly and showing why the bull perspective holds stronger merit. - Engagement: Present your argument in a conversational style, engaging directly with the bear analyst's points and debating effectively rather than just listing data. Resources available: Market research report: {market_research_report} Social media sentiment report: {sentiment_report} Latest world affairs news: {news_report} Company fundamentals report: {fundamentals_report} Conversation history of the debate: {history} Last bear argument: {current_response} Reflections from similar situations and lessons learned: {past_memory_str} Use this information to deliver a compelling bull argument, refute the bear's concerns, and engage in a dynamic debate that demonstrates the strengths of the bull position. You must also address reflections and learn from lessons and mistakes you made in the past. """ response = llm.invoke(prompt) argument = f"Bull Analyst: {response.content}" new_investment_debate_state = { "history": history + "\n" + argument, "bull_history": bull_history + "\n" + argument, "bear_history": investment_debate_state.get("bear_history", ""), "current_response": argument, "count": investment_debate_state["count"] + 1, } return {"investment_debate_state": new_investment_debate_state} return bull_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/researchers/bull_researcher.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/risk_mgmt/conservative_debator.py
from langchain_core.messages import AIMessage import time import json def create_conservative_debator(llm): def conservative_node(state) -> dict: risk_debate_state = state["risk_debate_state"] history = risk_debate_state.get("history", "") conservative_history = risk_debate_state.get("conservative_history", "") current_aggressive_response = risk_debate_state.get("current_aggressive_response", "") current_neutral_response = risk_debate_state.get("current_neutral_response", "") market_research_report = state["market_report"] sentiment_report = state["sentiment_report"] news_report = state["news_report"] fundamentals_report = state["fundamentals_report"] trader_decision = state["trader_investment_plan"] prompt = f"""As the Conservative Risk Analyst, your primary objective is to protect assets, minimize volatility, and ensure steady, reliable growth. You prioritize stability, security, and risk mitigation, carefully assessing potential losses, economic downturns, and market volatility. When evaluating the trader's decision or plan, critically examine high-risk elements, pointing out where the decision may expose the firm to undue risk and where more cautious alternatives could secure long-term gains. Here is the trader's decision: {trader_decision} Your task is to actively counter the arguments of the Aggressive and Neutral Analysts, highlighting where their views may overlook potential threats or fail to prioritize sustainability. Respond directly to their points, drawing from the following data sources to build a convincing case for a low-risk approach adjustment to the trader's decision: Market Research Report: {market_research_report} Social Media Sentiment Report: {sentiment_report} Latest World Affairs Report: {news_report} Company Fundamentals Report: {fundamentals_report} Here is the current conversation history: {history} Here is the last response from the aggressive analyst: {current_aggressive_response} Here is the last response from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints, do not hallucinate and just present your point. Engage by questioning their optimism and emphasizing the potential downsides they may have overlooked. Address each of their counterpoints to showcase why a conservative stance is ultimately the safest path for the firm's assets. Focus on debating and critiquing their arguments to demonstrate the strength of a low-risk strategy over their approaches. Output conversationally as if you are speaking without any special formatting.""" response = llm.invoke(prompt) argument = f"Conservative Analyst: {response.content}" new_risk_debate_state = { "history": history + "\n" + argument, "aggressive_history": risk_debate_state.get("aggressive_history", ""), "conservative_history": conservative_history + "\n" + argument, "neutral_history": risk_debate_state.get("neutral_history", ""), "latest_speaker": "Conservative", "current_aggressive_response": risk_debate_state.get( "current_aggressive_response", "" ), "current_conservative_response": argument, "current_neutral_response": risk_debate_state.get( "current_neutral_response", "" ), "count": risk_debate_state["count"] + 1, } return {"risk_debate_state": new_risk_debate_state} return conservative_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/risk_mgmt/conservative_debator.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/risk_mgmt/neutral_debator.py
import time import json def create_neutral_debator(llm): def neutral_node(state) -> dict: risk_debate_state = state["risk_debate_state"] history = risk_debate_state.get("history", "") neutral_history = risk_debate_state.get("neutral_history", "") current_aggressive_response = risk_debate_state.get("current_aggressive_response", "") current_conservative_response = risk_debate_state.get("current_conservative_response", "") market_research_report = state["market_report"] sentiment_report = state["sentiment_report"] news_report = state["news_report"] fundamentals_report = state["fundamentals_report"] trader_decision = state["trader_investment_plan"] prompt = f"""As the Neutral Risk Analyst, your role is to provide a balanced perspective, weighing both the potential benefits and risks of the trader's decision or plan. You prioritize a well-rounded approach, evaluating the upsides and downsides while factoring in broader market trends, potential economic shifts, and diversification strategies.Here is the trader's decision: {trader_decision} Your task is to challenge both the Aggressive and Conservative Analysts, pointing out where each perspective may be overly optimistic or overly cautious. Use insights from the following data sources to support a moderate, sustainable strategy to adjust the trader's decision: Market Research Report: {market_research_report} Social Media Sentiment Report: {sentiment_report} Latest World Affairs Report: {news_report} Company Fundamentals Report: {fundamentals_report} Here is the current conversation history: {history} Here is the last response from the aggressive analyst: {current_aggressive_response} Here is the last response from the conservative analyst: {current_conservative_response}. If there are no responses from the other viewpoints, do not hallucinate and just present your point. Engage actively by analyzing both sides critically, addressing weaknesses in the aggressive and conservative arguments to advocate for a more balanced approach. Challenge each of their points to illustrate why a moderate risk strategy might offer the best of both worlds, providing growth potential while safeguarding against extreme volatility. Focus on debating rather than simply presenting data, aiming to show that a balanced view can lead to the most reliable outcomes. Output conversationally as if you are speaking without any special formatting.""" response = llm.invoke(prompt) argument = f"Neutral Analyst: {response.content}" new_risk_debate_state = { "history": history + "\n" + argument, "aggressive_history": risk_debate_state.get("aggressive_history", ""), "conservative_history": risk_debate_state.get("conservative_history", ""), "neutral_history": neutral_history + "\n" + argument, "latest_speaker": "Neutral", "current_aggressive_response": risk_debate_state.get( "current_aggressive_response", "" ), "current_conservative_response": risk_debate_state.get("current_conservative_response", ""), "current_neutral_response": argument, "count": risk_debate_state["count"] + 1, } return {"risk_debate_state": new_risk_debate_state} return neutral_node
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/risk_mgmt/neutral_debator.py", "license": "Apache License 2.0", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/trader/trader.py
import functools import time import json def create_trader(llm, memory): def trader_node(state, name): company_name = state["company_of_interest"] investment_plan = state["investment_plan"] market_research_report = state["market_report"] sentiment_report = state["sentiment_report"] news_report = state["news_report"] fundamentals_report = state["fundamentals_report"] curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}" past_memories = memory.get_memories(curr_situation, n_matches=2) past_memory_str = "" if past_memories: for i, rec in enumerate(past_memories, 1): past_memory_str += rec["recommendation"] + "\n\n" else: past_memory_str = "No past memories found." context = { "role": "user", "content": f"Based on a comprehensive analysis by a team of analysts, here is an investment plan tailored for {company_name}. This plan incorporates insights from current technical market trends, macroeconomic indicators, and social media sentiment. Use this plan as a foundation for evaluating your next trading decision.\n\nProposed Investment Plan: {investment_plan}\n\nLeverage these insights to make an informed and strategic decision.", } messages = [ { "role": "system", "content": f"""You are a trading agent analyzing market data to make investment decisions. Based on your analysis, provide a specific recommendation to buy, sell, or hold. End with a firm decision and always conclude your response with 'FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**' to confirm your recommendation. Do not forget to utilize lessons from past decisions to learn from your mistakes. Here is some reflections from similar situatiosn you traded in and the lessons learned: {past_memory_str}""", }, context, ] result = llm.invoke(messages) return { "messages": [result], "trader_investment_plan": result.content, "sender": name, } return functools.partial(trader_node, name="Trader")
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/trader/trader.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/utils/agent_states.py
from typing import Annotated, Sequence from datetime import date, timedelta, datetime from typing_extensions import TypedDict, Optional from langchain_openai import ChatOpenAI from tradingagents.agents import * from langgraph.prebuilt import ToolNode from langgraph.graph import END, StateGraph, START, MessagesState # Researcher team state class InvestDebateState(TypedDict): bull_history: Annotated[ str, "Bullish Conversation history" ] # Bullish Conversation history bear_history: Annotated[ str, "Bearish Conversation history" ] # Bullish Conversation history history: Annotated[str, "Conversation history"] # Conversation history current_response: Annotated[str, "Latest response"] # Last response judge_decision: Annotated[str, "Final judge decision"] # Last response count: Annotated[int, "Length of the current conversation"] # Conversation length # Risk management team state class RiskDebateState(TypedDict): aggressive_history: Annotated[ str, "Aggressive Agent's Conversation history" ] # Conversation history conservative_history: Annotated[ str, "Conservative Agent's Conversation history" ] # Conversation history neutral_history: Annotated[ str, "Neutral Agent's Conversation history" ] # Conversation history history: Annotated[str, "Conversation history"] # Conversation history latest_speaker: Annotated[str, "Analyst that spoke last"] current_aggressive_response: Annotated[ str, "Latest response by the aggressive analyst" ] # Last response current_conservative_response: Annotated[ str, "Latest response by the conservative analyst" ] # Last response current_neutral_response: Annotated[ str, "Latest response by the neutral analyst" ] # Last response judge_decision: Annotated[str, "Judge's decision"] count: Annotated[int, "Length of the current conversation"] # Conversation length class AgentState(MessagesState): company_of_interest: Annotated[str, "Company that we are interested in trading"] trade_date: Annotated[str, "What date we are trading at"] sender: Annotated[str, "Agent that sent this message"] # research step market_report: Annotated[str, "Report from the Market Analyst"] sentiment_report: Annotated[str, "Report from the Social Media Analyst"] news_report: Annotated[ str, "Report from the News Researcher of current world affairs" ] fundamentals_report: Annotated[str, "Report from the Fundamentals Researcher"] # researcher team discussion step investment_debate_state: Annotated[ InvestDebateState, "Current state of the debate on if to invest or not" ] investment_plan: Annotated[str, "Plan generated by the Analyst"] trader_investment_plan: Annotated[str, "Plan generated by the Trader"] # risk management team discussion step risk_debate_state: Annotated[ RiskDebateState, "Current state of the debate on evaluating risk" ] final_trade_decision: Annotated[str, "Final decision made by the Risk Analysts"]
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/utils/agent_states.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/utils/agent_utils.py
from langchain_core.messages import HumanMessage, RemoveMessage # Import tools from separate utility files from tradingagents.agents.utils.core_stock_tools import ( get_stock_data ) from tradingagents.agents.utils.technical_indicators_tools import ( get_indicators ) from tradingagents.agents.utils.fundamental_data_tools import ( get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement ) from tradingagents.agents.utils.news_data_tools import ( get_news, get_insider_transactions, get_global_news ) def create_msg_delete(): def delete_messages(state): """Clear messages and add placeholder for Anthropic compatibility""" messages = state["messages"] # Remove all messages removal_operations = [RemoveMessage(id=m.id) for m in messages] # Add a minimal placeholder message placeholder = HumanMessage(content="Continue") return {"messages": removal_operations + [placeholder]} return delete_messages
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/utils/agent_utils.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/agents/utils/memory.py
"""Financial situation memory using BM25 for lexical similarity matching. Uses BM25 (Best Matching 25) algorithm for retrieval - no API calls, no token limits, works offline with any LLM provider. """ from rank_bm25 import BM25Okapi from typing import List, Tuple import re class FinancialSituationMemory: """Memory system for storing and retrieving financial situations using BM25.""" def __init__(self, name: str, config: dict = None): """Initialize the memory system. Args: name: Name identifier for this memory instance config: Configuration dict (kept for API compatibility, not used for BM25) """ self.name = name self.documents: List[str] = [] self.recommendations: List[str] = [] self.bm25 = None def _tokenize(self, text: str) -> List[str]: """Tokenize text for BM25 indexing. Simple whitespace + punctuation tokenization with lowercasing. """ # Lowercase and split on non-alphanumeric characters tokens = re.findall(r'\b\w+\b', text.lower()) return tokens def _rebuild_index(self): """Rebuild the BM25 index after adding documents.""" if self.documents: tokenized_docs = [self._tokenize(doc) for doc in self.documents] self.bm25 = BM25Okapi(tokenized_docs) else: self.bm25 = None def add_situations(self, situations_and_advice: List[Tuple[str, str]]): """Add financial situations and their corresponding advice. Args: situations_and_advice: List of tuples (situation, recommendation) """ for situation, recommendation in situations_and_advice: self.documents.append(situation) self.recommendations.append(recommendation) # Rebuild BM25 index with new documents self._rebuild_index() def get_memories(self, current_situation: str, n_matches: int = 1) -> List[dict]: """Find matching recommendations using BM25 similarity. Args: current_situation: The current financial situation to match against n_matches: Number of top matches to return Returns: List of dicts with matched_situation, recommendation, and similarity_score """ if not self.documents or self.bm25 is None: return [] # Tokenize query query_tokens = self._tokenize(current_situation) # Get BM25 scores for all documents scores = self.bm25.get_scores(query_tokens) # Get top-n indices sorted by score (descending) top_indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:n_matches] # Build results results = [] max_score = max(scores) if max(scores) > 0 else 1 # Normalize scores for idx in top_indices: # Normalize score to 0-1 range for consistency normalized_score = scores[idx] / max_score if max_score > 0 else 0 results.append({ "matched_situation": self.documents[idx], "recommendation": self.recommendations[idx], "similarity_score": normalized_score, }) return results def clear(self): """Clear all stored memories.""" self.documents = [] self.recommendations = [] self.bm25 = None if __name__ == "__main__": # Example usage matcher = FinancialSituationMemory("test_memory") # Example data example_data = [ ( "High inflation rate with rising interest rates and declining consumer spending", "Consider defensive sectors like consumer staples and utilities. Review fixed-income portfolio duration.", ), ( "Tech sector showing high volatility with increasing institutional selling pressure", "Reduce exposure to high-growth tech stocks. Look for value opportunities in established tech companies with strong cash flows.", ), ( "Strong dollar affecting emerging markets with increasing forex volatility", "Hedge currency exposure in international positions. Consider reducing allocation to emerging market debt.", ), ( "Market showing signs of sector rotation with rising yields", "Rebalance portfolio to maintain target allocations. Consider increasing exposure to sectors benefiting from higher rates.", ), ] # Add the example situations and recommendations matcher.add_situations(example_data) # Example query current_situation = """ Market showing increased volatility in tech sector, with institutional investors reducing positions and rising interest rates affecting growth stock valuations """ try: recommendations = matcher.get_memories(current_situation, n_matches=2) for i, rec in enumerate(recommendations, 1): print(f"\nMatch {i}:") print(f"Similarity Score: {rec['similarity_score']:.2f}") print(f"Matched Situation: {rec['matched_situation']}") print(f"Recommendation: {rec['recommendation']}") except Exception as e: print(f"Error during recommendation: {str(e)}")
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/agents/utils/memory.py", "license": "Apache License 2.0", "lines": 114, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
TauricResearch/TradingAgents:tradingagents/dataflows/config.py
import tradingagents.default_config as default_config from typing import Dict, Optional # Use default config but allow it to be overridden _config: Optional[Dict] = None def initialize_config(): """Initialize the configuration with default values.""" global _config if _config is None: _config = default_config.DEFAULT_CONFIG.copy() def set_config(config: Dict): """Update the configuration with custom values.""" global _config if _config is None: _config = default_config.DEFAULT_CONFIG.copy() _config.update(config) def get_config() -> Dict: """Get the current configuration.""" if _config is None: initialize_config() return _config.copy() # Initialize with default config initialize_config()
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/config.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
TauricResearch/TradingAgents:tradingagents/dataflows/interface.py
from typing import Annotated # Import from vendor-specific modules from .y_finance import ( get_YFin_data_online, get_stock_stats_indicators_window, get_fundamentals as get_yfinance_fundamentals, get_balance_sheet as get_yfinance_balance_sheet, get_cashflow as get_yfinance_cashflow, get_income_statement as get_yfinance_income_statement, get_insider_transactions as get_yfinance_insider_transactions, ) from .yfinance_news import get_news_yfinance, get_global_news_yfinance from .alpha_vantage import ( get_stock as get_alpha_vantage_stock, get_indicator as get_alpha_vantage_indicator, get_fundamentals as get_alpha_vantage_fundamentals, get_balance_sheet as get_alpha_vantage_balance_sheet, get_cashflow as get_alpha_vantage_cashflow, get_income_statement as get_alpha_vantage_income_statement, get_insider_transactions as get_alpha_vantage_insider_transactions, get_news as get_alpha_vantage_news, get_global_news as get_alpha_vantage_global_news, ) from .alpha_vantage_common import AlphaVantageRateLimitError # Configuration and routing logic from .config import get_config # Tools organized by category TOOLS_CATEGORIES = { "core_stock_apis": { "description": "OHLCV stock price data", "tools": [ "get_stock_data" ] }, "technical_indicators": { "description": "Technical analysis indicators", "tools": [ "get_indicators" ] }, "fundamental_data": { "description": "Company fundamentals", "tools": [ "get_fundamentals", "get_balance_sheet", "get_cashflow", "get_income_statement" ] }, "news_data": { "description": "News and insider data", "tools": [ "get_news", "get_global_news", "get_insider_transactions", ] } } VENDOR_LIST = [ "yfinance", "alpha_vantage", ] # Mapping of methods to their vendor-specific implementations VENDOR_METHODS = { # core_stock_apis "get_stock_data": { "alpha_vantage": get_alpha_vantage_stock, "yfinance": get_YFin_data_online, }, # technical_indicators "get_indicators": { "alpha_vantage": get_alpha_vantage_indicator, "yfinance": get_stock_stats_indicators_window, }, # fundamental_data "get_fundamentals": { "alpha_vantage": get_alpha_vantage_fundamentals, "yfinance": get_yfinance_fundamentals, }, "get_balance_sheet": { "alpha_vantage": get_alpha_vantage_balance_sheet, "yfinance": get_yfinance_balance_sheet, }, "get_cashflow": { "alpha_vantage": get_alpha_vantage_cashflow, "yfinance": get_yfinance_cashflow, }, "get_income_statement": { "alpha_vantage": get_alpha_vantage_income_statement, "yfinance": get_yfinance_income_statement, }, # news_data "get_news": { "alpha_vantage": get_alpha_vantage_news, "yfinance": get_news_yfinance, }, "get_global_news": { "yfinance": get_global_news_yfinance, "alpha_vantage": get_alpha_vantage_global_news, }, "get_insider_transactions": { "alpha_vantage": get_alpha_vantage_insider_transactions, "yfinance": get_yfinance_insider_transactions, }, } def get_category_for_method(method: str) -> str: """Get the category that contains the specified method.""" for category, info in TOOLS_CATEGORIES.items(): if method in info["tools"]: return category raise ValueError(f"Method '{method}' not found in any category") def get_vendor(category: str, method: str = None) -> str: """Get the configured vendor for a data category or specific tool method. Tool-level configuration takes precedence over category-level. """ config = get_config() # Check tool-level configuration first (if method provided) if method: tool_vendors = config.get("tool_vendors", {}) if method in tool_vendors: return tool_vendors[method] # Fall back to category-level configuration return config.get("data_vendors", {}).get(category, "default") def route_to_vendor(method: str, *args, **kwargs): """Route method calls to appropriate vendor implementation with fallback support.""" category = get_category_for_method(method) vendor_config = get_vendor(category, method) primary_vendors = [v.strip() for v in vendor_config.split(',')] if method not in VENDOR_METHODS: raise ValueError(f"Method '{method}' not supported") # Build fallback chain: primary vendors first, then remaining available vendors all_available_vendors = list(VENDOR_METHODS[method].keys()) fallback_vendors = primary_vendors.copy() for vendor in all_available_vendors: if vendor not in fallback_vendors: fallback_vendors.append(vendor) for vendor in fallback_vendors: if vendor not in VENDOR_METHODS[method]: continue vendor_impl = VENDOR_METHODS[method][vendor] impl_func = vendor_impl[0] if isinstance(vendor_impl, list) else vendor_impl try: return impl_func(*args, **kwargs) except AlphaVantageRateLimitError: continue # Only rate limits trigger fallback raise RuntimeError(f"No available vendor for '{method}'")
{ "repo_id": "TauricResearch/TradingAgents", "file_path": "tradingagents/dataflows/interface.py", "license": "Apache License 2.0", "lines": 146, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex