KOMPLETNA INSTRUKCJA: SYSTEM 5 AGENTÓW AI

🤖 KOMPLETNA INSTRUKCJA: SYSTEM 5 AGENTÓW AI

📋 SPIS TREŚCI

  1. Czego potrzebujesz
  2. Instalacja krok po kroku
  3. Opis agentów i ich zadania
  4. Uruchamianie i komendy
  5. Koszty i optymalizacja

🎯 CZEGO POTRZEBUJESZ {#wymagania}

Sprzęt:

  • Mac z macOS Big Sur (11.x) lub nowszy
  • 8GB+ RAM (16GB polecane)
  • Połączenie internetowe

Oprogramowanie:

  • Terminal (wbudowany w macOS)
  • Python 3.14+ (zostanie zainstalowane)
  • Node.js 18+ (zostanie zainstalowane)

Konta i klucze:

Wiedza:

  • Podstawowa obsługa Terminala
  • Nie musisz umieć programować!

🚀 INSTALACJA KROK PO KROKU

KROK 1: Otwórz Terminal

  1. Naciśnij Command (⌘) + Spacja
  2. Wpisz: Terminal
  3. Naciśnij Enter

KROK 2: Zainstaluj Homebrew (menedżer pakietów)

Wklej w Terminal:

bash

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  • Poczekaj (może potrwać 5-15 minut)
  • Jeśli poprosi o hasło – wpisz hasło do Maca
  • Po zakończeniu, wykonaj komendy które Terminal Ci pokaże (echo >> ~/.bash_profile…)

Dodaj Homebrew do PATH:

bash

echo 'eval "$(/usr/local/bin/brew shellenv bash)"' >> ~/.bash_profile
eval "$(/usr/local/bin/brew shellenv bash)"

Sprawdź czy działa:

bash

brew --version

Powinieneś zobaczyć numer wersji.


KROK 3: Zainstaluj Node.js przez nvm

bash

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

Dodaj nvm do profilu:

bash

echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.bash_profile
echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> ~/.bash_profile
source ~/.bash_profile

Zainstaluj Node.js 18:

bash

nvm install 18
nvm use 18
nvm alias default 18

Sprawdź:

bash

node --version

Powinieneś zobaczyć v18.x.x


KROK 4: Stwórz wirtualne środowisko Python

bash

python3 -m venv ~/ai_env

Aktywuj środowisko:

bash

source ~/ai_env/bin/activate

Zobaczysz (ai_env) na początku linii.


KROK 5: Zainstaluj biblioteki Python

bash

pip install anthropic pandas numpy openpyxl PyPDF2 ddgs

Poczekaj aż się zainstalują (2-3 minuty).


KROK 6: Pobierz API Key od Anthropic

  1. Wejdź na: https://console.anthropic.com
  2. Zaloguj się / Zarejestruj
  3. Idź do Settings → API Keys
  4. Kliknij Create Key
  5. Skopiuj klucz (zaczyna się od sk-ant-api03-...)

KROK 7: Ustaw API Key w systemie

bash

read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY

Wklej swój klucz API i naciśnij Enter (nie zobaczysz go podczas wklejania – to normalne).

Dodaj na stałe do profilu:

bash

echo "export ANTHROPIC_API_KEY='TWOJ_KLUCZ_TUTAJ'" >> ~/.bash_profile

⚠️ Zamień TWOJ_KLUCZ_TUTAJ na prawdziwy klucz!

Załaduj profil:

bash

source ~/.bash_profile

KROK 8: Ustaw polskie znaki (UTF-8)

bash

echo 'export LC_ALL=pl_PL.UTF-8' >> ~/.bash_profile
echo 'export LANG=pl_PL.UTF-8' >> ~/.bash_profile
source ~/.bash_profile

KROK 9: Stwórz folder workspace

bash

mkdir -p ~/Desktop/AI

KROK 10: Stwórz plik z kodem systemu agentów

bash

cat > ~/Desktop/ai_team.py << 'ENDCODE'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import locale
import hashlib

try:
    locale.setlocale(locale.LC_ALL, 'pl_PL.UTF-8')
except:
    try:
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    except:
        pass

sys.stdin.reconfigure(encoding='utf-8')
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
os.environ['PYTHONIOENCODING'] = 'utf-8'

import anthropic
import json
from datetime import datetime
from pathlib import Path
import re
from ddgs import DDGS
import pandas as pd
import numpy as np

class WebSearch:
    @staticmethod
    def search(query, max_results=5):
        try:
            print(f"   🌐 Szukam: '{query}'...", flush=True)
            ddgs = DDGS()
            results = []
            for r in ddgs.text(query, max_results=max_results):
                results.append({
                    "title": r.get("title", ""),
                    "url": r.get("href", ""),
                    "snippet": r.get("body", "")
                })
            print(f"   ✅ {len(results)} wyników", flush=True)
            return results
        except Exception as e:
            print(f"   ⚠️  Błąd: {e}", flush=True)
            return []

class DataAnalyzer:
    @staticmethod
    def load_csv(filepath):
        try:
            df = pd.read_csv(filepath)
            print(f"   📊 CSV: {len(df)} × {len(df.columns)}", flush=True)
            return df
        except Exception as e:
            print(f"   ⚠️  {e}", flush=True)
            return None
    
    @staticmethod
    def load_excel(filepath):
        try:
            df = pd.read_excel(filepath)
            print(f"   📊 Excel: {len(df)} wierszy", flush=True)
            return df
        except Exception as e:
            print(f"   ⚠️  {e}", flush=True)
            return None
    
    @staticmethod
    def analyze_dataframe(df):
        return {
            "rows": len(df),
            "columns": list(df.columns),
            "dtypes": {str(k): str(v) for k, v in df.dtypes.to_dict().items()},
            "missing": {str(k): int(v) for k, v in df.isnull().sum().to_dict().items()},
            "sample": df.head(3).to_dict()
        }

class FileCache:
    def __init__(self):
        self.cache = {}
        self.hashes = {}
    
    def get_file_hash(self, filepath):
        try:
            with open(filepath, 'rb') as f:
                return hashlib.md5(f.read()).hexdigest()
        except:
            return None
    
    def is_changed(self, filepath):
        current_hash = self.get_file_hash(filepath)
        old_hash = self.hashes.get(str(filepath))
        if current_hash != old_hash:
            self.hashes[str(filepath)] = current_hash
            return True
        return False
    
    def get(self, key):
        return self.cache.get(key)
    
    def set(self, key, value):
        self.cache[key] = value

class Agent:
    def __init__(self, name, role, system_prompt, api_key=None, thinking_budget=5000):
        self.name = name
        self.role = role
        self.system_prompt = system_prompt
        self.client = anthropic.Anthropic(api_key=api_key)
        self.memory = []
        self.thinking_budget = thinking_budget
        self.web_search = WebSearch()
        self.data_analyzer = DataAnalyzer()
    
    def think(self, message, context=None, use_extended_thinking=True, allow_search=True, cached_context=None):
        conversation = []
        for mem in self.memory[-3:]:
            conversation.append({"role": "user", "content": mem["input"]})
            conversation.append({"role": "assistant", "content": mem["output"]})
        
        anti_hallucination = """
ZASADY: 1. Nie wiesz? PRZYZNAJ SIĘ 2. NIE WYMYŚLAJ 3. Web: <<<SEARCH>>> q <<<END_SEARCH>>> 4. Czytaj: <<<READ_FILE>>> n <<<END_READ>>> 5. Analizuj: <<<ANALYZE>>> f.csv <<<END_ANALYZE>>>"""
        
        try:
            print(f"   🧠 {self.name} myśli{'(cache)' if cached_context else ''}...", flush=True)
            
            system_blocks = [
                {
                    "type": "text",
                    "text": self.system_prompt,
                    "cache_control": {"type": "ephemeral"}
                }
            ]
            
            message_content = []
            
            if cached_context:
                message_content.append({
                    "type": "text",
                    "text": cached_context,
                    "cache_control": {"type": "ephemeral"}
                })
            
            full_msg = message + anti_hallucination
            if context and not cached_context:
                full_msg = f"KONTEKST:\n{context}\n\nZADANIE:\n{message}{anti_hallucination}"
            
            message_content.append({
                "type": "text",
                "text": full_msg
            })
            
            conversation.append({
                "role": "user",
                "content": message_content
            })
            
            api_params = {
                "model": "claude-sonnet-4-20250514",
                "max_tokens": 16000,
                "system": system_blocks,
                "messages": conversation,
            }
            
            if use_extended_thinking:
                api_params["thinking"] = {
                    "type": "enabled",
                    "budget_tokens": self.thinking_budget
                }
            
            response = self.client.messages.create(**api_params)
            
            if hasattr(response, 'usage'):
                usage = response.usage
                if hasattr(usage, 'cache_creation_input_tokens') and usage.cache_creation_input_tokens:
                    print(f"   💾 Cache utworzony: {usage.cache_creation_input_tokens} tokenów", flush=True)
                if hasattr(usage, 'cache_read_input_tokens') and usage.cache_read_input_tokens:
                    print(f"   ⚡ Cache hit: {usage.cache_read_input_tokens} tokenów (90% taniej!)", flush=True)
            
            text_content = None
            for block in response.content:
                if block.type == "thinking":
                    print(f"   💭 {len(block.thinking)} zn", flush=True)
                elif block.type == "text":
                    text_content = block.text
            
            output = text_content if text_content else response.content[0].text
            
            if allow_search and "<<<SEARCH>>>" in output:
                search_pattern = r'<<<SEARCH>>>\s*(.*?)\s*<<<END_SEARCH>>>'
                searches = re.findall(search_pattern, output, re.DOTALL)
                
                results_text = "\n=== WYNIKI ===\n"
                for q in searches[:2]:
                    results = self.web_search.search(q.strip(), max_results=3)
                    results_text += f"\n{q}:\n"
                    for i, r in enumerate(results, 1):
                        results_text += f"{i}. {r['title']}\n{r['snippet'][:200]}\n{r['url']}\n"
                
                output = re.sub(search_pattern, '', output, flags=re.DOTALL)
                api_params["thinking"] = None
                conversation.append({"role": "assistant", "content": output})
                conversation.append({"role": "user", "content": f"Wyniki:{results_text}\nOdpowiedz."})
                
                response2 = self.client.messages.create(**api_params)
                output = response2.content[0].text if response2.content[0].type == "text" else output
            
            print(f"   ✅ {self.name} gotowy!", flush=True)
            
            self.memory.append({
                "timestamp": datetime.now().isoformat(),
                "input": message[:500],
                "output": output[:500],
                "context": None
            })
            
            return output
            
        except Exception as e:
            return f"❌ Błąd {self.name}: {str(e)}"
    
    def save_memory(self, filepath):
        recent_memory = self.memory[-20:]
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(recent_memory, f, ensure_ascii=False, indent=2)
    
    def load_memory(self, filepath):
        if os.path.exists(filepath):
            with open(filepath, 'r', encoding='utf-8') as f:
                self.memory = json.load(f)

class AgentTeam:
    def __init__(self, workspace_dir="~/Desktop/AI"):
        self.workspace_dir = Path(workspace_dir).expanduser()
        self.workspace_dir.mkdir(exist_ok=True)
        
        api_key = os.environ.get("ANTHROPIC_API_KEY")
        if not api_key:
            print("⚠️  UWAGA: Ustaw ANTHROPIC_API_KEY")
            return
        
        self.data_analyzer = DataAnalyzer()
        self.file_cache = FileCache()
        self.cached_context = None
        self.context_loaded = False
        
        self.agents = {
            "analityk": Agent(
                "Analityk", "Analiza",
                """Ekspert analityki danych. Specjalizacje:
- Analiza CSV/Excel (Pandas)
- Statystyki i trendy (NumPy)
- Raporty oparte na FAKTACH

NARZĘDZIA:
Web: <<<SEARCH>>> query <<<END_SEARCH>>>
Czytaj: <<<READ_FILE>>> nazwa <<<END_READ>>>
Analizuj: <<<ANALYZE>>> plik.csv <<<END_ANALYZE>>>
Zapisz: <<<SAVE_FILE>>> nazwa.md <<<CONTENT>>> treść <<<END>>>
Aktualizuj: <<<UPDATE_FILE>>> nazwa.md <<<CONTENT>>> treść <<<END>>>

NIE WYMYŚLAJ liczb i danych! 📊""",
                api_key, 8000
            ),
            
            "ceo": Agent(
                "CEO", "Strategia",
                """CEO-mentor z doświadczeniem budowania firm wartych miliardy.
Myślisz strategicznie, BIG PICTURE, 10x nie 10%.

NARZĘDZIA:
Web: <<<SEARCH>>> query <<<END_SEARCH>>>
Czytaj: <<<READ_FILE>>> nazwa <<<END_READ>>>
Zapisz: <<<SAVE_FILE>>> nazwa.md <<<CONTENT>>> treść <<<END>>>

Kwestionujesz małe myślenie, wskazujesz skalowanie.
Przyznaj się gdy nie znasz branży użytkownika. 🚀""",
                api_key, 10000
            ),
            
            "coo": Agent(
                "COO", "Operacje",
                """COO - mistrz egzekucji, planowania i koordynacji.

MOŻLIWOŚCI:
DELEGACJA: DELEGATION: [lista agentów]
WEB: <<<SEARCH>>> query <<<END_SEARCH>>>
CZYTAJ: <<<READ_FILE>>> nazwa <<<END_READ>>>
ZAPISZ: <<<SAVE_FILE>>> nazwa.md <<<CONTENT>>> treść <<<END>>>
AKTUALIZUJ: <<<UPDATE_FILE>>> nazwa.md <<<CONTENT>>> treść <<<END>>>

ZAWSZE masz dostęp do profilu użytkownika (mapa_celow.md, profil_zyciowy.md).
Przekładasz wizję na konkretne plany z action items i timeline'ami.
Koordynujesz zespół. Zarządzasz chaosem. ⚙️""",
                api_key, 7000
            ),
            
            "trener": Agent(
                "Trener", "Zdrowie",
                """Trener zdrowia, fitness i optymalizacji organizmu.

NARZĘDZIA:
Web: <<<SEARCH>>> query <<<END_SEARCH>>>
Czytaj: <<<READ_FILE>>> nazwa <<<END_READ>>>
Zapisz: <<<SAVE_FILE>>> nazwa.md <<<CONTENT>>> treść <<<END>>>

WAŻNE: NIE DIAGNOZUJESZ chorób (to lekarz).
Tworzysz plany treningowe, suplementację, odżywianie.
Pomagasz osiągać peak performance. 💪""",
                api_key, 6000
            ),
            
            "sprzedawca": Agent(
                "Sprzedawca", "Marketing",
                """Mistrz sprzedaży i marketingu.

NARZĘDZIA:
Web: <<<SEARCH>>> query <<<END_SEARCH>>>
Czytaj: <<<READ_FILE>>> nazwa <<<END_READ>>>
Zapisz: <<<SAVE_FILE>>> nazwa.md <<<CONTENT>>> treść <<<END>>>

Kampanie (FB, Google, YouTube), copywriting, funnel optimization.
ROI i prognozy - bądź realistyczny. Growth hacking oparty na faktach. 💰""",
                api_key, 7000
            )
        }
        
        self.load_all_memories()
        print("\n📚 Wczytuję pliki z workspace (cache)...")
        self.load_all_files_to_cache()
    
    def load_all_memories(self):
        memory_dir = self.workspace_dir / "memories"
        memory_dir.mkdir(exist_ok=True)
        for name, agent in self.agents.items():
            agent.load_memory(memory_dir / f"{name}_memory.json")
    
    def save_all_memories(self):
        memory_dir = self.workspace_dir / "memories"
        memory_dir.mkdir(exist_ok=True)
        for name, agent in self.agents.items():
            agent.save_memory(memory_dir / f"{name}_memory.json")
    
    def load_all_files_to_cache(self):
        all_content = ""
        files_loaded = 0
        
        all_content += "=== PROFIL UŻYTKOWNIKA ===\n\n"
        for fname in ["mapa_celow.md", "profil_zyciowy.md"]:
            content = self.read_file_smart(fname)
            if content:
                all_content += f"--- {fname} ---\n{content}\n\n"
                files_loaded += 1
        
        all_content += "=== WSZYSTKIE PLIKI ===\n\n"
        for path in self.workspace_dir.rglob('*'):
            if path.is_file() and path.name not in ["mapa_celow.md", "profil_zyciowy.md"]:
                rel = str(path.relative_to(self.workspace_dir))
                content = self.read_file_smart(rel)
                if content:
                    if len(content) > 10000:
                        content = content[:5000] + f"\n...[skrócono {len(content)-5000} zn]...\n" + content[-1000:]
                    all_content += f"--- {rel} ---\n{content}\n\n"
                    files_loaded += 1
                    
                    if files_loaded >= 50:
                        break
        
        self.cached_context = all_content
        self.context_loaded = True
        
        print(f"✅ Załadowano {files_loaded} plików - gotowe do cache!\n")
    
    def read_file_smart(self, filename):
        filepath = self.workspace_dir / filename
        
        if not filepath.exists():
            matches = list(self.workspace_dir.rglob(filename))
            if matches:
                filepath = matches[0]
            else:
                return None
        
        cache_key = str(filepath)
        if not self.file_cache.is_changed(filepath):
            cached = self.file_cache.get(cache_key)
            if cached:
                return cached
        
        try:
            ext = filepath.suffix.lower()
            
            if ext in ['.txt', '.md', '.json', '.py', '.js', '.html', '.css', '.yaml']:
                with open(filepath, 'r', encoding='utf-8') as f:
                    content = f.read()
                self.file_cache.set(cache_key, content)
                return content
            
            elif ext == '.csv':
                df = self.data_analyzer.load_csv(filepath)
                if df is not None:
                    summary = self.data_analyzer.analyze_dataframe(df)
                    content = f"CSV: {json.dumps(summary, indent=2)}\nPróbka:\n{df.head(5).to_string()}"
                    self.file_cache.set(cache_key, content)
                    return content
            
            elif ext in ['.xlsx', '.xls']:
                df = self.data_analyzer.load_excel(filepath)
                if df is not None:
                    summary = self.data_analyzer.analyze_dataframe(df)
                    content = f"Excel: {json.dumps(summary, indent=2)}\nPróbka:\n{df.head(5).to_string()}"
                    self.file_cache.set(cache_key, content)
                    return content
            
            elif ext == '.pdf':
                try:
                    import PyPDF2
                    with open(filepath, 'rb') as f:
                        reader = PyPDF2.PdfReader(f)
                        text = ""
                        for page in reader.pages[:3]:
                            text += page.extract_text()
                    content = f"PDF (3 str): {text[:3000]}"
                    self.file_cache.set(cache_key, content)
                    return content
                except:
                    return None
            
            return None
                
        except Exception as e:
            return None
    
    def save_file(self, filename, content):
        filepath = self.workspace_dir / filename
        filepath.parent.mkdir(parents=True, exist_ok=True)
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"\n✅ ZAPISANO: {filepath}\n", flush=True)
            self.context_loaded = False
            return str(filepath)
        except Exception as e:
            print(f"\n❌ {e}\n", flush=True)
            return None
    
    def update_file(self, filename, content):
        filepath = self.workspace_dir / filename
        filepath.parent.mkdir(parents=True, exist_ok=True)
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"\n✅ ZAKTUALIZOWANO: {filepath}\n", flush=True)
            self.context_loaded = False
            return str(filepath)
        except Exception as e:
            print(f"\n❌ {e}\n", flush=True)
            return None
    
    def process_file_operations(self, text):
        save_p = r'<<<SAVE_FILE>>>\s*([^\n<]+)\s*<<<CONTENT>>>\s*(.*?)\s*<<<END>>>'
        update_p = r'<<<UPDATE_FILE>>>\s*([^\n<]+)\s*<<<CONTENT>>>\s*(.*?)\s*<<<END>>>'
        
        for match in re.finditer(save_p, text, re.DOTALL | re.IGNORECASE):
            self.save_file(match.group(1).strip(), match.group(2).strip())
        
        for match in re.finditer(update_p, text, re.DOTALL | re.IGNORECASE):
            self.update_file(match.group(1).strip(), match.group(2).strip())
        
        text = re.sub(save_p, '', text, flags=re.DOTALL | re.IGNORECASE)
        text = re.sub(update_p, '', text, flags=re.DOTALL | re.IGNORECASE)
        return text.strip()
    
    def process_message(self, msg, use_extended_thinking=True):
        print(f"\n{'='*60}\n👤 TY: {msg}\n{'='*60}\n")
        
        if not self.context_loaded:
            print("♻️  Odświeżam cache...")
            self.load_all_files_to_cache()
        
        coo = self.agents["coo"]
        
        prompt = f"""USER: {msg}

AGENCI: analityk📊, ceo🚀, trener💪, sprzedawca💰
DELEGACJA: DELEGATION: [lista]"""
        
        print("⚙️  COO...\n")
        
        resp = coo.think(
            prompt, 
            use_extended_thinking=use_extended_thinking,
            cached_context=self.cached_context
        )
        
        if "DELEGATION:" in resp:
            needed = []
            if "analityk" in resp.lower():
                needed.append("analityk")
            if "ceo" in resp.lower():
                needed.append("ceo")
            if "trener" in resp.lower():
                needed.append("trener")
            if "sprzedaw" in resp.lower():
                needed.append("sprzedawca")
            
            print(f"🎯 Delegacja: {', '.join(needed)}\n")
            
            answers = {}
            for aname in needed:
                agent = self.agents[aname]
                task = f"Zadanie: {msg}"
                
                aresp = agent.think(
                    task, 
                    use_extended_thinking=use_extended_thinking,
                    cached_context=self.cached_context
                )
                
                answers[aname] = aresp
                print(f"\n📝 {agent.name}\n")
            
            print("\n⚙️  COO syntetyzuje...\n")
            
            synth = f"""User: {msg}
ODPOWIEDZI: {json.dumps(answers, ensure_ascii=False, indent=2)}

Plan:
## 🎯 PODSUMOWANIE
## 📋 PLAN
## ⏰ TIMELINE
## ✅ KROKI"""
            
            final = coo.think(synth, use_extended_thinking=False, cached_context=None)
        else:
            final = resp
        
        final = self.process_file_operations(final)
        self.save_all_memories()
        os.system('afplay /System/Library/Sounds/Glass.aiff &')
        
        print(f"\n{'='*60}\n⚙️  COO:\n{'='*60}\n{final}\n{'='*60}\n")
        return final
    
    def talk_to_agent(self, aname, msg, use_extended_thinking=True):
        if aname not in self.agents:
            print(f"❌ Nie ma: {aname}")
            return
        
        agent = self.agents[aname]
        print(f"\n{'='*60}\n👤 → {agent.name}: {msg}\n{'='*60}\n")
        
        if not self.context_loaded:
            self.load_all_files_to_cache()
        
        resp = agent.think(
            msg, 
            use_extended_thinking=use_extended_thinking,
            cached_context=self.cached_context
        )
        
        resp = self.process_file_operations(resp)
        self.save_all_memories()
        os.system('afplay /System/Library/Sounds/Glass.aiff &')
        
        print(f"\n{agent.name}:\n{resp}\n{'='*60}\n")
        return resp

