Skip to content

feat: adds extra tools to codebase agent #594

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/codegen/agents/code_agent.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
from typing import Optional
from uuid import uuid4

from langchain.tools import BaseTool

from codegen.extensions.langchain.agent import create_codebase_agent
from codegen.sdk.core.codebase import Codebase


class CodeAgent:
"""Agent for interacting with a codebase."""

def __init__(self, codebase: Codebase):
def __init__(self, codebase: Codebase, tools: Optional[list[BaseTool]] = None):
self.codebase = codebase
self.agent = create_codebase_agent(self.codebase)
self.agent = create_codebase_agent(self.codebase, additional_tools=tools)

def run(self, prompt: str, session_id: Optional[str] = None) -> str:
if session_id is None:
Expand Down
8 changes: 8 additions & 0 deletions src/codegen/extensions/langchain/agent.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Demo implementation of an agent with Codegen tools."""

from typing import Optional

from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.agents.openai_functions_agent.base import OpenAIFunctionsAgent
from langchain.hub import pull
Expand Down Expand Up @@ -34,6 +36,7 @@ def create_codebase_agent(
temperature: float = 0,
verbose: bool = True,
chat_history: list[BaseMessage] = [],
additional_tools: Optional[list[BaseTool]] = None,
) -> RunnableWithMessageHistory:
"""Create an agent with all codebase tools.

Expand All @@ -42,6 +45,8 @@ def create_codebase_agent(
model_name: Name of the model to use (default: gpt-4)
temperature: Model temperature (default: 0)
verbose: Whether to print agent's thought process (default: True)
chat_history: Optional list of messages to initialize chat history with
additional_tools: Optional list of additional tools to provide to the agent

Returns:
Initialized agent with message history
Expand Down Expand Up @@ -78,6 +83,9 @@ def create_codebase_agent(
# GithubCreatePRCommentTool(codebase),
# GithubCreatePRReviewCommentTool(codebase),
]
# Add additional tools if provided
if additional_tools:
tools.extend(additional_tools)

prompt = ChatPromptTemplate.from_messages(
[
Expand Down
4 changes: 4 additions & 0 deletions src/codegen/sdk/core/codebase.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@
TExport = TypeVar("TExport", bound="Export", default=Export)
TSGlobalVar = TypeVar("TSGlobalVar", bound="Assignment", default=Assignment)
PyGlobalVar = TypeVar("PyGlobalVar", bound="Assignment", default=Assignment)
TSDirectory = Directory[TSFile, TSSymbol, TSImportStatement, TSGlobalVar, TSClass, TSFunction, TSImport]

Check failure on line 107 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Cannot resolve name "TSDirectory" (possible cyclic definition) [misc]
PyDirectory = Directory[PyFile, PySymbol, PyImportStatement, PyGlobalVar, PyClass, PyFunction, PyImport]

Check failure on line 108 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Cannot resolve name "PyDirectory" (possible cyclic definition) [misc]


@apidoc
Expand Down Expand Up @@ -182,13 +182,13 @@
main_project = ProjectConfig.from_path(repo_path, programming_language=ProgrammingLanguage(language.upper()) if language else None)
projects = [main_project]
else:
main_project = projects[0]

Check failure on line 185 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Value of type "list[ProjectConfig] | None" is not indexable [index]

# Initialize codebase
self._op = main_project.repo_operator
self.viz = VisualizationManager(op=self._op)
self.repo_path = Path(self._op.repo_path)
self.ctx = CodebaseContext(projects, config=config, secrets=secrets, io=io, progress=progress)

Check failure on line 191 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Argument 1 to "CodebaseContext" has incompatible type "list[ProjectConfig] | None"; expected "list[ProjectConfig]" [arg-type]
self.console = Console(record=True, soft_wrap=True)

@noapidoc
Expand All @@ -204,7 +204,7 @@
yield "nodes", len(self.ctx.nodes)
yield "edges", len(self.ctx.edges)

__rich_repr__.angular = ANGULAR_STYLE

Check failure on line 207 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: "Callable[[Codebase[TSourceFile, TDirectory, TSymbol, TClass, TFunction, TImport, TGlobalVar, TInterface, TTypeAlias, TParameter, TCodeBlock]], Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]]]" has no attribute "angular" [attr-defined]

@property
@deprecated("Please do not use the local repo operator directly")
Expand Down Expand Up @@ -246,8 +246,8 @@

@noapidoc
def _symbols(self, symbol_type: SymbolType | None = None) -> list[TSymbol | TClass | TFunction | TGlobalVar]:
matches: list[Symbol] = self.ctx.get_nodes(NodeType.SYMBOL)

Check failure on line 249 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: Incompatible types in assignment (expression has type "list[Importable[Any]]", variable has type "list[Symbol[Any, Any]]") [assignment]
return [x for x in matches if x.is_top_level and (symbol_type is None or x.symbol_type == symbol_type)]

Check failure on line 250 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: List comprehension has incompatible type List[Symbol[Any, Any]]; expected List[TSymbol | TClass | TFunction | TGlobalVar] [misc]

# =====[ Node Types ]=====
@overload
Expand All @@ -256,7 +256,7 @@
def files(self, *, extensions: Literal["*"]) -> list[File]: ...
@overload
def files(self, *, extensions: None = ...) -> list[TSourceFile]: ...
@proxy_property

Check failure on line 259 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: "cached_property[ProxyProperty[[Codebase[TSourceFile, TDirectory, TSymbol, TClass, TFunction, TImport, TGlobalVar, TInterface, TTypeAlias, TParameter, TCodeBlock], DefaultNamedArg(list[str] | Literal['*'] | None, 'extensions')], list[TSourceFile] | list[File]]]" not callable [operator]
def files(self, *, extensions: list[str] | Literal["*"] | None = None) -> list[TSourceFile] | list[File]:
"""A list property that returns all files in the codebase.

Expand Down Expand Up @@ -291,13 +291,13 @@
return sort_editables(files, alphabetical=True, dedupe=False)

@cached_property
def codeowners(self) -> list["CodeOwner[TSourceFile]"]:

Check failure on line 294 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: "CodeOwner" expects 7 type arguments, but 1 given [type-arg]
"""List all CodeOnwers in the codebase.

Returns:
list[CodeOwners]: A list of CodeOwners objects in the codebase.
"""
if self.G.codeowners_parser is None:

Check failure on line 300 in src/codegen/sdk/core/codebase.py

View workflow job for this annotation

GitHub Actions / mypy

error: "Codebase[TSourceFile, TDirectory, TSymbol, TClass, TFunction, TImport, TGlobalVar, TInterface, TTypeAlias, TParameter, TCodeBlock]" has no attribute "G" [attr-defined]
return []
return CodeOwner.from_parser(self.G.codeowners_parser, lambda *args, **kwargs: self.files(*args, **kwargs))

Expand Down Expand Up @@ -1318,6 +1318,10 @@
patch = cg_pr.get_pr_diff()
return cg_pr.modified_symbols, patch

def create_pr_comment(self, pr_number: int, body: str) -> None:
"""Create a comment on a pull request"""
return self._op.create_pr_comment(pr_number, body)


# The last 2 lines of code are added to the runner. See codegen-backend/cli/generate/utils.py
# Type Aliases
Expand Down