Commit ·
bb3e0eb
1
Parent(s): 5ade0c3
unified ref tag and imporved read_file
Browse filesFiles changed (6)
105 unmodified lines106107108109110111112225 unmodified lines338339340341342343344345105 unmodified linesfiles = [{"path": item["path"],"sha": item["sha"],"size": item.get("size", 0),"url": f"https://github.com/{full_repo}/blob/{default_branch}/{item['path']}",}225 unmodified linesfor i, file in enumerate(results, 1):lines.append(f"{i}. **{file['path']}** (score: {file['score']})")lines.append(f" Size: {file['size']:,} bytes | SHA: {file['sha'][:7]}")lines.append(f" URL: {file['url']}")lines.append("")return {105 unmodified lines106107108109110111112225 unmodified lines338339340341342343344345346347348349105 unmodified linesfiles = [{"path": item["path"],"ref": item["sha"],"size": item.get("size", 0),"url": f"https://github.com/{full_repo}/blob/{default_branch}/{item['path']}",}225 unmodified linesfor i, file in enumerate(results, 1):lines.append(f"{i}. **{file['path']}** (score: {file['score']})")lines.append(f" Size: {file['size']:,} bytes | Ref: {file['ref'][:7]}")lines.append(f" URL: {file['url']}")# Copyable parameters for read_file toolread_params = f"{{'repo': '{org}/{repo}', 'path': '{file['path']}'}}"lines.append(f" To read, use: {read_params}")lines.append("")return {
185 unmodified lines186187188189190191185 unmodified lineslines.append(f" URL: {repo['html_url']}")if repo["topics"]:lines.append(f" Topics: {', '.join(repo['topics'][:5])}")lines.append("")return {185 unmodified lines186187188189190191192193194185 unmodified lineslines.append(f" URL: {repo['html_url']}")if repo["topics"]:lines.append(f" Topics: {', '.join(repo['topics'][:5])}")# Copyable parameters for other toolslines.append(f" Use in tools: {{'repo': '{repo['full_name']}'}}")lines.append("")return {
4 unmodified lines56789101112131415161718107 unmodified lines1261271281291301311321331341351361371381391401411 unmodified line14314414514614714814920 unmodified lines17017117217317417517617717817918018118218318418518618718818919019 unmodified lines2102112122132142152162172182192202214 unmodified lines"""import base64import osfrom typing import Any, Dict, Optionalimport requestsfrom agent.tools.types import ToolResultdef read_file(repo: str,path: str,107 unmodified lines}content = raw_response.text# Get metadatafile_sha = data.get("sha")file_size = data.get("size", 0)# Process line rangeslines = content.split("\n")total_lines = len(lines)truncated = Falsemessage = Noneif line_start is None and line_end is None:# No range specified1 unmodified lineline_start = 1line_end = 300truncated = Truemessage = f"File has {total_lines} lines. Showing first 300 lines. Use line_start and line_end to view more."else:line_start = 1line_end = total_lines20 unmodified linesselected_content = "\n".join(selected_lines)# Format outputlines_output = [f"**File: {repo}/{path}**"]lines_output.append(f"SHA: {file_sha}")lines_output.append(f"Size: {file_size:,} bytes")lines_output.append(f"Lines: {line_start}-{line_end} of {total_lines} total lines")if ref and ref != "HEAD":lines_output.append(f"Ref: {ref}")if truncated and message:lines_output.append(f"⚠️ {message}")lines_output.append("\n**Content:**")lines_output.append("```")lines_output.append(selected_content)lines_output.append("```")return {"formatted": "\n".join(lines_output),"totalResults": 1,19 unmodified lines"- Auto-truncates large files to 300 lines (with warning)\n""- Works with any branch, tag, or commit SHA\n""- Returns file metadata (SHA, size, line count)\n""- Handles both small and large files efficiently\n\n""## Examples:\n\n""**Read entire README:**\n""{'repo': 'facebook/react', 'path': 'README.md'}\n\n""**Read specific line range:**\n""{'repo': 'torvalds/linux', 'path': 'kernel/sched/core.c', 'line_start': 100, 'line_end': 150}\n\n""**Read from specific branch:**\n""{'repo': 'python/cpython', 'path': 'Lib/ast.py', 'ref': 'main', 'line_start': 1, 'line_end': 50}\n\n""**Read from specific commit:**\n"4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869107 unmodified lines1771781791801811821831841851861871881891901 unmodified line19219319419519619720 unmodified lines21821922022122222322422522622722822923023123223323423523619 unmodified lines2562572582592602612622632642652664 unmodified lines"""import base64import jsonimport osfrom typing import Any, Dict, Optionalimport nbformatimport requestsfrom nbconvert import MarkdownExporterfrom nbconvert.preprocessors import ClearOutputPreprocessor, TagRemovePreprocessorfrom agent.tools.types import ToolResultdef _convert_ipynb_to_markdown(content: str) -> str:"""Convert Jupyter notebook JSON to LLM-friendly Markdown.Args:content: Raw notebook JSON stringReturns:Converted Markdown string"""try:# Parse notebook JSONnb_dict = json.loads(content)# Normalize cell sources (can be string or list of strings)if "cells" in nb_dict:for cell in nb_dict["cells"]:if "source" in cell and isinstance(cell["source"], list):cell["source"] = "".join(cell["source"])# Read notebook with explicit versionnb = nbformat.reads(json.dumps(nb_dict), as_version=4)# Strip outputs for LLM readability (outputs can be noisy/large)clear = ClearOutputPreprocessor()nb, _ = clear.preprocess(nb, {})# Optionally remove cells tagged with "hide" or similarremove = TagRemovePreprocessor(remove_cell_tags={"hide", "hidden", "remove"},remove_input_tags=set(),remove_all_outputs_tags=set(),)nb, _ = remove.preprocess(nb, {})# Convert to markdownexporter = MarkdownExporter()markdown, _ = exporter.from_notebook_node(nb)return markdownexcept json.JSONDecodeError:return contentexcept Exception:return contentdef read_file(repo: str,path: str,107 unmodified lines}content = raw_response.textif path.lower().endswith(".ipynb"):content = _convert_ipynb_to_markdown(content)# Process line rangeslines = content.split("\n")total_lines = len(lines)truncated = Falseif line_start is None and line_end is None:# No range specified1 unmodified lineline_start = 1line_end = 300truncated = Trueelse:line_start = 1line_end = total_lines20 unmodified linesselected_content = "\n".join(selected_lines)# Format outputlines_output = [f"**Reading file from repo: {repo}, path: {path}**"]if ref and ref != "HEAD":lines_output.append(f"Ref: {ref}")lines_output.append("\n**File content:")lines_output.append("```")lines_output.append(selected_content)lines_output.append("```")if truncated:lines_output.append(f"Currently showing lines {line_start}-{line_end} out of {total_lines} total lines. Use line_start and line_end to view more lines.")return {"formatted": "\n".join(lines_output),"totalResults": 1,19 unmodified lines"- Auto-truncates large files to 300 lines (with warning)\n""- Works with any branch, tag, or commit SHA\n""- Returns file metadata (SHA, size, line count)\n""## Examples:\n\n""**Read entire README:**\n""{'repo': 'huggingface/transformers', 'path': 'README.md'}\n\n""**Read specific line range:**\n""{'repo': 'huggingface/trl', 'path': '/examples/scripts/grpo_vlm.py', 'line_start': 100, 'line_end': 150}\n\n""**Read from specific branch:**\n""{'repo': 'python/cpython', 'path': 'Lib/ast.py', 'ref': 'main', 'line_start': 1, 'line_end': 50}\n\n""**Read from specific commit:**\n"
214 unmodified lines215216217218219220214 unmodified lines)lines_output.append(f" URL: {match['url']}")# Show snippet (first 5 lines)snippet_lines = match["snippet"].split("\n")[:5]if snippet_lines:214 unmodified lines215216217218219220221222223224214 unmodified lines)lines_output.append(f" URL: {match['url']}")# Copyable parameters for read_file toolread_params = f"{{'repo': '{match['repo']}', 'path': '{match['path']}', 'ref': '{match['ref'][:7]}'}}"lines_output.append(f" To read, use: {read_params}")# Show snippet (first 5 lines)snippet_lines = match["snippet"].split("\n")[:5]if snippet_lines:
23 unmodified lines2425262723 unmodified lines"ipykernel>=7.1.0","ipywidgets>=8.1.8","thefuzz>=0.22.1",]23 unmodified lines2425262728293023 unmodified lines"ipykernel>=7.1.0","ipywidgets>=8.1.8","thefuzz>=0.22.1","nbconvert>=7.16.6","nbformat>=5.10.4","markitdown[all,docx,outlook,pdf,pptx,xls,xlsx]>=0.1.4",]
agent/tools/github_find_examples.py+6-2
agent/tools/github_list_repos.py+3
agent/tools/github_read_file.py+63-18
agent/tools/github_search_code.py+4
pyproject.toml+3
uv.lock