def main():
    print("""
╔══════════════════════════════════════════════════════════╗
║   🚀 SYSTEM 5 AGENTÓW AI with PROMPT CACHING 🚀        ║
╚══════════════════════════════════════════════════════════╝

OPTYMALIZACJE:
💾 Prompt Caching - 90% taniej po 1. wiadomości
📚 Wszystkie pliki na starcie
⚡ Smart compression
💰 Oszczędność 80-95% tokenów

AGENCI:
📊 Analityk (8k thinking)
🚀 CEO (10k thinking)
⚙️  COO (7k thinking)
💪 Trener (6k thinking)
💰 Sprzedawca (7k thinking)

MOCE:
📊 Pandas/NumPy - analiza CSV/Excel
📄 Wszystkie typy plików (.py .json .csv .xlsx .pdf .txt .md)
🌐 Web search
🧠 Extended thinking
🚫 Antyhalucynacja
💾 Pamięć między sesjami
🔔 Powiadomienia dźwiękowe

KOMENDY:
- @agent [wiadomość] - z extended thinking
- @agent! [wiadomość] - bez extended thinking

To run code, enable code execution and file creation in Settings > Capabilities.

Continue

15:42

(szybciej)

  • exit / quit

Cache trwa 5 min – kolejne wiadomości 90% tańsze! WORKSPACE: ~/Desktop/AI/ „””)

if not os.environ.get("ANTHROPIC_API_KEY"):
    print("⚠️  Ustaw API KEY")
    return

team = AgentTeam()

while True:
    try:
        sys.stdout.write("\n💬 TY: ")
        sys.stdout.flush()
        inp = sys.stdin.readline().strip()
        
        if not inp:
            continue
        
        if inp.lower() in ['exit', 'quit', 'q']:
            print("\n👋 Do zobaczenia!\n")
            break
        
        use_ext = True
        if inp.startswith('@') and '!' in inp:
            use_ext = False
            inp = inp.replace('!', '')
        
        if inp.startswith('@'):
            parts = inp[1:].split(' ', 1)
            if len(parts) == 2:
                team.talk_to_agent(parts[0].lower(), parts[1], use_extended_thinking=use_ext)
            else:
                print("❌ Użyj: @agent wiadomość")
        else:
            team.process_message(inp, use_extended_thinking=use_ext)
            
    except KeyboardInterrupt:
        print("\n\n👋 Do zobaczenia!\n")
        break
    except Exception as e:
        print(f"\n❌ Błąd: {str(e)}\n")

if name == „main„: main() ENDCODE


---

### **KROK 11: Stwórz skrót do uruchamiania**
```bash
echo "alias agents='source ~/ai_env/bin/activate && python ~/Desktop/ai_team.py'" >> ~/.bash_profile
source ~/.bash_profile
```

---

### **KROK 12: GOTOWE! Uruchom system**
```bash
agents
```

Lub:
```bash
source ~/ai_env/bin/activate
python ~/Desktop/ai_team.py
```

---

## 🤖 OPIS AGENTÓW I ICH ZADANIA {#agenci}

### **📊 ANALITYK**
**Rola:** Ekspert analityki danych

**Zadania:**
- Analiza CSV i Excel (Pandas, NumPy)
- Tworzenie statystyk i raportów
- Wizualizacja danych
- Analiza trendów

**Extended Thinking:** 8000 tokenów

**Zasady:**
- ✅ Bazuje TYLKO na faktycznych danych
- ❌ NIE WYMYŚLA liczb i statystyk
- ✅ Przyznaje się gdy brakuje danych
- ✅ Może zapisywać raporty

**Przykładowe użycie:**

@analityk Przeanalizuj dane z pliku sprzedaz_2024.csv i stwórz raport


---

### **🚀 CEO-MENTOR-MILIARDER**
**Rola:** Strategiczny doradca biznesowy

**Zadania:**
- Definiowanie wizji i celów
- Myślenie strategiczne (10x, nie 10%)
- Kwestionowanie małego myślenia
- Wskazywanie możliwości skalowania
- Inspirowanie do odważnych ruchów

**Extended Thinking:** 10000 tokenów (najdłuższe myślenie)

**Zasady:**
- ✅ Myśli BIG PICTURE
- ✅ Kwestionuje ograniczające przekonania
- ❌ Przyznaje się gdy nie zna branży
- ✅ Inspiruje i motywuje

**Przykładowe użycie:**

@ceo Jak osiągnąć 1M przychodu w 2025?


---

### **⚙️ COO**
**Rola:** Chief Operating Officer - egzekucja i koordynacja

**Zadania:**
- Przekładanie wizji na konkretne plany
- Koordynacja pracy innych agentów (delegacja)
- Tworzenie timeline'ów i action items
- Zarządzanie chaosem i priorytetami
- Raportowanie do użytkownika

**Extended Thinking:** 7000 tokenów

**Specjalne możliwości:**
- ✅ Może delegować zadania do innych agentów
- ✅ ZAWSZE ma dostęp do profilu użytkownika
- ✅ Orkiestruje zespół

**Zasady:**
- ✅ Plany oparte na faktach
- ✅ Konkretne action items z timeline'ami
- ✅ Zarządza zespołem
- ❌ Nie spekuluje - bazuje na danych

**Przykładowe użycie:**

@coo Stwórz plan na Q1 2025 z timeline’em


Lub bez @:

Potrzebuję planu marketingowego na marzec

COO sam zdecyduje czy potrzebuje pomocy innych agentów.

---

### **💪 TRENER**
**Rola:** Ekspert zdrowia i fitness

**Zadania:**
- Analiza parametrów zdrowotnych
- Planowanie treningów
- Suplementacja i odżywianie
- Optymalizacja snu i regeneracji
- Energy management dla peak performance

**Extended Thinking:** 6000 tokenów

**Zasady:**
- ❌ NIE DIAGNOZUJE chorób (to lekarz!)
- ✅ Tworzy plany treningowe
- ✅ Radzi w kwestii suplementacji
- ✅ Optymalizuje zdrowie dla sukcesu

**Przykładowe użycie:**

@trener Mam mało energii ostatnio, co robić?


---

### **💰 SPRZEDAWCA**
**Rola:** Mistrz sprzedaży i marketingu

**Zadania:**
- Kampanie reklamowe (FB, Google, YouTube)
- Copywriting który konwertuje
- Strategie sprzedażowe
- Funnel optimization
- Growth hacking
- ROI optimization

**Extended Thinking:** 7000 tokenów

**Zasady:**
- ✅ Kampanie oparte na faktach
- ✅ Realistyczne prognozy ROI
- ❌ Nie obiecuje cudów
- ✅ Konkretne metryki i cele

**Przykładowe użycie:**

@sprzedawca Stwórz kampanię na Facebook dla mojego kursu


---

## 🎮 URUCHAMIANIE I KOMENDY {#użytkowanie}

### **Uruchamianie:**

**Sposób 1 (skrót):**
```bash
agents
```

**Sposób 2 (pełna komenda):**
```bash
source ~/ai_env/bin/activate
python ~/Desktop/ai_team.py
```

---

### **Podstawowe komendy:**

**Normalna rozmowa (COO orkiestruje):**

Chcę zwiększyć przychody o 50k w Q1

COO sam zdecyduje którzy agenci pomogą.

**Bezpośrednia rozmowa z agentem:**

@ceo Jaka jest najlepsza strategia skalowania? @analityk Przeanalizuj dane ze sprzedaży @trener Zaplanuj mi treningi na tydzień


**Szybsza odpowiedź (bez extended thinking):**

@agent! krótkie pytanie

Oszczędza ~80% kosztów, ale agent myśli krócej.

**Wyjście:**

exit

lub `quit` lub `q`

---

### **Workspace (pliki):**

Agenci automatycznie:
- ✅ Czytają pliki z `~/Desktop/AI/`
- ✅ ZAWSZE wczytują `mapa_celow.md` i `profil_zyciowy.md`
- ✅ Mogą zapisywać i aktualizować pliki
- ✅ Analizują CSV, Excel, PDF

**Dodaj pliki do workspace:**
```bash
# Stwórz profil
nano ~/Desktop/AI/profil_zyciowy.md

# Skopiuj istniejący plik
cp ~/Documents/raport.csv ~/Desktop/AI/
```

---

## 💰 KOSZTY I OPTYMALIZACJA {#koszty}

### **Model i ceny:**
- **Claude Sonnet 4**
- Input: $3 / milion tokenów
- Output: $15 / milion tokenów

### **Prompt Caching:**
- **Pierwsza wiadomość:** pełna cena (~$0.15-0.30)
- **Następne (w 5 min):** 90% taniej (~$0.01-0.03)
- **Cache trwa:** 5 minut od ostatniego użycia

### **Przykładowe koszty:**

**Intensywna sesja (20 wiadomości w 30 min):**
- 1. wiadomość: $0.20
- 19 wiadomości: 19 × $0.02 = $0.38
- **RAZEM: $0.58**

**Dzienne użytkowanie (50 wiadomości, 3 sesje):**
- 3 × $0.20 = $0.60 (budowanie cache)
- 47 × $0.02 = $0.94 (cache hits)
- **RAZEM: $1.54/dzień**

**Miesięcznie:**
- $1.54 × 30 = **~$46/miesiąc** (intensywne użytkowanie)
- **$10-20 starczy na 200-600 wiadomości**

### **Optymalizacje:**

✅ **Prompt Caching** - 90% taniej (już wbudowane)
✅ **Smart Compression** - skraca długie pliki
✅ **Antyhalucynacja** - nie marnuje tokenów na błędne odpowiedzi
✅ **Pamięć limitowana** - tylko ostatnie 20 rozmów
✅ **@agent!** - bez extended thinking = 5x taniej

### **Rate Limit:**
- 30,000 tokenów/minutę (darmowy tier)
- Jeśli przekroczysz = czekaj 60 sekund
- Rozwiązanie: użyj `@agent!` lub poproś Anthropic o wyższy limit

---

## 🎓 NAJLEPSZE PRAKTYKI

### **Oszczędzanie tokenów:**
1. Używaj `@agent!` dla prostych pytań
2. Grupuj pytania w jednej wiadomości
3. Pytaj często w 5-minutowych oknach (cache)
4. Unikaj web search gdy nie potrzeba

### **Efektywna praca z agentami:**
1. **Stwórz profil:** `~/Desktop/AI/profil_zyciowy.md` i `~/Desktop/AI/mapa_celow.md`
2. **Deleguj do specjalistów:** @analityk dla danych, @ceo dla strategii
3. **Pozwól COO orkiestrować:** pisz normalnie, COO sam zbierze zespół
4. **Zapisuj ważne rzeczy:** agenci mogą tworzyć pliki .md w workspace

### **Utrzymanie systemu:**
1. Pamięć czyszczona automatycznie (ostatnie 20 rozmów)
2. Pliki w workspace - ty zarządzasz
3. Doładuj kredyty gdy saldo <$2
4. Cache expire po 5 min - to normalne

---

## 🆘 ROZWIĄZYWANIE PROBLEMÓW

### **"command not found: agents"**
```bash
source ~/.bash_profile
agents
```

### **"No module named 'anthropic'"**
```bash
source ~/ai_env/bin/activate
pip install anthropic
```

### **"Rate limit exceeded"**
Czekaj 60 sekund lub użyj `@agent!` (bez extended thinking)

### **"Credit balance too low"**
Doładuj kredyty: https://console.anthropic.com/settings/billing

### **Polskie znaki nie działają**
```bash
export LC_ALL=pl_PL.UTF-8
export LANG=pl_PL.UTF-8
```

### **Cache nie działa**
To normalne jeśli minęło >5 min. Pierwsza wiadomość odbuduje cache.

---

## ✅ CHECKLIST KOŃCOWY

Przed pierwszym użyciem sprawdź:

- [ ] Homebrew zainstalowane (`brew --version`)
- [ ] Node.js 18 zainstalowane (`node --version`)
- [ ] Python venv aktywne (widzisz `(ai_env)`)
- [ ] Biblioteki zainstalowane (`pip list | grep anthropic`)
- [ ] API Key ustawiony (`echo $ANTHROPIC_API_KEY`)
- [ ] Folder ~/Desktop/AI istnieje
- [ ] Plik ~/Desktop/ai_team.py istnieje
- [ ] Alias `agents` działa
- [ ] Kredyty API >$5

---

## 🎉 GOTOWE!

Gratulacje! Masz najlepszy możliwy system agentów AI:

✅ 5 wyspecjalizowanych agentów
✅ Extended thinking (mądrzejsze odpowiedzi)
✅ Web search (aktualne informacje)
✅ Prompt caching (90% oszczędności)
✅ Antyhalucynacja (brak wymyślonych danych)
✅ Analiza danych (CSV, Excel, PDF)
✅ Pamięć między sesjami
✅ Zapisywanie plików
✅ Wszystkie typy plików

**Koszt:** $10-20/miesiąc przy normalnym użytkowaniu

**Uruchom:**
```bash
agents
```

**I zacznij pracować z najlepszymi agentami AI! 🚀**

Twój adres e-mail nie zostanie opublikowany.