instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Help me write clear docstrings
import logging import uuid from typing import Dict, List, Mapping, Optional from urllib.parse import urlparse from pydantic import BaseModel try: import weaviate except ImportError: raise ImportError( "The 'weaviate' library is required. Please install it using 'pip install weaviate-client weaviate'."...
--- +++ @@ -37,6 +37,17 @@ auth_client_secret: str = None, additional_headers: dict = None, ): + """ + Initialize the Weaviate vector store. + + Args: + collection_name (str): Name of the collection/class in Weaviate. + embedding_model_dims (int): Dimensi...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/weaviate.py
Write Python docstrings for this snippet
from typing import Tuple from app.models import App, User from sqlalchemy.orm import Session def get_or_create_user(db: Session, user_id: str) -> User: user = db.query(User).filter(User.user_id == user_id).first() if not user: user = User(user_id=user_id) db.add(user) db.commit() ...
--- +++ @@ -5,6 +5,7 @@ def get_or_create_user(db: Session, user_id: str) -> User: + """Get or create a user with the given user_id""" user = db.query(User).filter(User.user_id == user_id).first() if not user: user = User(user_id=user_id) @@ -15,6 +16,7 @@ def get_or_create_app(db: Session...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/openmemory/api/app/utils/db.py
Generate consistent documentation across files
from typing import Any, Dict, Optional from app.database import get_db from app.models import Config as ConfigModel from app.utils.memory import reset_memory_client from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel, Field from sqlalchemy.orm import Session router = APIRouter(prefix=...
--- +++ @@ -47,6 +47,7 @@ mem0: Optional[Mem0Config] = None def get_default_configuration(): + """Get the default configuration with sensible defaults for LLM and embedder.""" return { "openmemory": { "custom_instructions": None @@ -73,6 +74,7 @@ } def get_config_from_db(db: ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/openmemory/api/app/routers/config.py
Fully document this Python code with docstrings
import logging from abc import ABC, abstractmethod from mem0.memory.utils import format_entities try: from rank_bm25 import BM25Okapi except ImportError: raise ImportError("rank_bm25 is not installed. Please install it using pip install rank-bm25") from mem0.graphs.tools import ( DELETE_MEMORY_STRUCT_TOO...
--- +++ @@ -23,9 +23,16 @@ class NeptuneBase(ABC): + """ + Abstract base class for neptune (neptune analytics and neptune db) calls using OpenCypher + to store/retrieve data + """ @staticmethod def _create_embedding_model(config): + """ + :return: the Embedder model used for me...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/graphs/neptune/base.py
Add standardized docstrings across the file
import logging import uuid from typing import List, Optional from pydantic import BaseModel try: import vecs except ImportError: raise ImportError("The 'vecs' library is required. Please install it using 'pip install vecs'.") from mem0.configs.vector_stores.supabase import IndexMeasure, IndexMethod from mem0...
--- +++ @@ -30,6 +30,16 @@ index_method: IndexMethod = IndexMethod.AUTO, index_measure: IndexMeasure = IndexMeasure.COSINE, ): + """ + Initialize the Supabase vector store using vecs. + + Args: + connection_string (str): PostgreSQL connection string + col...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/supabase.py
Write docstrings that follow conventions
import os from typing import Dict, List, Optional try: from google import genai from google.genai import types except ImportError: raise ImportError("The 'google-genai' library is required. Please install it using 'pip install google-genai'.") from mem0.configs.llms.base import BaseLlmConfig from mem0.llm...
--- +++ @@ -22,6 +22,16 @@ self.client = genai.Client(api_key=api_key) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The list of tools pr...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/gemini.py
Add return value explanations in docstrings
import logging from mem0.memory.utils import format_entities try: import kuzu except ImportError: raise ImportError("kuzu is not installed. Please install it using pip install kuzu") try: from rank_bm25 import BM25Okapi except ImportError: raise ImportError("rank_bm25 is not installed. Please install...
--- +++ @@ -96,6 +96,13 @@ return list(results.rows_as_dict()) def add(self, data, filters): + """ + Adds data to the graph. + + Args: + data (str): The data to add to the graph. + filters (dict): A dictionary containing filters to be applied during the addition...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/memory/kuzu_memory.py
Document all public functions with docstrings
import json import os from typing import Dict, List, Optional, Union from openai import OpenAI from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.deepseek import DeepSeekConfig from mem0.llms.base import LLMBase from mem0.memory.utils import extract_json class DeepSeekLLM(LLMBase): def __in...
--- +++ @@ -41,6 +41,16 @@ self.client = OpenAI(api_key=api_key, base_url=base_url) def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The lis...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/deepseek.py
Generate missing documentation strings
import asyncio import concurrent import gc import hashlib import json import logging import os import uuid import warnings from copy import deepcopy from datetime import datetime from typing import Any, Dict, Optional import pytz from pydantic import ValidationError from mem0.configs.base import MemoryConfig, MemoryI...
--- +++ @@ -52,6 +52,7 @@ def _safe_deepcopy_config(config): + """Safely deepcopy config, falling back to JSON serialization for non-serializable objects.""" try: return deepcopy(config) except Exception as e: @@ -94,6 +95,40 @@ input_metadata: Optional[Dict[str, Any]] = None, input_f...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/memory/main.py
Create docstrings for all classes and functions
from abc import ABC, abstractmethod class MemoryBase(ABC): @abstractmethod def get(self, memory_id): pass @abstractmethod def get_all(self): pass @abstractmethod def update(self, memory_id, data): pass @abstractmethod def delete(self, memory_id): pass...
--- +++ @@ -4,20 +4,60 @@ class MemoryBase(ABC): @abstractmethod def get(self, memory_id): + """ + Retrieve a memory by ID. + + Args: + memory_id (str): ID of the memory to retrieve. + + Returns: + dict: Retrieved memory. + """ pass @abs...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/memory/base.py
Write Python docstrings for this snippet
import logging import uuid from datetime import datetime import pytz from .base import NeptuneBase try: from langchain_aws import NeptuneGraph except ImportError: raise ImportError("langchain_aws is not installed. Please install it using 'make install_all'.") logger = logging.getLogger(__name__) class Memor...
--- +++ @@ -14,6 +14,9 @@ class MemoryGraph(NeptuneBase): def __init__(self, config): + """ + Initialize the Neptune DB memory store. + """ self.config = config @@ -58,6 +61,15 @@ self.vector_store_limit=5 def _delete_entities_cypher(self, source, destination, rel...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/graphs/neptune/neptunedb.py
Add minimal docstrings for each function
import json from typing import Dict, List, Optional try: import litellm except ImportError: raise ImportError("The 'litellm' library is required. Please install it using 'pip install litellm'.") from mem0.configs.llms.base import BaseLlmConfig from mem0.llms.base import LLMBase from mem0.memory.utils import e...
--- +++ @@ -19,6 +19,16 @@ self.config.model = "gpt-4.1-nano-2025-04-14" def _parse_response(self, response, tools): + """ + Process the response based on whether tools are used or not. + + Args: + response: The raw response from API. + tools: The list of to...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/litellm.py
Add detailed documentation for each class
import os import re import glob import json import logging import torch from nanochat.common import get_base_dir from nanochat.gpt import GPT, GPTConfig from nanochat.tokenizer import get_tokenizer from nanochat.common import setup_default_logging # Set up logging setup_default_logging() logger = logging.getLogger(__...
--- +++ @@ -1,3 +1,6 @@+""" +Utilities for saving and loading model/optim/state checkpoints. +""" import os import re import glob @@ -18,12 +21,14 @@ logger.info(message) def _patch_missing_config_keys(model_config_kwargs): + """Add default values for new config keys missing in old checkpoints.""" ...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/checkpoint_manager.py
Write beginner-friendly docstrings
import torch import pyarrow.parquet as pq from nanochat.common import get_dist_info from nanochat.dataset import list_parquet_files def _document_batches(split, resume_state_dict, tokenizer_batch_size): ddp, ddp_rank, ddp_local_rank, ddp_world_size = get_dist_info() warn_on_legacy = ddp_rank == 0 and split ...
--- +++ @@ -1,3 +1,20 @@+""" +Distributed dataloaders for pretraining. + +BOS-aligned bestfit: + - Every row starts with BOS token + - Documents packed using best-fit algorithm to minimize cropping + - When no document fits remaining space, crops a document to fill exactly + - 100% utilization (no padding), ~35...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/dataloader.py
Add docstrings to meet PEP guidelines
import os import re import logging import urllib.request import torch import torch.distributed as dist from filelock import FileLock # The dtype used for compute (matmuls, activations). Master weights stay fp32 for optimizer precision. # Linear layers cast their weights to this dtype in forward, replacing torch.amp.a...
--- +++ @@ -1,3 +1,6 @@+""" +Common utilities for nanochat. +""" import os import re @@ -28,6 +31,7 @@ COMPUTE_DTYPE, COMPUTE_DTYPE_REASON = _detect_compute_dtype() class ColoredFormatter(logging.Formatter): + """Custom formatter that adds colors to log messages.""" # ANSI color codes COLORS = { ...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/common.py
Write reusable docstrings
import logging import os from typing import Any, Dict, List, Optional from dotenv import load_dotenv from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse, RedirectResponse from pydantic import BaseModel, Field from mem0 import Memory logging.basicConfig(level=logging.INFO, format="%(...
--- +++ @@ -88,6 +88,7 @@ @app.post("/configure", summary="Configure Mem0") def set_config(config: Dict[str, Any]): + """Set memory configuration.""" global MEMORY_INSTANCE MEMORY_INSTANCE = Memory.from_config(config) return {"message": "Configuration set successfully"} @@ -95,6 +96,7 @@ @app.pos...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/server/main.py
Generate consistent docstrings
#!/usr/bin/env python3 import argparse import json import sys import urllib.error import urllib.parse import urllib.request DOCS_BASE = "https://docs.mem0.ai" SEARCH_ENDPOINT = f"{DOCS_BASE}/api/search" LLMS_INDEX = f"{DOCS_BASE}/llms.txt" # Known documentation sections for targeted retrieval SECTION_MAP = { "pl...
--- +++ @@ -1,4 +1,24 @@ #!/usr/bin/env python3 +""" +Mem0 Documentation Search Agent (Mintlify-based) +On-demand search tool for querying Mem0 documentation without storing content locally. + +This tool leverages Mintlify's documentation structure to perform just-in-time +retrieval of technical information from docs.m...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/skills/mem0/scripts/mem0_doc_search.py
Generate docstrings for exported functions
import logging from typing import Dict, List, Optional from pydantic import BaseModel try: from langchain_community.vectorstores import VectorStore except ImportError: raise ImportError( "The 'langchain_community' library is required. Please install it using 'pip install langchain_community'." ) ...
--- +++ @@ -27,6 +27,15 @@ self.collection_name = collection_name def _parse_output(self, data: Dict) -> List[OutputData]: + """ + Parse the output data. + + Args: + data (Dict): Output data or list of Document objects. + + Returns: + List[OutputData]: Pa...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/vector_stores/langchain.py
Add docstrings to improve code quality
import os import argparse import time import requests import pyarrow.parquet as pq from multiprocessing import Pool from nanochat.common import get_base_dir # ----------------------------------------------------------------------------- # The specifics of the current pretraining dataset # The URL on the internet wh...
--- +++ @@ -1,3 +1,11 @@+""" +The base/pretraining dataset is a set of parquet files. +This file contains utilities for: +- iterating over the parquet files and yielding documents from it +- download the files on demand if they are not on disk + +For details of how the dataset was prepared, see `repackage_data_referenc...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/dataset.py
Add detailed docstrings explaining each function
import datetime import enum import uuid import sqlalchemy as sa from app.database import Base from app.utils.categorization import get_categories_for_memory from sqlalchemy import ( JSON, UUID, Boolean, Column, DateTime, Enum, ForeignKey, Index, Integer, String, Table, e...
--- +++ @@ -23,6 +23,7 @@ def get_current_utc_time(): + """Get current UTC time""" return datetime.datetime.now(datetime.UTC) @@ -187,6 +188,7 @@ ) def categorize_memory(memory: Memory, db: Session) -> None: + """Categorize a memory using OpenAI and store the categories in the database.""" ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/openmemory/api/app/models.py
Create simple docstrings for beginners
import contextvars import datetime import json import logging import uuid from app.database import SessionLocal from app.models import Memory, MemoryAccessLog, MemoryState, MemoryStatusHistory from app.utils.db import get_user_and_app from app.utils.memory import get_memory_client from app.utils.permissions import ch...
--- +++ @@ -1,3 +1,19 @@+""" +MCP Server for OpenMemory with resilient memory client handling. + +This module implements an MCP (Model Context Protocol) server that provides +memory operations for OpenMemory. The memory client is initialized lazily +to prevent server crashes when external dependencies (like Ollama) are...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/openmemory/api/app/mcp_server.py
Add docstrings to incomplete code
import logging from mem0.memory.utils import format_entities, sanitize_relationship_for_cypher try: from langchain_neo4j import Neo4jGraph except ImportError: raise ImportError("langchain_neo4j is not installed. Please install it using pip install langchain-neo4j") try: from rank_bm25 import BM25Okapi ex...
--- +++ @@ -74,6 +74,13 @@ self.threshold = self.config.graph_store.threshold if hasattr(self.config.graph_store, 'threshold') else 0.7 def add(self, data, filters): + """ + Adds data to the graph. + + Args: + data (str): The data to add to the graph. + filters ...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/memory/graph_memory.py
Add docstrings with type hints explained
import random from jinja2 import Template import torch import torch.distributed as dist # ----------------------------------------------------------------------------- # Prompt rendering utilities def render_prompts_mc(item, continuation_delimiter, fewshot_examples=None): template_str = """ {%- for example in fe...
--- +++ @@ -1,3 +1,10 @@+""" +Functions for evaluating the CORE metric, as described in the DCLM paper. +https://arxiv.org/abs/2406.11794 + +TODOs: +- All tasks ~match except for squad. We get 31% reference is 37%. Figure out why. +""" import random from jinja2 import Template @@ -8,6 +15,7 @@ # Prompt rendering ut...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/core_eval.py
Help me document legacy Python code
from typing import Dict, List, Optional from mem0.configs.llms.base import BaseLlmConfig from mem0.llms.base import LLMBase try: from langchain.chat_models.base import BaseChatModel from langchain_core.messages import AIMessage except ImportError: raise ImportError("langchain is not installed. Please inst...
--- +++ @@ -23,6 +23,16 @@ self.langchain_model = self.config.model def _parse_response(self, response: AIMessage, tools: Optional[List[Dict]]): + """ + Process the response based on whether tools are used or not. + + Args: + response: AI Message. + tools: The l...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/llms/langchain.py
Document all public functions with docstrings
import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile from dataclasses import dataclass from typing import Optional # ----------------------------------------------------------------------------- @dataclass class ExecutionResult: success: b...
--- +++ @@ -1,3 +1,25 @@+""" +Sandboxed execution utilities for running Python code that comes out of an LLM. +Adapted from OpenAI HumanEval code: +https://github.com/openai/human-eval/blob/master/human_eval/execution.py + +What is covered: +- Each execution runs in its own process (can be killed if it hangs or crashes...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/execution.py
Add docstrings including usage examples
import math import torch import torch.distributed as dist @torch.no_grad() def evaluate_bpb(model, batches, steps, token_bytes): # record the losses total_nats = torch.tensor(0.0, dtype=torch.float32, device=model.get_device()) total_bytes = torch.tensor(0, dtype=torch.int64, device=model.get_device()) ...
--- +++ @@ -1,9 +1,29 @@+""" +A number of functions that help with evaluating a base model. +""" import math import torch import torch.distributed as dist @torch.no_grad() def evaluate_bpb(model, batches, steps, token_bytes): + """ + Instead of the naive 'mean loss', this function returns the bits per byte...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/loss_eval.py
Add docstrings that explain logic
import requests import json import os import copy import random from concurrent.futures import ThreadPoolExecutor, as_completed from dotenv import load_dotenv from nanochat.common import get_base_dir load_dotenv() api_key = os.environ["OPENROUTER_API_KEY"] url = "https://openrouter.ai/api/v1/chat/completions" header...
--- +++ @@ -1,3 +1,23 @@+""" +Synthetic data generation for teaching nanochat about its identity and capabilities. + +This script uses the OpenRouter API to generate diverse multi-turn conversations +between a user and nanochat. The conversations are saved to a .jsonl file for use +in supervised finetuning (SFT) via th...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/dev/gen_synthetic_data.py
Add missing documentation to my Python functions
import logging from mem0.memory.utils import format_entities, sanitize_relationship_for_cypher try: from langchain_memgraph.graphs.memgraph import Memgraph except ImportError: raise ImportError("langchain_memgraph is not installed. Please install it using pip install langchain-memgraph") try: from rank_b...
--- +++ @@ -79,6 +79,13 @@ self.graph.query("CREATE INDEX ON :Entity;") def add(self, data, filters): + """ + Adds data to the graph. + + Args: + data (str): The data to add to the graph. + filters (dict): A dictionary containing filters to be applied during...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/memory/memgraph_memory.py
Add docstrings to meet PEP guidelines
import torch import torch.distributed as dist from torch import Tensor # ----------------------------------------------------------------------------- """ Good old AdamW optimizer, fused kernel. https://arxiv.org/abs/1711.05101 """ @torch.compile(dynamic=False, fullgraph=True) def adamw_step_fused( p: Tensor, ...
--- +++ @@ -1,3 +1,11 @@+""" +A nice and efficient mixed AdamW/Muon Combined Optimizer. +Usually the embeddings and scalars go into AdamW, and the matrix parameters go into Muon. +Two versions are provided (MuonAdamW, DistMuonAdamW), for single GPU and distributed. + +Addapted from: https://github.com/KellerJordan/modd...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/optim.py
Add docstrings to incomplete code
import re from datasets import load_dataset from nanochat.execution import execute_code from tasks.common import Task def extract_imports(prompt): imports = [] for line in prompt.split('\n'): stripped = line.strip() if stripped.startswith('import ') or stripped.startswith('from '): ...
--- +++ @@ -1,3 +1,8 @@+""" +Evaluate the Chat model on HumanEval dataset. +Btw this dataset is a misnomer and has nothing to do with humans. +It is a coding benchmark. +""" import re from datasets import load_dataset @@ -5,6 +10,7 @@ from tasks.common import Task def extract_imports(prompt): + """Extract imp...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/tasks/humaneval.py
Document all public functions with docstrings
import re from datasets import load_dataset from tasks.common import Task GSM_RE = re.compile(r"#### (\-?[0-9\.\,]+)") def extract_answer(completion): match = GSM_RE.search(completion) if match: match_str = match.group(1).strip() match_str = match_str.replace(",", "") return match_str...
--- +++ @@ -1,3 +1,18 @@+""" +GSM8K evaluation. +https://huggingface.co/datasets/openai/gsm8k + +Example problem instance: + +Question: +Weng earns $12 an hour for babysitting. Yesterday, she just did 50 minutes of babysitting. How much did she earn? +Answer: +Weng earns 12/60 = $<<12/60=0.2>>0.2 per minute. +Working 5...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/tasks/gsm8k.py
Document all endpoints with docstrings
import hashlib import json import os import socket from app.database import SessionLocal from app.models import Config as ConfigModel from mem0 import Memory _memory_client = None _config_hash = None def _get_config_hash(config_dict): config_str = json.dumps(config_dict, sort_keys=True) return hashlib.md5...
--- +++ @@ -1,3 +1,31 @@+""" +Memory client utilities for OpenMemory. + +This module provides functionality to initialize and manage the Mem0 memory client +with automatic configuration management and Docker environment support. + +Docker Ollama Configuration: +When running inside a Docker container and using Ollama as...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/openmemory/api/app/utils/memory.py
Add docstrings to existing functions
import torch import torch.nn.functional as F # ============================================================================= # Detection: Try to load FA3 on Hopper+ GPUs # ============================================================================= def _load_flash_attention_3(): if not torch.cuda.is_available():...
--- +++ @@ -1,3 +1,18 @@+""" +Unified Flash Attention interface with automatic FA3/SDPA switching. + +Exports `flash_attn` module that matches the FA3 API exactly, but falls back +to PyTorch SDPA on non-Hopper GPUs (including Blackwell), MPS, and CPU. + +Usage (drop-in replacement for FA3): + from nanochat.flash_att...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/flash_attention.py
Write docstrings for data processing functions
from abc import ABC, abstractmethod from typing import List, Dict, Any class BaseReranker(ABC): @abstractmethod def rerank(self, query: str, documents: List[Dict[str, Any]], top_k: int = None) -> List[Dict[str, Any]]: pass
--- +++ @@ -2,7 +2,19 @@ from typing import List, Dict, Any class BaseReranker(ABC): + """Abstract base class for all rerankers.""" @abstractmethod def rerank(self, query: str, documents: List[Dict[str, Any]], top_k: int = None) -> List[Dict[str, Any]]: + """ + Rerank documents based...
https://raw.githubusercontent.com/mem0ai/mem0/HEAD/mem0/reranker/base.py
Generate docstrings with parameter types
from functools import partial from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from nanochat.common import get_dist_info, print0, COMPUTE_DTYPE from nanochat.optim import MuonAdamW, DistMuonAdamW # Our custom Flash Attention module that automatically uses FA3 on H...
--- +++ @@ -1,3 +1,16 @@+""" +GPT model (rewrite, a lot simpler) +Notable features: +- rotary embeddings (and no positional embeddings) +- QK norm +- untied weights for token embedding and lm_head +- relu^2 activation in MLP +- norm after token embedding +- no learnable params in rmsnorm +- no bias in linear layers +- ...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/gpt.py
Generate docstrings with parameter types
import torch import torch.nn.functional as F import signal import warnings from contextlib import contextmanager from collections import deque from nanochat.common import compute_init, autodetect_device_type from nanochat.checkpoint_manager import load_model # ---------------------------------------------------------...
--- +++ @@ -1,3 +1,15 @@+""" +Engine for efficient inference of our models. + +Everything works around token sequences: +- The user can send token sequences to the engine +- The engine returns the next token + +Notes: +- The engine knows nothing about tokenization, it's purely token id sequences. + +The whole thing is ...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/engine.py
Write docstrings describing each step
import torch import torch.nn as nn from nanochat.common import COMPUTE_DTYPE # Avoid division by zero when computing scale from an all-zeros tensor EPS = 1e-12 @torch.no_grad() def _to_fp8(x, fp8_dtype): fp8_max = torch.finfo(fp8_dtype).max # Compute the max absolute value across the entire tensor amax...
--- +++ @@ -1,3 +1,73 @@+"""Minimal FP8 training for nanochat — tensorwise dynamic scaling only. + +Drop-in replacement for torchao's Float8Linear (~2000 lines) with ~150 lines. +We only need the "tensorwise" recipe (one scalar scale per tensor), not the full +generality of torchao (rowwise scaling, FSDP float8 all-gat...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/fp8.py
Fill in missing docstrings in my code
import os import copy from functools import lru_cache SPECIAL_TOKENS = [ # every document begins with the Beginning of Sequence (BOS) token that delimits documents "<|bos|>", # tokens below are only used during finetuning to render Conversations into token ids "<|user_start|>", # user messages "<|...
--- +++ @@ -1,3 +1,10 @@+""" +BPE Tokenizer in the style of GPT-4. + +Two implementations are available: +1) HuggingFace Tokenizer that can do both training and inference but is really confusing +2) Our own RustBPE Tokenizer for training and tiktoken for efficient inference +""" import os import copy @@ -30,6 +37,7...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/tokenizer.py
Add docstrings that explain purpose and usage
import os import re import shutil import subprocess import socket import datetime import platform import psutil import torch def run_command(cmd): try: result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5) # Return stdout if we got output (even if some files in xargs ...
--- +++ @@ -1,3 +1,6 @@+""" +Utilities for generating training report cards. More messy code than usual, will fix. +""" import os import re @@ -10,6 +13,7 @@ import torch def run_command(cmd): + """Run a shell command and return output, or None if it fails.""" try: result = subprocess.run(cmd, s...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/nanochat/report.py
Generate descriptive docstrings automatically
import os import csv import time import json import yaml import shutil import random import zipfile import tempfile import argparse import torch from nanochat.common import compute_init, compute_cleanup, print0, get_base_dir, autodetect_device_type, download_file_with_lock from nanochat.tokenizer import HuggingFaceTok...
--- +++ @@ -1,3 +1,24 @@+""" +Unified evaluation script for base models. + +Supports three evaluation modes (comma-separated): + --eval core : CORE metric (accuracy on ICL tasks) + --eval bpb : Bits per byte on train/val splits + --eval sample : Generate samples from the model + +Default is all three: --eval...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/scripts/base_eval.py
Replace inline comments with docstrings
import os os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True" import gc import json import time import math import argparse from dataclasses import asdict from contextlib import contextmanager import wandb import torch import torch.distributed as dist from nanochat.gpt import GPT, GPTConfig, Linear from na...
--- +++ @@ -1,3 +1,15 @@+""" +Train model. From root directory of the project, run as: + +python -m scripts.base_train + +or distributed as: + +torchrun --nproc_per_node=8 -m scripts.base_train + +If you are only on CPU/Macbook, you'll want to train a much much smaller LLM. Example: +python -m scripts.base_train --dept...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/scripts/base_train.py
Write Python docstrings for this snippet
#!/usr/bin/env python3 import argparse import json import os import torch import asyncio import logging import random from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse, HTMLResponse, F...
--- +++ @@ -1,4 +1,34 @@ #!/usr/bin/env python3 +""" +Unified web chat server - serves both UI and API from a single FastAPI instance. + +Uses data parallelism to distribute requests across multiple GPUs. Each GPU loads +a full copy of the model, and incoming requests are distributed to available workers. + +Launch exa...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/scripts/chat_web.py
Write proper docstrings for these functions
import argparse import os import itertools import wandb import torch import torch.distributed as dist from nanochat.common import compute_init, compute_cleanup, print0, get_base_dir, DummyWandb, autodetect_device_type from nanochat.checkpoint_manager import save_checkpoint, load_model from nanochat.engine import Engin...
--- +++ @@ -1,3 +1,20 @@+""" +Reinforcement learning on GSM8K via "GRPO". + +I put GRPO in quotes because we actually end up with something a lot +simpler and more similar to just REINFORCE: + +1) Delete trust region, so there is no KL regularization to a reference model +2) We are on policy, so there's no need for PPO...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/scripts/chat_rl.py
Expand my code with proper documentation strings
from sqlalchemy.orm import Session from sqlalchemy import func from typing import List, Optional from datetime import datetime from app.backend.database.models import ApiKey class ApiKeyRepository: def __init__(self, db: Session): self.db = db def create_or_update_api_key( self, ...
--- +++ @@ -7,6 +7,7 @@ class ApiKeyRepository: + """Repository for API key database operations""" def __init__(self, db: Session): self.db = db @@ -18,6 +19,7 @@ description: str = None, is_active: bool = True ) -> ApiKey: + """Create a new API key or update exi...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/repositories/api_key_repository.py
Improve my code by adding docstrings
import gc import argparse import os os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True" import time import wandb import torch from nanochat.common import compute_init, compute_cleanup, print0, DummyWandb, get_base_dir, autodetect_device_type, get_peak_flops, COMPUTE_DTYPE, COMPUTE_DTYPE_REASON, is_ddp_initia...
--- +++ @@ -1,3 +1,13 @@+""" +Supervised fine-tuning (SFT) the model. +Run as: + +python -m scripts.chat_sft + +Or torchrun for training: + +torchrun --standalone --nproc_per_node=8 -m scripts.chat_sft -- --device-batch-size=16 +""" import gc import argparse @@ -175,6 +185,14 @@ approx_progress = 0.0 # will go from...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/scripts/chat_sft.py
Write beginner-friendly docstrings
from nanochat.tokenizer import get_tokenizer, RustBPETokenizer from nanochat.dataset import parquets_iter_batched # Random text I got from a random website this morning news_text = r""" (Washington, D.C., July 9, 2025)- Yesterday, Mexico’s National Service of Agro-Alimentary Health, Safety, and Quality (SENASICA) rep...
--- +++ @@ -1,3 +1,6 @@+""" +Evaluate compression ratio of the tokenizer. +""" from nanochat.tokenizer import get_tokenizer, RustBPETokenizer from nanochat.dataset import parquets_iter_batched @@ -198,6 +201,7 @@ print(f"Ours: {vocab_sizes['ours']}") def print_comparison(baseline_name, baseline_results, ours_res...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/scripts/tok_eval.py
Document my Python code with docstrings
import os import time import argparse import torch from nanochat.tokenizer import RustBPETokenizer from nanochat.common import get_base_dir from nanochat.dataset import parquets_iter_batched # ----------------------------------------------------------------------------- # Parse command line arguments parser = argpars...
--- +++ @@ -1,3 +1,7 @@+""" +Train a tokenizer using our own BPE Tokenizer library. +In the style of GPT-4 tokenizer. +""" import os import time import argparse @@ -22,6 +26,11 @@ # Text iterator def text_iterator(): + """ + 1) Flatten the batches into a single iterator + 2) Crop every document to args.d...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/scripts/tok_train.py
Turn comments into proper docstrings
import os import json from tasks.common import Task class CustomJSON(Task): def __init__(self, filepath, **kwargs): super().__init__(**kwargs) self.filepath = filepath self.conversations = [] # Load all conversations from the JSONL file if not os.path.exists(filepath): ...
--- +++ @@ -1,9 +1,18 @@+""" +CustomJSON task for loading conversations from JSONL files. +Each line in the JSONL file should be a JSON array of messages. +""" import os import json from tasks.common import Task class CustomJSON(Task): + """ + Load conversations from a JSONL file. + Each line should be...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/tasks/customjson.py
Add professional docstrings to my codebase
from fastapi import APIRouter, HTTPException, Depends, Query from sqlalchemy.orm import Session from typing import List, Optional from app.backend.database import get_db from app.backend.repositories.flow_run_repository import FlowRunRepository from app.backend.repositories.flow_repository import FlowRepository from a...
--- +++ @@ -30,6 +30,7 @@ request: FlowRunCreateRequest, db: Session = Depends(get_db) ): + """Create a new flow run for the specified flow""" try: # Verify flow exists flow_repo = FlowRepository(db) @@ -64,6 +65,7 @@ offset: int = Query(0, ge=0, description="Number of runs to s...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/routes/flow_runs.py
Generate docstrings for script automation
import random class Task: def __init__(self, start=0, stop=None, step=1): # allows a lightweight logical view over a dataset assert start >= 0, f"Start must be non-negative, got {start}" assert stop is None or stop >= start, f"Stop should be greater than or equal to start, got {stop} and ...
--- +++ @@ -1,7 +1,16 @@+""" +Base class for all Tasks. +A Task is basically a dataset of conversations, together with some +metadata and often also evaluation criteria. +Example tasks: MMLU, ARC-Easy, ARC-Challenge, GSM8K, HumanEval, SmolTalk. +""" import random class Task: + """ + Base class of a Task. Al...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/tasks/common.py
Document functions with clear intent
from fastapi import APIRouter, HTTPException, Request, Depends from fastapi.responses import StreamingResponse from sqlalchemy.orm import Session import asyncio from app.backend.database import get_db from app.backend.models.schemas import ErrorResponse, HedgeFundRequest, BacktestRequest, BacktestDayResult, BacktestPe...
--- +++ @@ -50,6 +50,7 @@ # Function to detect client disconnection async def wait_for_disconnect(): + """Wait for client disconnect and return True when it happens""" try: while True: message = await request.receive() @@ -167,6 +168,7 @@ ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/routes/hedge_fund.py
Provide docstrings following PEP 257
from datasets import load_dataset from tasks.common import Task class SmolTalk(Task): def __init__(self, split, **kwargs): super().__init__(**kwargs) assert split in ["train", "test"], "SmolTalk split must be train|test" self.ds = load_dataset("HuggingFaceTB/smol-smoltalk", split=split).s...
--- +++ @@ -1,8 +1,14 @@+""" +SmolTalk by HuggingFace. Good "general" conversational dataset. +https://huggingface.co/datasets/HuggingFaceTB/smol-smoltalk +We use the "smol" version, which is more appropriate for smaller models. +""" from datasets import load_dataset from tasks.common import Task class SmolTalk(...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/tasks/smoltalk.py
Write beginner-friendly docstrings
import re import random from tasks.common import Task from nanochat.common import download_file_with_lock # Letters of the alphabet LETTERS = "abcdefghijklmnopqrstuvwxyz" # A list of 370K English words of large variety WORD_LIST_URL = "https://raw.githubusercontent.com/dwyl/english-words/refs/heads/master/words_alpha...
--- +++ @@ -1,3 +1,30 @@+""" +Task intended to make nanochat better in spelling and counting, for example: + +"How many r are in strawberry?" -> 3 + +An interesting part of this task is that we will get the assistant to +solve the problem using a combination of manual counting and Python. +This is a good problem solvin...
https://raw.githubusercontent.com/karpathy/nanochat/HEAD/tasks/spellingbee.py
Insert docstrings into my code
from fastapi import APIRouter, HTTPException from typing import List, Dict, Any from app.backend.models.schemas import ErrorResponse from app.backend.services.ollama_service import OllamaService from src.llm.models import get_models_list router = APIRouter(prefix="/language-models") # Initialize Ollama service ollam...
--- +++ @@ -18,6 +18,7 @@ }, ) async def get_language_models(): + """Get the list of available cloud-based and Ollama language models.""" try: # Start with cloud models models = get_models_list() @@ -38,6 +39,7 @@ }, ) async def get_language_model_providers(): + """Get the list ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/routes/language_models.py
Create docstrings for API functions
from sqlalchemy import Column, Integer, String, DateTime, Text, Boolean, JSON, ForeignKey from sqlalchemy.sql import func from .connection import Base class HedgeFundFlow(Base): __tablename__ = "hedge_fund_flows" id = Column(Integer, primary_key=True, index=True) created_at = Column(DateTime(timezone...
--- +++ @@ -4,6 +4,7 @@ class HedgeFundFlow(Base): + """Table to store React Flow configurations (nodes, edges, viewport)""" __tablename__ = "hedge_fund_flows" id = Column(Integer, primary_key=True, index=True) @@ -26,6 +27,7 @@ class HedgeFundFlowRun(Base): + """Table to track individual ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/database/models.py
Improve my code by adding docstrings
from datetime import datetime, timedelta from pydantic import BaseModel, Field, field_validator from typing import List, Optional, Dict, Any from src.llm.models import ModelProvider from enum import Enum from app.backend.services.graph import extract_base_agent_key class FlowRunStatus(str, Enum): IDLE = "IDLE" ...
--- +++ @@ -70,9 +70,11 @@ api_keys: Optional[Dict[str, str]] = None def get_agent_ids(self) -> List[str]: + """Extract agent IDs from graph structure""" return [node.id for node in self.graph_nodes] def get_agent_model_config(self, agent_id: str) -> tuple[str, ModelProvider]: + ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/models/schemas.py
Write docstrings describing functionality
from sqlalchemy.orm import Session from typing import Dict, Optional from app.backend.repositories.api_key_repository import ApiKeyRepository class ApiKeyService: def __init__(self, db: Session): self.repository = ApiKeyRepository(db) def get_api_keys_dict(self) -> Dict[str, str]: ap...
--- +++ @@ -4,14 +4,20 @@ class ApiKeyService: + """Simple service to load API keys for requests""" def __init__(self, db: Session): self.repository = ApiKeyRepository(db) def get_api_keys_dict(self) -> Dict[str, str]: + """ + Load all active API keys from database an...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/services/api_key_service.py
Improve my code by adding docstrings
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import get_financial_metrics, get_market_cap, search_line_items from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel import json from typing_extensions import ...
--- +++ @@ -17,6 +17,13 @@ def cathie_wood_agent(state: AgentState, agent_id: str = "cathie_wood_agent"): + """ + Analyzes stocks using Cathie Wood's investing principles and LLM reasoning. + 1. Prioritizes companies with breakthrough technologies or business models + 2. Focuses on industries with rapid...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/cathie_wood.py
Create Google-style docstrings for my code
from typing import List, Optional, Dict, Any from datetime import datetime from sqlalchemy.orm import Session from sqlalchemy import desc, func from app.backend.database.models import HedgeFundFlowRun from app.backend.models.schemas import FlowRunStatus class FlowRunRepository: def __init__(self, db: Session...
--- +++ @@ -7,11 +7,13 @@ class FlowRunRepository: + """Repository for HedgeFundFlowRun CRUD operations""" def __init__(self, db: Session): self.db = db def create_flow_run(self, flow_id: int, request_data: Dict[str, Any] = None) -> HedgeFundFlowRun: + """Create a new flow r...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/repositories/flow_run_repository.py
Write reusable docstrings
import asyncio import json import re from langchain_core.messages import HumanMessage from langgraph.graph import END, StateGraph from app.backend.services.agent_service import create_agent_function from src.agents.portfolio_manager import portfolio_management_agent from src.agents.risk_manager import risk_management_...
--- +++ @@ -13,6 +13,15 @@ def extract_base_agent_key(unique_id: str) -> str: + """ + Extract the base agent key from a unique node ID. + + Args: + unique_id: The unique node ID with suffix (e.g., "warren_buffett_abc123") + + Returns: + The base agent key (e.g., "warren_buffett") +...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/services/graph.py
Add docstrings that explain logic
from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # Th...
--- +++ @@ -26,6 +26,17 @@ def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/alembic/env.py
Write docstrings for this repository
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import get_financial_metrics, get_market_cap, search_line_items, get_insider_trades, get_company_news from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel impo...
--- +++ @@ -16,6 +16,10 @@ def charlie_munger_agent(state: AgentState, agent_id: str = "charlie_munger_agent"): + """ + Analyzes stocks using Charlie Munger's investing principles and mental models. + Focuses on moat strength, management quality, predictability, and valuation. + """ data = state["d...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/charlie_munger.py
Write docstrings describing functionality
from __future__ import annotations import json from typing_extensions import Literal from pydantic import BaseModel from src.graph.state import AgentState, show_agent_reasoning from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from src.tools.api import ( get_f...
--- +++ @@ -25,6 +25,14 @@ def aswath_damodaran_agent(state: AgentState, agent_id: str = "aswath_damodaran_agent"): + """ + Analyze US equities through Aswath Damodaran's intrinsic-value lens: + • Cost of Equity via CAPM (risk-free + β·ERP) + • 5-yr revenue / FCFF growth trends & reinvestment effici...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/aswath_damodaran.py
Fully document this Python code with docstrings
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import get_financial_metrics, get_market_cap, search_line_items from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel import json from typing_extensions import ...
--- +++ @@ -18,6 +18,13 @@ def ben_graham_agent(state: AgentState, agent_id: str = "ben_graham_agent"): + """ + Analyzes stocks using Benjamin Graham's classic value-investing principles: + 1. Earnings stability over multiple years. + 2. Solid financial strength (low debt, adequate liquidity). + 3. D...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/ben_graham.py
Document classes and their methods
from typing import List, Optional from sqlalchemy.orm import Session from app.backend.database.models import HedgeFundFlow class FlowRepository: def __init__(self, db: Session): self.db = db def create_flow(self, name: str, nodes: dict, edges: dict, description: str = None, ...
--- +++ @@ -4,12 +4,14 @@ class FlowRepository: + """Repository for HedgeFundFlow CRUD operations""" def __init__(self, db: Session): self.db = db def create_flow(self, name: str, nodes: dict, edges: dict, description: str = None, viewport: dict = None, data: d...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/repositories/flow_repository.py
Generate consistent documentation across files
import asyncio import os import sys import platform import subprocess import time import re import json import queue import threading from pathlib import Path from typing import Dict, List, Optional, AsyncGenerator import logging import signal import ollama logger = logging.getLogger(__name__) class OllamaService: ...
--- +++ @@ -17,6 +17,7 @@ logger = logging.getLogger(__name__) class OllamaService: + """Service for managing Ollama integration in the backend.""" def __init__(self): self._download_progress = {} @@ -31,6 +32,7 @@ # =========================================================================...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/services/ollama_service.py
Annotate my code with docstrings
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import get_financial_metrics, get_market_cap, search_line_items from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel import json from typing_extensions import ...
--- +++ @@ -17,6 +17,11 @@ def bill_ackman_agent(state: AgentState, agent_id: str = "bill_ackman_agent"): + """ + Analyzes stocks using Bill Ackman's investing principles and LLM reasoning. + Fetches multiple periods of data for a more robust long-term view. + Incorporates brand/competitive advantage, a...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/bill_ackman.py
Write Python docstrings for this snippet
from __future__ import annotations """Valuation Agent Implements four complementary valuation methodologies and aggregates them with configurable weights. """ import json import statistics from langchain_core.messages import HumanMessage from src.graph.state import AgentState, show_agent_reasoning from src.utils.pr...
--- +++ @@ -19,6 +19,7 @@ ) def valuation_analyst_agent(state: AgentState, agent_id: str = "valuation_analyst_agent"): + """Run valuation across tickers and write signals back to `state`.""" data = state["data"] end_date = data["end_date"] @@ -232,6 +233,7 @@ margin_of_safety: float = 0.25, n...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/valuation.py
Expand my code with proper documentation strings
from typing import Dict, Optional, Any, Literal from pydantic import BaseModel class BaseEvent(BaseModel): type: str def to_sse(self) -> str: event_type = self.type.lower() return f"event: {event_type}\ndata: {self.model_dump_json()}\n\n" class StartEvent(BaseEvent): type: Literal["st...
--- +++ @@ -3,20 +3,24 @@ class BaseEvent(BaseModel): + """Base class for all Server-Sent Event events""" type: str def to_sse(self) -> str: + """Convert to Server-Sent Event format""" event_type = self.type.lower() return f"event: {event_type}\ndata: {self.model_dump_json(...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/models/events.py
Create structured documentation for my script
import sys from dotenv import load_dotenv from langchain_core.messages import HumanMessage from langgraph.graph import END, StateGraph from colorama import Fore, Style, init import questionary from src.agents.portfolio_manager import portfolio_management_agent from src.agents.risk_manager import risk_management_agent ...
--- +++ @@ -28,6 +28,7 @@ def parse_hedge_fund_response(response): + """Parses a JSON string and returns a dictionary.""" try: return json.loads(response) except json.JSONDecodeError as e: @@ -92,10 +93,12 @@ def start(state: AgentState): + """Initialize the workflow with the input mess...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/main.py
Generate docstrings for script automation
import platform import subprocess import requests import time from typing import List import questionary from colorama import Fore, Style import os from . import docker # Constants DEFAULT_OLLAMA_SERVER_URL = "http://localhost:11434" def _get_ollama_base_url() -> str: url = os.environ.get("OLLAMA_BASE_URL", DEF...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for working with Ollama models""" import platform import subprocess @@ -14,6 +15,7 @@ def _get_ollama_base_url() -> str: + """Return the configured Ollama base URL, trimming any trailing slash.""" url = os.environ.get("OLLAMA_BASE_URL", DEFAULT_OLLAMA_SERVER_URL) ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/utils/ollama.py
Generate NumPy-style docstrings
from src.graph.state import AgentState, show_agent_reasoning from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel, Field import json from typing_extensions import Literal from src.tools.api import get_financial_metrics, get_market_cap, sea...
--- +++ @@ -17,6 +17,7 @@ def warren_buffett_agent(state: AgentState, agent_id: str = "warren_buffett_agent"): + """Analyzes stocks using Buffett's principles and LLM reasoning.""" data = state["data"] end_date = data["end_date"] tickers = data["tickers"] @@ -153,6 +154,7 @@ def analyze_fundam...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/warren_buffett.py
Create docstrings for API functions
from src.graph.state import AgentState, show_agent_reasoning from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel import json from typing_extensions import Literal from src.tools.api import get_financial_metrics, get_market_cap, search_lin...
--- +++ @@ -15,6 +15,7 @@ reasoning: str def rakesh_jhunjhunwala_agent(state: AgentState, agent_id: str = "rakesh_jhunjhunwala_agent"): + """Analyzes stocks using Rakesh Jhunjhunwala's principles and LLM reasoning.""" data = state["data"] end_date = data["end_date"] tickers = data["tickers"] @@...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/rakesh_jhunjhunwala.py
Add clean documentation to messy code
from src.agents import portfolio_manager from src.agents.aswath_damodaran import aswath_damodaran_agent from src.agents.ben_graham import ben_graham_agent from src.agents.bill_ackman import bill_ackman_agent from src.agents.cathie_wood import cathie_wood_agent from src.agents.charlie_munger import charlie_munger_agent...
--- +++ @@ -1,3 +1,4 @@+"""Constants and utilities related to analysts configuration.""" from src.agents import portfolio_manager from src.agents.aswath_damodaran import aswath_damodaran_agent @@ -172,10 +173,12 @@ def get_analyst_nodes(): + """Get the mapping of analyst keys to their (node_name, agent_func)...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/utils/analysts.py
Document all public functions with docstrings
from fastapi import APIRouter, HTTPException, Depends from sqlalchemy.orm import Session from typing import List from app.backend.database import get_db from app.backend.repositories.api_key_repository import ApiKeyRepository from app.backend.models.schemas import ( ApiKeyCreateRequest, ApiKeyUpdateRequest, ...
--- +++ @@ -25,6 +25,7 @@ }, ) async def create_or_update_api_key(request: ApiKeyCreateRequest, db: Session = Depends(get_db)): + """Create a new API key or update existing one""" try: repo = ApiKeyRepository(db) api_key = repo.create_or_update_api_key( @@ -46,6 +47,7 @@ }, ) async...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/routes/api_keys.py
Write docstrings describing each step
import math from langchain_core.messages import HumanMessage from src.graph.state import AgentState, show_agent_reasoning from src.utils.api_key import get_api_key_from_state import json import pandas as pd import numpy as np from src.tools.api import get_prices, prices_to_df from src.utils.progress import progress ...
--- +++ @@ -13,6 +13,16 @@ def safe_float(value, default=0.0): + """ + Safely convert a value to float, handling NaN cases + + Args: + value: The value to convert (can be pandas scalar, numpy value, etc.) + default: Default value to return if the input is NaN or invalid + + Returns...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/technicals.py
Help me comply with documentation standards
import requests import time from colorama import Fore, Style import questionary def ensure_ollama_and_model(model_name: str, ollama_url: str) -> bool: print(f"{Fore.CYAN}Using Ollama endpoint at {ollama_url}{Style.RESET_ALL}") # Step 1: Check if Ollama service is available if not is_ollama_available(...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for working with Ollama models in Docker environments""" import requests import time @@ -5,6 +6,7 @@ import questionary def ensure_ollama_and_model(model_name: str, ollama_url: str) -> bool: + """Ensure the Ollama model is available at the target Ollama endpoint.""" p...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/utils/docker.py
Write docstrings describing each step
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import ( get_financial_metrics, get_market_cap, search_line_items, get_insider_trades, get_company_news, get_prices, ) from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMe...
--- +++ @@ -24,6 +24,15 @@ def stanley_druckenmiller_agent(state: AgentState, agent_id: str = "stanley_druckenmiller_agent"): + """ + Analyzes stocks using Stanley Druckenmiller's investing principles: + - Seeking asymmetric risk-reward opportunities + - Emphasizing growth, momentum, and sentiment +...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/stanley_druckenmiller.py
Add inline docstrings for readability
# coding=utf-8 import json import os import re import smtplib import time from datetime import datetime from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr, formatdate, make_msgid from pathlib import Path from typing imp...
--- +++ @@ -1,4 +1,10 @@ # coding=utf-8 +""" +通知推送工具 + +支持向已配置的通知渠道发送消息,自动检测 config.yaml 和 .env 中的渠道配置。 +接受 markdown 格式内容,内部按各渠道要求自动转换格式后发送。 +""" import json import os @@ -89,6 +95,20 @@ def _split_text_into_batches(text: str, max_bytes: int) -> List[str]: + """将文本按字节限制分批,优先在段落边界(双换行)切割 + + 分割策略(参考 trendr...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/notification.py
Add docstrings to my Python code
from __future__ import annotations """Growth Agent Implements a growth-focused valuation methodology. """ import json import statistics from langchain_core.messages import HumanMessage from src.graph.state import AgentState, show_agent_reasoning from src.utils.progress import progress from src.utils.api_key import g...
--- +++ @@ -17,6 +17,7 @@ ) def growth_analyst_agent(state: AgentState, agent_id: str = "growth_analyst_agent"): + """Run growth analysis across tickers and write signals back to `state`.""" data = state["data"] end_date = data["end_date"] @@ -135,6 +136,7 @@ ############################# def _calc...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/growth_agent.py
Generate missing documentation strings
from typing import Dict, List, Optional, Union from ..services.data_service import DataService from ..utils.validators import ( validate_platforms, validate_limit, validate_keyword, validate_date_range, validate_top_n, validate_mode, validate_date_query, normalize_date_range ) from ..u...
--- +++ @@ -1,3 +1,8 @@+""" +数据查询工具 + +实现P0核心的数据查询工具。 +""" from typing import Dict, List, Optional, Union @@ -16,8 +21,15 @@ class DataQueryTools: + """数据查询工具类""" def __init__(self, project_root: str = None): + """ + 初始化数据查询工具 + + Args: + project_root: 项目根目录 + "...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/data_query.py
Include argument descriptions in docstrings
class Cache: def __init__(self): self._prices_cache: dict[str, list[dict[str, any]]] = {} self._financial_metrics_cache: dict[str, list[dict[str, any]]] = {} self._line_items_cache: dict[str, list[dict[str, any]]] = {} self._insider_trades_cache: dict[str, list[dict[str, any]]] = {}...
--- +++ @@ -1,4 +1,5 @@ class Cache: + """In-memory cache for API responses.""" def __init__(self): self._prices_cache: dict[str, list[dict[str, any]]] = {} @@ -8,6 +9,7 @@ self._company_news_cache: dict[str, list[dict[str, any]]] = {} def _merge_data(self, existing: list[dict] | None,...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/data/cache.py
Generate descriptive docstrings automatically
import re from collections import Counter from datetime import datetime, timedelta from typing import Dict, List, Optional, Tuple from .cache_service import get_cache from .parser_service import ParserService from ..utils.errors import DataNotFoundError class DataService: # 中文停用词列表(用于 auto_extract 模式) STOP...
--- +++ @@ -1,3 +1,8 @@+""" +数据访问服务 + +提供统一的数据查询接口,封装数据访问逻辑。 +""" import re from collections import Counter @@ -10,6 +15,7 @@ class DataService: + """数据访问服务类""" # 中文停用词列表(用于 auto_extract 模式) STOPWORDS = { @@ -28,6 +34,12 @@ } def __init__(self, project_root: str = None): + """ +...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/services/data_service.py
Add clean documentation to messy code
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import get_financial_metrics, get_market_cap, search_line_items from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel import json from typing_extensions import ...
--- +++ @@ -17,6 +17,7 @@ def mohnish_pabrai_agent(state: AgentState, agent_id: str = "mohnish_pabrai_agent"): + """Evaluate stocks using Mohnish Pabrai's checklist and 'heads I win, tails I don't lose much' approach.""" data = state["data"] end_date = data["end_date"] tickers = data["tickers"] @@...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/mohnish_pabrai.py
Create documentation strings for testing functions
import re import sqlite3 from pathlib import Path from typing import Dict, List, Tuple, Optional from datetime import datetime import yaml from ..utils.errors import FileParseError, DataNotFoundError from .cache_service import get_cache class ParserService: def __init__(self, project_root: str = None): ...
--- +++ @@ -1,3 +1,9 @@+""" +数据解析服务 + +v2.0.0: 仅支持 SQLite 数据库,移除 TXT 文件支持 +新存储结构:output/{type}/{date}.db +""" import re import sqlite3 @@ -12,8 +18,15 @@ class ParserService: + """数据解析服务类""" def __init__(self, project_root: str = None): + """ + 初始化解析服务 + + Args: + proje...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/services/parser_service.py
Add standardized docstrings across the file
import datetime import logging import os import pandas as pd import requests import time logger = logging.getLogger(__name__) from src.data.cache import get_cache from src.data.models import ( CompanyNews, CompanyNewsResponse, FinancialMetrics, FinancialMetricsResponse, Price, PriceResponse, ...
--- +++ @@ -27,6 +27,22 @@ def _make_api_request(url: str, headers: dict, method: str = "GET", json_data: dict = None, max_retries: int = 3) -> requests.Response: + """ + Make an API request with rate limiting handling and moderate backoff. + + Args: + url: The URL to request + headers: H...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/tools/api.py
Generate docstrings with parameter types
import os import json from langchain_anthropic import ChatAnthropic from langchain_deepseek import ChatDeepSeek from langchain_google_genai import ChatGoogleGenerativeAI from langchain_groq import ChatGroq from langchain_xai import ChatXAI from langchain_openai import ChatOpenAI, AzureChatOpenAI from langchain_gigachat...
--- +++ @@ -15,6 +15,7 @@ class ModelProvider(str, Enum): + """Enum for supported LLM providers""" ALIBABA = "Alibaba" ANTHROPIC = "Anthropic" @@ -32,18 +33,22 @@ class LLMModel(BaseModel): + """Represents an LLM model configuration""" display_name: str model_name: str provide...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/llm/models.py
Create docstrings for all classes and functions
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import ( get_market_cap, search_line_items, get_insider_trades, get_company_news, ) from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel import...
--- +++ @@ -22,6 +22,17 @@ def phil_fisher_agent(state: AgentState, agent_id: str = "phil_fisher_agent"): + """ + Analyzes stocks using Phil Fisher's investing principles: + - Seek companies with long-term above-average growth potential + - Emphasize quality of management and R&D + - Look for s...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/phil_fisher.py
Add professional docstrings to my codebase
from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import ( get_market_cap, search_line_items, get_insider_trades, get_company_news, ) from langchain_core.prompts import ChatPromptTemplate from langchain_core.messages import HumanMessage from pydantic import BaseModel import...
--- +++ @@ -16,12 +16,28 @@ class PeterLynchSignal(BaseModel): + """ + Container for the Peter Lynch-style output signal. + """ signal: Literal["bullish", "bearish", "neutral"] confidence: float reasoning: str def peter_lynch_agent(state: AgentState, agent_id: str = "peter_lynch_agent")...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/peter_lynch.py
Improve documentation using docstrings
from typing import Dict, Optional, Any, TypedDict from ..services.data_service import DataService from ..utils.validators import validate_config_section from ..utils.errors import MCPError class ErrorInfo(TypedDict, total=False): code: str message: str suggestion: str class ConfigResult(TypedDict): ...
--- +++ @@ -1,3 +1,8 @@+""" +配置管理工具 + +实现配置查询和管理功能。 +""" from typing import Dict, Optional, Any, TypedDict @@ -7,12 +12,14 @@ class ErrorInfo(TypedDict, total=False): + """错误信息结构""" code: str message: str suggestion: str class ConfigResult(TypedDict): + """配置查询结果 - success 字段必需,其他字段可选...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/config_mgmt.py
Include argument descriptions in docstrings
from __future__ import annotations from datetime import datetime, timedelta import json from typing_extensions import Literal from src.graph.state import AgentState, show_agent_reasoning from langchain_core.messages import HumanMessage from langchain_core.prompts import ChatPromptTemplate from pydantic import BaseMod...
--- +++ @@ -22,6 +22,7 @@ class MichaelBurrySignal(BaseModel): + """Schema returned by the LLM.""" signal: Literal["bullish", "bearish", "neutral"] confidence: float # 0–100 @@ -29,6 +30,7 @@ def michael_burry_agent(state: AgentState, agent_id: str = "michael_burry_agent"): + """Analyse stock...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/michael_burry.py
Fully document this Python code with docstrings
import time from typing import Dict, List import requests from ..utils.errors import MCPError, InvalidParameterError # Jina Reader 配置 JINA_READER_BASE = "https://r.jina.ai" DEFAULT_TIMEOUT = 30 # 秒 MAX_BATCH_SIZE = 5 # 单次批量最大篇数 BATCH_INTERVAL = 5.0 # 批量请求间隔(秒) class ArticleReaderTools: def __init__(self,...
--- +++ @@ -1,3 +1,10 @@+""" +文章内容读取工具 + +通过 Jina AI Reader API 将 URL 转换为 LLM 友好的 Markdown 格式。 +支持单篇和批量读取,内置速率限制和并发控制。 + +""" import time from typing import Dict, List @@ -15,13 +22,22 @@ class ArticleReaderTools: + """文章内容读取工具类""" def __init__(self, project_root: str = None, jina_api_key: str = None)...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/article_reader.py
Write docstrings for data processing functions
import hashlib import json import time from typing import Any, Optional from threading import Lock def make_cache_key(namespace: str, **params) -> str: if not params: return namespace # 对参数进行规范化处理 normalized_params = {} for k, v in params.items(): if v is None: continue ...
--- +++ @@ -1,3 +1,8 @@+""" +缓存服务 + +实现TTL缓存机制,提升数据访问性能。 +""" import hashlib import json @@ -7,6 +12,24 @@ def make_cache_key(namespace: str, **params) -> str: + """ + 生成结构化缓存 key + + 通过对参数排序和哈希,确保相同参数组合总是生成相同的 key。 + + Args: + namespace: 缓存命名空间,如 "latest_news", "trending_topics" + **p...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/services/cache_service.py
Add standardized docstrings across the file
from datetime import datetime, timezone from rich.console import Console from rich.live import Live from rich.table import Table from rich.style import Style from rich.text import Text from typing import Dict, Optional, Callable, List console = Console() class AgentProgress: def __init__(self): self.age...
--- +++ @@ -10,6 +10,7 @@ class AgentProgress: + """Manages progress tracking for multiple agents.""" def __init__(self): self.agent_status: Dict[str, Dict[str, str]] = {} @@ -19,24 +20,29 @@ self.update_handlers: List[Callable[[str, Optional[str], str], None]] = [] def register_ha...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/utils/progress.py
Generate missing documentation strings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import subprocess import time import signal from pathlib import Path from datetime import datetime # Web 服务器配置 WEBSERVER_PORT = int(os.environ.get("WEBSERVER_PORT", "8080")) WEBSERVER_DIR = "/app/output" WEBSERVER_PID_FILE = "/tmp/webserver.pid" WEBS...
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +新闻爬虫容器管理工具 - supercronic +""" import os import sys @@ -17,6 +20,7 @@ def _env_bool(name: str, default: bool) -> bool: + """读取布尔环境变量,兼容 true/1/yes/on。""" value = os.environ.get(name) if value is None: return defau...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/docker/manage.py
Create documentation strings for testing functions
from langchain_core.messages import HumanMessage from src.graph.state import AgentState, show_agent_reasoning from src.utils.progress import progress from src.tools.api import get_prices, prices_to_df import json import numpy as np import pandas as pd from src.utils.api_key import get_api_key_from_state ##### Risk Man...
--- +++ @@ -9,6 +9,7 @@ ##### Risk Management Agent ##### def risk_management_agent(state: AgentState, agent_id: str = "risk_management_agent"): + """Controls position sizing based on volatility-adjusted risk factors for multiple tickers.""" portfolio = state["data"]["portfolio"] data = state["data"] ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/risk_manager.py
Write docstrings for this repository
import asyncio import json from typing import List, Optional, Dict, Union from fastmcp import FastMCP from .tools.data_query import DataQueryTools from .tools.analytics import AnalyticsTools from .tools.search_tools import SearchTools from .tools.config_mgmt import ConfigManagementTools from .tools.system import Sys...
--- +++ @@ -1,3 +1,9 @@+""" +TrendRadar MCP Server - FastMCP 2.0 实现 + +使用 FastMCP 2.0 提供生产级 MCP 工具服务器。 +支持 stdio 和 HTTP 两种传输模式。 +""" import asyncio import json @@ -25,6 +31,7 @@ def _get_tools(project_root: Optional[str] = None): + """获取或创建工具实例(单例模式)""" if not _tools_instances: _tools_instances...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/server.py
Annotate my code with docstrings
import os import re from collections import Counter, defaultdict from datetime import datetime, timedelta from typing import Dict, List, Optional, Union from difflib import SequenceMatcher import yaml from trendradar.core.analyzer import calculate_news_weight as _calculate_news_weight from ..services.data_service i...
--- +++ @@ -1,3 +1,8 @@+""" +高级数据分析工具 + +提供热度趋势分析、平台对比、关键词共现、情感分析等高级分析功能。 +""" import os import re @@ -35,6 +40,14 @@ def _get_weight_config() -> Dict: + """ + 从 config.yaml 读取权重配置(带 mtime 缓存) + + 仅当配置文件被修改时才重新读取,避免循环内重复 IO。 + + Returns: + 权重配置字典,包含 RANK_WEIGHT, FREQUENCY_WEIGHT, HOTNESS_WEIG...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/analytics.py
Write documentation strings for class attributes
from langchain_core.messages import HumanMessage from pydantic import BaseModel, Field from src.data.models import CompanyNews import pandas as pd import numpy as np import json from src.graph.state import AgentState, show_agent_reasoning from src.tools.api import get_company_news from src.utils.api_key import get_a...
--- +++ @@ -16,12 +16,27 @@ class Sentiment(BaseModel): + """Represents the sentiment of a news article.""" sentiment: Literal["positive", "negative", "neutral"] confidence: int = Field(description="Confidence 0-100") def news_sentiment_agent(state: AgentState, agent_id: str = "news_sentiment_ag...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/news_sentiment.py
Add detailed docstrings explaining each function
import json import time from langchain_core.messages import HumanMessage from langchain_core.prompts import ChatPromptTemplate from src.graph.state import AgentState, show_agent_reasoning from pydantic import BaseModel, Field from typing_extensions import Literal from src.utils.progress import progress from src.utils....
--- +++ @@ -23,6 +23,7 @@ ##### Portfolio Management Agent ##### def portfolio_management_agent(state: AgentState, agent_id: str = "portfolio_manager"): + """Makes final trading decisions and generates orders for multiple tickers""" portfolio = state["data"]["portfolio"] analyst_signals = state["data"...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/agents/portfolio_manager.py