diff --git a/.gitignore b/.gitignore index 128a69ab..6f6f4dac 100644 --- a/.gitignore +++ b/.gitignore @@ -175,6 +175,8 @@ ex/ **/ex/ cookiecutter.json +tests/tmp + examples/tests/ examples/tests/**/* diff --git a/MANIFEST.in b/MANIFEST.in index 1f7cc4f8..bf2bea26 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,4 @@ recursive-include agentstack/templates * +recursive-include agentstack/frameworks/templates * recursive-include agentstack/_tools * include agentstack.json .env .env.example \ No newline at end of file diff --git a/agentstack/agents.py b/agentstack/agents.py index f669435a..a2661d19 100644 --- a/agentstack/agents.py +++ b/agentstack/agents.py @@ -6,6 +6,7 @@ from ruamel.yaml.scalarstring import FoldedScalarString from agentstack import conf, log from agentstack.exceptions import ValidationError +from agentstack.providers import parse_provider_model AGENTS_FILENAME: Path = Path("src/config/agents.yaml") @@ -70,13 +71,13 @@ def __init__(self, name: str): @property def provider(self) -> str: - from agentstack import frameworks - return frameworks.parse_llm(self.llm)[0] + """The LLM provider ie. 'openai' or 'openrouter'""" + return parse_provider_model(self.llm)[0] @property def model(self) -> str: - from agentstack import frameworks - return frameworks.parse_llm(self.llm)[1] + """The model name ie. 'gpt-4o'""" + return parse_provider_model(self.llm)[1] @property def prompt(self) -> str: diff --git a/agentstack/cli/agentstack_data.py b/agentstack/cli/agentstack_data.py index 4337dd4d..8ccdb02b 100644 --- a/agentstack/cli/agentstack_data.py +++ b/agentstack/cli/agentstack_data.py @@ -2,7 +2,7 @@ from datetime import datetime from typing import Optional -from agentstack.utils import clean_input, get_version +from agentstack.utils import clean_input, get_version, snake_to_camel from agentstack import log @@ -11,6 +11,7 @@ def __init__( self, project_name: Optional[str] = None, project_slug: Optional[str] = None, + class_name: Optional[str] = None, description: str = "", author_name: str = "", version: str = "", @@ -21,6 +22,7 @@ def __init__( ): self.project_name = clean_input(project_name) if project_name else "myagent" self.project_slug = clean_input(project_slug) if project_slug else self.project_name + self.class_name = snake_to_camel(self.project_slug) if not class_name else class_name self.description = description self.author_name = author_name self.version = version @@ -36,6 +38,7 @@ def to_dict(self): return { 'project_name': self.project_name, 'project_slug': self.project_slug, + 'class_name': self.class_name, 'description': self.description, 'author_name': self.author_name, 'version': self.version, diff --git a/agentstack/cli/init.py b/agentstack/cli/init.py index 21864ea5..758db9b8 100644 --- a/agentstack/cli/init.py +++ b/agentstack/cli/init.py @@ -11,7 +11,7 @@ from agentstack import frameworks from agentstack import generation from agentstack import repo -from agentstack.proj_templates import get_all_templates, TemplateConfig +from agentstack.templates import get_all_templates, TemplateConfig from agentstack.cli import welcome_message from agentstack.cli.wizard import run_wizard @@ -80,7 +80,7 @@ def init_project( # TODO prevent the user from passing the --path argument to init if template and use_wizard: raise Exception("Template and wizard flags cannot be used together") - + require_uv() welcome_message() diff --git a/agentstack/cli/run.py b/agentstack/cli/run.py index 735dd5fd..3e142b19 100644 --- a/agentstack/cli/run.py +++ b/agentstack/cli/run.py @@ -1,5 +1,6 @@ from typing import Optional, List import sys +import asyncio import traceback from pathlib import Path import importlib.util @@ -122,7 +123,13 @@ def run_project(command: str = 'run', cli_args: Optional[List[str]] = None): try: log.notify("Running your agent...") project_main = _import_project_module(conf.PATH) - getattr(project_main, command)() + main = getattr(project_main, command) + + # handle both async and sync entrypoints + if asyncio.iscoroutinefunction(main): + asyncio.run(main()) + else: + main() except ImportError as e: raise ValidationError(f"Failed to import AgentStack project at: {conf.PATH.absolute()}\n{e}") except Exception as e: diff --git a/agentstack/cli/templates.py b/agentstack/cli/templates.py index 0cf2f6d5..81a99fec 100644 --- a/agentstack/cli/templates.py +++ b/agentstack/cli/templates.py @@ -10,7 +10,7 @@ from agentstack.agents import get_all_agents from agentstack.tasks import get_all_tasks from agentstack import inputs -from agentstack.proj_templates import CURRENT_VERSION, TemplateConfig +from agentstack.templates import CURRENT_VERSION, TemplateConfig from agentstack.generation.files import ProjectFile from .agentstack_data import ( FrameworkData, @@ -52,7 +52,7 @@ def insert_template(name: str, template: TemplateConfig, framework: Optional[str framework=framework, ) - template_path = get_package_path() / f'templates/{framework}' + template_path = get_package_path() / f'frameworks/templates/{framework}' with open(f"{template_path}/cookiecutter.json", "w") as json_file: json.dump(cookiecutter_data.to_dict(), json_file) # TODO this should not be written to the package directory diff --git a/agentstack/cli/wizard.py b/agentstack/cli/wizard.py index 7d0cf479..4ad24802 100644 --- a/agentstack/cli/wizard.py +++ b/agentstack/cli/wizard.py @@ -10,7 +10,7 @@ from agentstack.cli import welcome_message, get_validated_input from agentstack.cli.cli import PREFERRED_MODELS from agentstack._tools import get_all_tools, get_all_tool_names -from agentstack.proj_templates import TemplateConfig +from agentstack.templates import TemplateConfig class WizardData(dict): diff --git a/agentstack/frameworks/__init__.py b/agentstack/frameworks/__init__.py index 3cbd1ee1..8c45e41d 100644 --- a/agentstack/frameworks/__init__.py +++ b/agentstack/frameworks/__init__.py @@ -1,30 +1,54 @@ -from typing import TYPE_CHECKING, Optional, Protocol, Callable +from typing import Optional, Union, Protocol, Callable from types import ModuleType +from abc import ABCMeta, abstractmethod from importlib import import_module +from dataclasses import dataclass from pathlib import Path +import ast from agentstack import conf from agentstack.exceptions import ValidationError +from agentstack.generation import InsertionPoint from agentstack.utils import get_framework +from agentstack import packaging +from agentstack.generation import asttools from agentstack.agents import AgentConfig, get_all_agent_names from agentstack.tasks import TaskConfig, get_all_task_names from agentstack._tools import ToolConfig from agentstack import graph -if TYPE_CHECKING: - from agentstack.generation import InsertionPoint - CREWAI = 'crewai' LANGGRAPH = 'langgraph' OPENAI_SWARM = 'openai_swarm' +LLAMAINDEX = 'llamaindex' SUPPORTED_FRAMEWORKS = [ CREWAI, LANGGRAPH, OPENAI_SWARM, + LLAMAINDEX, ] DEFAULT_FRAMEWORK = CREWAI +@dataclass +class Provider: + """ + An LLM provider definition. + + Used to install required dependencies and provide attributes for an + import statement. + """ + + class_name: str # The class we use to import and run the provider + module_name: str # The module we import from + dependencies: list[str] # Any dependencies needed for use + + def install_dependencies(self): + """Install the dependencies for the provider.""" + for dependency in self.dependencies: + packaging.install(dependency) + + class FrameworkModule(Protocol): """ Protocol spec for a framework implementation module. @@ -36,6 +60,12 @@ class FrameworkModule(Protocol): ie. `src/crewai.py` """ + def get_entrypoint(self) -> 'BaseEntrypointFile': + """ + Get the entrypoint file for the framework. + """ + ... + def validate_project(self) -> None: """ Validate that a user's project is ready to run. @@ -43,9 +73,15 @@ def validate_project(self) -> None: """ ... - def parse_llm(self, llm: str) -> tuple[str, str]: + def add_agent(self, agent: 'AgentConfig', position: Optional[InsertionPoint] = None) -> None: + """ + Add an agent to the user's project. """ - Parse a language model string into a provider and model. + ... + + def add_task(self, task: 'TaskConfig', position: Optional[InsertionPoint] = None) -> None: + """ + Add a task to the user's project. """ ... @@ -67,42 +103,194 @@ def wrap_tool(self, tool_func: Callable) -> Callable: """ ... - def get_agent_method_names(self) -> list[str]: + def get_graph(self) -> list[graph.Edge]: """ - Get a list of agent names in the user's project. + Get the graph of the user's project. """ ... - def get_agent_tool_names(self, agent_name: str) -> list[str]: + +class BaseEntrypointFile(asttools.File, metaclass=ABCMeta): + """ + This handles interactions with a Framework's entrypoint file that are common + to all frameworks. + + In most cases, we have a base class which contains a `run` method, and + methods decorated with `@agentstack.task` and `@agentstack.agent`. + + We match the base class with a regex pattern defined as `base_class_pattern`, + and the `run` method with a method named `run` which accepts `inputs` as a + keyword argument. + + Usually, it looks something like this: + ``` + class UserStack: + @agentstack.task + def task_name(self): + ... + + @agentstack.agent + def agent_name(self): + ... + + def run(self, inputs: list): + ... + ``` + """ + + base_class_pattern: str = r'\w+Stack$' + agent_decorator_name: str = 'agent' + task_decorator_name: str = 'task' + + def get_import(self, module_name: str, attributes: str) -> Optional[ast.ImportFrom]: """ - Get a list of tool names in an agent in the user's project. + Return an import statement for a module and class if it exists in the file. """ - ... + for node in asttools.get_all_imports(self.tree): + names_str = ', '.join(alias.name for alias in node.names) + if node.module == module_name and names_str == attributes: + return node + return None - def add_agent(self, agent: 'AgentConfig', position: Optional['InsertionPoint'] = None) -> None: + def add_import(self, module_name: str, attributes: str): """ - Add an agent to the user's project. + Add an import statement to the file. """ - ... + # add the import after existing imports, or at the beginning of the file + all_imports = asttools.get_all_imports(self.tree) + _, end = self.get_node_range(all_imports[-1]) if all_imports else (0, 0) + + code = f"from {module_name} import {attributes}\n" + if not self.source[:end].endswith('\n'): + code = '\n' + code - def add_task(self, task: 'TaskConfig', position: Optional['InsertionPoint'] = None) -> None: + self.edit_node_range(end, end, code) + + def get_base_class(self) -> ast.ClassDef: """ - Add a task to the user's project. + A base class is the first class inside of the file that follows the + naming convention: `Graph` """ - ... + pattern = self.base_class_pattern + try: + return asttools.find_class_with_regex(self.tree, pattern)[0] + except IndexError: + raise ValidationError(f"`{pattern}` class not found in {self.filename}") + + def get_run_method(self) -> Union[ast.FunctionDef, ast.AsyncFunctionDef]: + """A method named `run` in the base class which accepts `inputs` as a keyword argument.""" + try: + base_class = self.get_base_class() + node = asttools.find_method_in_class(base_class, 'run') + assert node + except AssertionError: + raise ValidationError(f"`run` method not found in `{base_class.name}` class in {self.filename}.") + + try: + assert 'inputs' in (arg.arg for arg in node.args.args) + return node + except AssertionError: + raise ValidationError(f"Method `run` of `{base_class.name}` must accept `inputs` as a kwarg.") + + def get_task_methods(self) -> list[ast.FunctionDef]: + """A `task` method is a method decorated with `@`.""" + return asttools.find_decorated_method_in_class(self.get_base_class(), self.task_decorator_name) def get_task_method_names(self) -> list[str]: - """ - Get a list of task names in the user's project. - """ - ... + """Get a list of task names (methods with an @task decorator).""" + return [method.name for method in self.get_task_methods()] + + # not marked as abstract because you can override `add_task_method` for more + # control over adding new task methods if you need to + def get_new_task_method(self, task: TaskConfig) -> str: + """Get the content of a new task method.""" + # TODO allow returning `Union[str, ast.AST]` + raise NotImplementedError("Subclass must implement `get_new_task_method` to support insertion.") + + def add_task_method(self, task: TaskConfig): + """Add a new task method to the entrypoint.""" + task_methods = self.get_task_methods() + if task_methods: + # Add after the existing task methods + _, pos = self.get_node_range(task_methods[-1]) + else: + # Add before the `run` method + pos, _ = self.get_node_range(self.get_run_method()) + + self.insert_method(pos, self.get_new_task_method(task)) + + def get_agent_methods(self) -> list[ast.FunctionDef]: + """An `agent` method is a method decorated with `@`.""" + return asttools.find_decorated_method_in_class(self.get_base_class(), self.agent_decorator_name) - def get_graph(self) -> list[graph.Edge]: - """ - Get the graph of the user's project. - """ + def get_agent_method_names(self) -> list[str]: + """Get a list of agent names (methods with an @agent decorator).""" + return [method.name for method in self.get_agent_methods()] + + # not marked as abstract because you can override `add_agent_method` for more + # control over adding new agent methods if you need to + def get_new_agent_method(self, agent: AgentConfig) -> str: + """Get the content of a new agent method.""" + # TODO allow returning `Union[str, ast.AST]` + raise NotImplementedError("Subclass must implement `get_new_agent_method` to support insertion.") + + def add_agent_method(self, agent: AgentConfig): + """Add a new agent method to the LangGraph entrypoint.""" + agent_methods = self.get_agent_methods() + if agent_methods: + # Add after the existing agent methods + _, pos = self.get_node_range(agent_methods[-1]) + else: + # Add before the `run` method + pos, _ = self.get_node_range(self.get_run_method()) + + self.insert_method(pos, self.get_new_agent_method(agent)) + + @abstractmethod + def get_agent_tools(self, agent_name: str) -> ast.List: + """Get the list of tools used by an agent as an AST List node.""" ... + def get_agent_tool_nodes(self, agent_name: str) -> list[ast.Starred]: + """Get a list of all ast nodes that define agentstack tools used by the agent.""" + agent_tools_node = self.get_agent_tools(agent_name) + return asttools.find_tool_nodes(agent_tools_node) + + def get_agent_tool_names(self, agent_name: str) -> list[str]: + """Get a list of all tools used by the agent.""" + # Tools are identified by the item name of an `agentstack.tools` attribute node. + tool_names: list[str] = [] + for node in self.get_agent_tool_nodes(agent_name): + # ignore type checking here since `get_agent_tool_nodes` is exhaustive + tool_names.append(node.value.slice.value) # type: ignore[attr-defined] + return tool_names + + def add_agent_tools(self, agent_name: str, tool: ToolConfig): + """Modify the existing tools list to add a new tool.""" + existing_node: ast.List = self.get_agent_tools(agent_name) + existing_elts: list[ast.expr] = existing_node.elts + + if not tool.name in self.get_agent_tool_names(agent_name): + existing_elts.append(asttools.create_tool_node(tool.name)) + + new_node = ast.List(elts=existing_elts, ctx=ast.Load()) + start, end = self.get_node_range(existing_node) + self.edit_node_range(start, end, new_node) + + def remove_agent_tools(self, agent_name: str, tool: ToolConfig): + """Modify the existing tools list to remove a tool.""" + existing_node: ast.List = self.get_agent_tools(agent_name) + start, end = self.get_node_range(existing_node) + + # we're referencing the internal node list from two directions here, + # so it's important that the node tree doesn't get re-parsed in between + for node in self.get_agent_tool_nodes(agent_name): + # ignore type checking here since `get_agent_tool_nodes` is exhaustive + if tool.name == node.value.slice.value: # type: ignore[attr-defined] + existing_node.elts.remove(node) + + self.edit_node_range(start, end, existing_node) + def get_framework_module(framework: str) -> FrameworkModule: """ @@ -118,7 +306,8 @@ def get_entrypoint_path(framework: str) -> Path: """ Get the path to the entrypoint file for a framework. """ - return conf.PATH / get_framework_module(framework).ENTRYPOINT + module = get_framework_module(framework) + return conf.PATH / module.ENTRYPOINT def validate_project(): @@ -127,33 +316,49 @@ def validate_project(): """ framework = get_framework() entrypoint_path = get_entrypoint_path(framework) - _module = get_framework_module(framework) - + module = get_framework_module(framework) + entrypoint = module.get_entrypoint() + # Run framework-specific validation - _module.validate_project() - + module.validate_project() + + # A valid project must have a base class available + try: + class_node = entrypoint.get_base_class() + except ValidationError as e: + raise e + + # The base class must have a `run` method. + try: + entrypoint.get_run_method() + except ValidationError as e: + raise e + + # The class must have one or more task methods. + if len(entrypoint.get_task_methods()) < 1: + raise ValidationError( + f"One or more task methods could not be found on class `{class_node.name}` in {entrypoint_path}.\n" + "Create a new task using `agentstack generate task `." + ) + + # The class must have one or more agent methods. + if len(entrypoint.get_agent_methods()) < 1: + raise ValidationError( + f"One or more agent methods could not be found on class `{class_node.name}` in {entrypoint_path}.\n" + "Create a new agent using `agentstack generate agent `." + ) + # Verify that agents defined in agents.yaml are present in the codebase - agent_method_names = _module.get_agent_method_names() + agent_method_names = entrypoint.get_agent_method_names() for agent_name in get_all_agent_names(): if agent_name not in agent_method_names: - raise ValidationError( - f"Agent `{agent_name}` is defined in agents.yaml but not in {entrypoint_path}" - ) + raise ValidationError(f"Agent `{agent_name}` defined in agents.yaml but not in {entrypoint_path}") # Verify that tasks defined in tasks.yaml are present in the codebase - task_method_names = _module.get_task_method_names() + task_method_names = entrypoint.get_task_method_names() for task_name in get_all_task_names(): if task_name not in task_method_names: - raise ValidationError( - f"Task `{task_name}` is defined in tasks.yaml but not in {entrypoint_path}" - ) - - -def parse_llm(llm: str) -> tuple[str, str]: - """ - Parse a language model string into a provider and model. - """ - return get_framework_module(get_framework()).parse_llm(llm) + raise ValidationError(f"Task `{task_name}` defined in tasks.yaml but not in {entrypoint_path}") def add_tool(tool: ToolConfig, agent_name: str): @@ -162,28 +367,35 @@ def add_tool(tool: ToolConfig, agent_name: str): The tool will have already been installed in the user's application and have all dependencies installed. We're just handling code generation here. """ - return get_framework_module(get_framework()).add_tool(tool, agent_name) + # since this is a write operation, delegate to the framework impl. + module = get_framework_module(get_framework()) + return module.add_tool(tool, agent_name) def remove_tool(tool: ToolConfig, agent_name: str): """ Remove a tool from the user's project. """ - return get_framework_module(get_framework()).remove_tool(tool, agent_name) + # since this is a write operation, delegate to the framework impl. + module = get_framework_module(get_framework()) + return module.remove_tool(tool, agent_name) def get_tool_callables(tool_name: str) -> list[Callable]: """ Get a tool by name and return it as a list of framework-native callables. """ + # TODO: remove after agentops fixes their issue # wrap method with agentops tool event def wrap_method(method: Callable) -> Callable: from inspect import signature - + original_signature = signature(method) + def wrapped_method(*args, **kwargs): import agentops + tool_event = agentops.ToolEvent(method.__name__) result = method(*args, **kwargs) agentops.record(tool_event) @@ -219,45 +431,58 @@ def get_agent_method_names() -> list[str]: """ Get a list of agent names in the user's project. """ - return get_framework_module(get_framework()).get_agent_method_names() + module = get_framework_module(get_framework()) + entrypoint = module.get_entrypoint() + return entrypoint.get_agent_method_names() def get_agent_tool_names(agent_name: str) -> list[str]: """ - Get a list of tool names in the user's project. + Get a list of tool names in the user's project for a given agent. """ - return get_framework_module(get_framework()).get_agent_tool_names(agent_name) + module = get_framework_module(get_framework()) + entrypoint = module.get_entrypoint() + return entrypoint.get_agent_tool_names(agent_name) -def add_agent(agent: 'AgentConfig', position: Optional['InsertionPoint'] = None): +def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None): """ Add an agent to the user's project. """ framework = get_framework() + module = get_framework_module(framework) + if agent.name in get_agent_method_names(): raise ValidationError(f"Agent `{agent.name}` already exists in {get_entrypoint_path(framework)}") - return get_framework_module(framework).add_agent(agent, position) + + return module.add_agent(agent, position) -def add_task(task: 'TaskConfig', position: Optional['InsertionPoint'] = None): +def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None): """ Add a task to the user's project. """ framework = get_framework() + module = get_framework_module(framework) + if task.name in get_task_method_names(): raise ValidationError(f"Task `{task.name}` already exists in {get_entrypoint_path(framework)}") - return get_framework_module(framework).add_task(task, position) + + return module.add_task(task, position) def get_task_method_names() -> list[str]: """ Get a list of task names in the user's project. """ - return get_framework_module(get_framework()).get_task_method_names() + module = get_framework_module(get_framework()) + entrypoint = module.get_entrypoint() + return entrypoint.get_task_method_names() def get_graph() -> list[graph.Edge]: """ Get the graph of the user's project. """ - return get_framework_module(get_framework()).get_graph() + module = get_framework_module(get_framework()) + return module.get_graph() diff --git a/agentstack/frameworks/crewai.py b/agentstack/frameworks/crewai.py index 14e5a7c5..86e4f0e0 100644 --- a/agentstack/frameworks/crewai.py +++ b/agentstack/frameworks/crewai.py @@ -1,21 +1,22 @@ -from typing import TYPE_CHECKING, Optional, Any, Callable +from typing import Optional, Any, Callable from pathlib import Path import ast from agentstack import conf, log from agentstack.exceptions import ValidationError +from agentstack.generation import InsertionPoint +from agentstack.frameworks import BaseEntrypointFile from agentstack._tools import ToolConfig from agentstack.tasks import TaskConfig from agentstack.agents import AgentConfig from agentstack.generation import asttools from agentstack import graph -if TYPE_CHECKING: - from agentstack.generation import InsertionPoint +NAME: str = "CrewAI" ENTRYPOINT: Path = Path('src/crew.py') -class CrewFile(asttools.File): +class CrewFile(BaseEntrypointFile): """ Parses and manipulates the CrewAI entrypoint file. All AST interactions should happen within the methods of this class. @@ -37,60 +38,27 @@ def get_base_class(self) -> ast.ClassDef: except IndexError: raise ValidationError(f"`@CrewBase` decorated class not found in {ENTRYPOINT}") - def get_crew_method(self) -> ast.FunctionDef: - """A `crew` method is a method decorated with `@crew`.""" + def get_run_method(self) -> ast.FunctionDef: + """A run method is a method decorated with `@crew`.""" try: base_class = self.get_base_class() return asttools.find_decorated_method_in_class(base_class, 'crew')[0] except IndexError: raise ValidationError( - f"`@crew` decorated method not found in `{base_class.name}` class in {ENTRYPOINT}" + f"`@crew` decorated method not found in `{base_class.name}` in {ENTRYPOINT}" ) - def get_task_methods(self) -> list[ast.FunctionDef]: - """A `task` method is a method decorated with `@task`.""" - return asttools.find_decorated_method_in_class(self.get_base_class(), 'task') - - def add_task_method(self, task: TaskConfig): - """Add a new task method to the CrewAI entrypoint.""" - task_methods = self.get_task_methods() - if task_methods: - # Add after the existing task methods - _, pos = self.get_node_range(task_methods[-1]) - else: - # Add before the `crew` method - crew_method = self.get_crew_method() - pos, _ = self.get_node_range(crew_method) - - code = f""" @task + def get_new_task_method(self, task: TaskConfig) -> str: + """Get the content of a new task method.""" + return f""" @task def {task.name}(self) -> Task: return Task( config=self.tasks_config['{task.name}'], )""" - if not self.source[:pos].endswith('\n'): - code = '\n\n' + code - if not self.source[pos:].startswith('\n'): - code += '\n\n' - self.edit_node_range(pos, pos, code) - - def get_agent_methods(self) -> list[ast.FunctionDef]: - """An `agent` method is a method decorated with `@agent`.""" - return asttools.find_decorated_method_in_class(self.get_base_class(), 'agent') - - def add_agent_method(self, agent: AgentConfig): - """Add a new agent method to the CrewAI entrypoint.""" - # TODO do we want to pre-populate any tools? - agent_methods = self.get_agent_methods() - if agent_methods: - # Add after the existing agent methods - _, pos = self.get_node_range(agent_methods[-1]) - else: - # Add before the `crew` method - crew_method = self.get_crew_method() - pos, _ = self.get_node_range(crew_method) - - code = f""" @agent + def get_new_agent_method(self, agent: AgentConfig) -> str: + """Get the content of a new agent method.""" + return f""" @agent def {agent.name}(self) -> Agent: return Agent( config=self.agents_config['{agent.name}'], @@ -98,15 +66,9 @@ def {agent.name}(self) -> Agent: verbose=True, )""" - if not self.source[:pos].endswith('\n'): - code = '\n\n' + code - if not self.source[pos:].startswith('\n'): - code += '\n\n' - self.edit_node_range(pos, pos, code) - def get_agent_tools(self, agent_name: str) -> ast.List: """ - Get the tools used by an agent as AST nodes. + Get the list of tools used by an agent as an AST List node. Tool definitions are inside of the methods marked with an `@agent` decorator. The method returns a new class instance with the tools as a list of callables @@ -114,85 +76,27 @@ def get_agent_tools(self, agent_name: str) -> ast.List: """ method = asttools.find_method(self.get_agent_methods(), agent_name) if method is None: - raise ValidationError(f"`@agent` method `{agent_name}` does not exist in {ENTRYPOINT}") + raise ValidationError(f"Method `{agent_name}` does not exist in {ENTRYPOINT}") agent_class = asttools.find_class_instantiation(method, 'Agent') if agent_class is None: - raise ValidationError( - f"`@agent` method `{agent_name}` does not have an `Agent` class instantiation in {ENTRYPOINT}" - ) + raise ValidationError(f"Method `{agent_name}` does not call `Agent` in {ENTRYPOINT}") tools_kwarg = asttools.find_kwarg_in_method_call(agent_class, 'tools') if not tools_kwarg: - raise ValidationError( - f"`@agent` method `{agent_name}` does not have a keyword argument `tools` in {ENTRYPOINT}" - ) + raise ValidationError(f"`Agent` does not have a kwarg `tools` in {ENTRYPOINT}") if not isinstance(tools_kwarg.value, ast.List): - raise ValidationError( - f"`@agent` method `{agent_name}` has a non-list value for the `tools` kwarg in {ENTRYPOINT}" - ) + raise ValidationError(f"`Agent` must define a list for kwarg `tools` in {ENTRYPOINT}") return tools_kwarg.value - def get_agent_tool_nodes(self, agent_name: str) -> list[ast.Starred]: - """ - Get a list of all ast nodes that define agentstack tools used by the agent. - """ - agent_tools_node = self.get_agent_tools(agent_name) - return asttools.find_tool_nodes(agent_tools_node) - - def get_agent_tool_names(self, agent_name: str) -> list[str]: - """ - Get a list of all tools used by the agent. - - Tools are identified by the item name of an `agentstack.tools` attribute node. - """ - tool_names: list[str] = [] - for node in self.get_agent_tool_nodes(agent_name): - # ignore type checking here since `get_agent_tool_nodes` is exhaustive - tool_names.append(node.value.slice.value) # type: ignore[attr-defined] - return tool_names - def add_agent_tools(self, agent_name: str, tool: ToolConfig): - """ - Add new tools to be used by an agent. - - Tool definitions are inside the methods marked with an `@agent` decorator. - The method returns a new class instance with the tools as a list of callables - under the kwarg `tools`. - """ - method = asttools.find_method(self.get_agent_methods(), agent_name) - if method is None: - raise ValidationError(f"`@agent` method `{agent_name}` does not exist in {ENTRYPOINT}") - - existing_node: ast.List = self.get_agent_tools(agent_name) - existing_elts: list[ast.expr] = existing_node.elts - - new_tool_nodes: list[ast.expr] = [] - if not tool.name in self.get_agent_tool_names(agent_name): - existing_elts.append(asttools.create_tool_node(tool.name)) - - new_node = ast.List(elts=existing_elts, ctx=ast.Load()) - start, end = self.get_node_range(existing_node) - self.edit_node_range(start, end, new_node) - - def remove_agent_tools(self, agent_name: str, tool: ToolConfig): - """ - Remove tools from an agent belonging to `tool`. - """ - existing_node: ast.List = self.get_agent_tools(agent_name) - start, end = self.get_node_range(existing_node) - - # modify the existing node to remove any matching tools - # we're referencing the internal node list from two directions here, - # so it's important that the node tree doesn't get re-parsed in between - for node in self.get_agent_tool_nodes(agent_name): - # ignore type checking here since `get_agent_tool_nodes` is exhaustive - if tool.name == node.value.slice.value: # type: ignore[attr-defined] - existing_node.elts.remove(node) - - self.edit_node_range(start, end, existing_node) +def get_entrypoint() -> CrewFile: + """ + Get the CrewAI entrypoint file. + """ + return CrewFile(conf.PATH / ENTRYPOINT) def validate_project() -> None: @@ -200,91 +104,29 @@ def validate_project() -> None: Validate that a CrewAI project is ready to run. Raises an `agentstack.ValidationError` if the project is not valid. """ - try: - crew_file = CrewFile(conf.PATH / ENTRYPOINT) - except ValidationError as e: - raise e - - # A valid project must have a class in the crew.py file decorated with `@CrewBase` - try: - class_node = crew_file.get_base_class() - except ValidationError as e: - raise e - - # The Crew class must have one method decorated with `@crew` - try: - crew_file.get_crew_method() - except ValidationError as e: - raise e - - # The Crew class must have one or more methods decorated with `@task` - if len(crew_file.get_task_methods()) < 1: - raise ValidationError( - f"`@task` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new task using `agentstack generate task `." - ) - - # The Crew class must have one or more methods decorated with `@agent` - if len(crew_file.get_agent_methods()) < 1: - raise ValidationError( - f"`@agent` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new agent using `agentstack generate agent `." - ) - - -def parse_llm(llm: str) -> tuple[str, str]: - """ - Parse the llm string into a `LLM` dataclass. - Crew separates providers and models with a forward slash. - """ - provider, model = llm.split('/') - return provider, model + return # We don't need to do any additional validation -def get_task_method_names() -> list[str]: - """ - Get a list of task names (methods with an @task decorator). - """ - crew_file = CrewFile(conf.PATH / ENTRYPOINT) - return [method.name for method in crew_file.get_task_methods()] - - -def add_task(task: TaskConfig, position: Optional['InsertionPoint'] = None) -> None: +def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None) -> None: """ Add a task method to the CrewAI entrypoint. """ if position is not None: - raise NotImplementedError("Task insertion points are not supported in CrewAI.") - - with CrewFile(conf.PATH / ENTRYPOINT) as crew_file: - crew_file.add_task_method(task) - + raise NotImplementedError(f"Task insertion points are not supported in {NAME}.") -def get_agent_method_names() -> list[str]: - """ - Get a list of agent names (methods with an @agent decorator). - """ - crew_file = CrewFile(conf.PATH / ENTRYPOINT) - return [method.name for method in crew_file.get_agent_methods()] - - -def get_agent_tool_names(agent_name: str) -> list[Any]: - """ - Get a list of tools used by an agent. - """ - with CrewFile(conf.PATH / ENTRYPOINT) as crew_file: - return crew_file.get_agent_tool_names(agent_name) + with get_entrypoint() as entrypoint: + entrypoint.add_task_method(task) -def add_agent(agent: AgentConfig, position: Optional['InsertionPoint'] = None) -> None: +def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None) -> None: """ Add an agent method to the CrewAI entrypoint. """ if position is not None: - raise NotImplementedError("Agent insertion points are not supported in CrewAI.") + raise NotImplementedError(f"Agent insertion points are not supported in {NAME}.") - with CrewFile(conf.PATH / ENTRYPOINT) as crew_file: - crew_file.add_agent_method(agent) + with get_entrypoint() as entrypoint: + entrypoint.add_agent_method(agent) def add_tool(tool: ToolConfig, agent_name: str): @@ -292,16 +134,16 @@ def add_tool(tool: ToolConfig, agent_name: str): Add a tool to the CrewAI entrypoint for the specified agent. The agent should already exist in the crew class and have a keyword argument `tools`. """ - with CrewFile(conf.PATH / ENTRYPOINT) as crew_file: - crew_file.add_agent_tools(agent_name, tool) + with get_entrypoint() as entrypoint: + entrypoint.add_agent_tools(agent_name, tool) def remove_tool(tool: ToolConfig, agent_name: str): """ Remove a tool from the CrewAI framework for the specified agent. """ - with CrewFile(conf.PATH / ENTRYPOINT) as crew_file: - crew_file.remove_agent_tools(agent_name, tool) + with get_entrypoint() as entrypoint: + entrypoint.remove_agent_tools(agent_name, tool) def wrap_tool(tool_func: Callable) -> Callable: @@ -311,12 +153,12 @@ def wrap_tool(tool_func: Callable) -> Callable: try: from crewai.tools import tool as _crewai_tool_decorator except ImportError: - raise ValidationError("Could not import `crewai`. Is this an AgentStack CrewAI project?") + raise ValidationError(f"Could not import `crewai`. Is this an AgentStack {NAME} project?") return _crewai_tool_decorator(tool_func) def get_graph() -> list[graph.Edge]: """Get the graph of the user's project.""" - log.debug("CrewAI does not support graph generation.") + log.debug(f"{NAME} does not support graph generation.") return [] diff --git a/agentstack/frameworks/langgraph.py b/agentstack/frameworks/langgraph.py index 7c38e968..17540863 100644 --- a/agentstack/frameworks/langgraph.py +++ b/agentstack/frameworks/langgraph.py @@ -1,17 +1,20 @@ from functools import wraps from typing import Optional, Union, Callable, Any -from dataclasses import dataclass + from pathlib import Path import ast from agentstack import conf, log from agentstack import packaging from agentstack.exceptions import ValidationError from agentstack.generation import asttools, InsertionPoint +from agentstack.frameworks import Provider, BaseEntrypointFile from agentstack._tools import ToolConfig from agentstack.agents import AgentConfig, get_all_agent_names from agentstack.tasks import TaskConfig, get_all_task_names from agentstack import graph + +NAME: str = "LangGraph" ENTRYPOINT: Path = Path('src/graph.py') GRAPH_NODE_START = 'START' @@ -24,133 +27,64 @@ GRAPH_NODE_TOOLS_CONDITION, ) - -@dataclass -class LangGraphProvider: - """An LLM provider for the LangGraph framework.""" - - class_name: str - module_name: str - dependency: str - - PROVIDERS = { - 'openai': LangGraphProvider( + 'openai': Provider( class_name='ChatOpenAI', module_name='langchain_openai', - dependency='langchain-openai>=0.3.0', + dependencies=['langchain-openai>=0.3.0'], ), - 'deepseek': LangGraphProvider( + 'deepseek': Provider( class_name='ChatDeepSeek', module_name='langchain_deepseek_official', - dependency='langchain-deepseek-official>=0.1.0', + dependencies=['langchain-deepseek-official>=0.1.0'], ), - 'anthropic': LangGraphProvider( + 'anthropic': Provider( class_name='ChatAnthropic', module_name='langchain_anthropic', - dependency='langchain-anthropic>=0.3.1', + dependencies=['langchain-anthropic>=0.3.1'], ), - 'google': LangGraphProvider( + 'google': Provider( class_name='ChatGoogleGenerativeAI', module_name='langchain_google_genai', - dependency='langchain-google-genai>=2.0.8', + dependencies=['langchain-google-genai>=2.0.8'], ), - 'huggingface': LangGraphProvider( + 'huggingface': Provider( class_name='ChatHuggingFace', module_name='langchain_huggingface', - dependency='langchain-huggingface', + dependencies=['langchain-huggingface'], ), - 'microsoft': LangGraphProvider( + 'microsoft': Provider( class_name='AzureChatOpenAI', module_name='langchain_openai', - dependency='langchain-openai', + dependencies=['langchain-openai'], ), - 'mistral': LangGraphProvider( + 'mistral': Provider( class_name='ChatMistralAI', module_name='langchain_mistralai.chat_models', - dependency='langchain-mistralai', + dependencies=['langchain-mistralai'], ), - 'ollama': LangGraphProvider( + 'ollama': Provider( class_name='ChatOllama', module_name='langchain_ollama.chat_models', - dependency='langchain-ollama', + dependencies=['langchain-ollama'], ), - 'groq': LangGraphProvider( + 'groq': Provider( class_name='ChatGroq', module_name='langchain_groq', - dependency='langchain-groq', + dependencies=['langchain-groq'], ), } -class LangGraphFile(asttools.File): +class LangGraphFile(BaseEntrypointFile): """ Parses and manipulates the LangGraph entrypoint file. """ - def get_import(self, module_name: str, attributes: str) -> Optional[ast.ImportFrom]: - """ - Check if an import statement for a module and class exists in the file. - """ - for node in asttools.get_all_imports(self.tree): - names_str = ', '.join(alias.name for alias in node.names) - if node.module == module_name and names_str == attributes: - return node - return None - - def add_import(self, module_name: str, attributes: str): - """ - Add an import statement to the file. - """ - all_imports = asttools.get_all_imports(self.tree) - _, end = self.get_node_range(all_imports[-1]) if all_imports else (0, 0) - - code = f"from {module_name} import {attributes}\n" - if not self.source[:end].endswith('\n'): - code = '\n' + code - - self.edit_node_range(end, end, code) - - def get_base_class(self) -> ast.ClassDef: - """ - A base class is the first class inside of the file that follows the - naming convention: `Graph` - """ - try: - return asttools.find_class_with_regex(self.tree, r'\w+Graph$')[0] - except IndexError: - raise ValidationError(f"`Graph` class not found in {ENTRYPOINT}") - - def get_run_method(self) -> ast.FunctionDef: - """A method named `run`.""" - try: - base_class = self.get_base_class() - node = asttools.find_method_in_class(base_class, 'run')[0] - assert 'inputs' in (arg.arg for arg in node.args.args) - return node - except IndexError: - raise ValidationError(f"`run` method not found in `{base_class.name} class in {ENTRYPOINT}.") - except AssertionError: - raise ValidationError( - f"Method `run` of `{base_class.name}` must accept `inputs` as a keyword argument." - ) - - def get_task_methods(self) -> list[ast.FunctionDef]: - """A `task` method is a method decorated with `@task`.""" - return asttools.find_decorated_method_in_class(self.get_base_class(), 'task') - - def add_task_method(self, task: TaskConfig): - """Add a new task method to the LangGraph entrypoint.""" - task_methods = self.get_task_methods() - if task_methods: - # Add after the existing task methods - _, pos = self.get_node_range(task_methods[-1]) - else: - # Add before the `main` method - main_method = self.get_run_method() - pos, _ = self.get_node_range(main_method) + base_class_pattern: str = r'\w+Graph$' - code = f""" @agentstack.task + def get_new_task_method(self, task: TaskConfig) -> str: + return f""" @agentstack.task def {task.name}(self, state: State): task_config = agentstack.get_task('{task.name}') messages = ChatPromptTemplate.from_messages([ @@ -159,30 +93,10 @@ def {task.name}(self, state: State): messages = messages.format_messages(**state['inputs']) return {{'messages': messages + state['messages']}}""" - if not self.source[:pos].endswith('\n'): - code = '\n\n' + code - if not self.source[pos:].startswith('\n'): - code += '\n\n' - self.edit_node_range(pos, pos, code) - - def get_agent_methods(self) -> list[ast.FunctionDef]: - """An `agent` method is a method decorated with `@agent`.""" - return asttools.find_decorated_method_in_class(self.get_base_class(), 'agent') - - def add_agent_method(self, agent: AgentConfig): - """Add a new agent method to the LangGraph entrypoint.""" - agent_methods = self.get_agent_methods() - if agent_methods: - # Add after the existing agent methods - _, pos = self.get_node_range(agent_methods[-1]) - else: - # Add before the `main` method - main_method = self.get_run_method() - pos, _ = self.get_node_range(main_method) - + def get_new_agent_method(self, agent: AgentConfig) -> str: assert agent.provider in PROVIDERS.keys() # this gets validated in `add_agent` agent_class_name = PROVIDERS[agent.provider].class_name - code = f""" @agentstack.agent + return f""" @agentstack.agent def {agent.name}(self, state: State): agent_config = agentstack.get_agent('{agent.name}') messages = ChatPromptTemplate.from_messages([ @@ -195,12 +109,6 @@ def {agent.name}(self, state: State): ) return {{'messages': [response, ]}}""" - if not self.source[:pos].endswith('\n'): - code = '\n\n' + code - if not self.source[pos:].startswith('\n'): - code += '\n\n' - self.edit_node_range(pos, pos, code) - def get_global_tools(self) -> ast.List: try: method = asttools.find_method_calls(self.get_run_method(), 'ToolNode')[0] @@ -234,7 +142,7 @@ def get_global_tool_names(self) -> list[str]: def get_agent_tools(self, agent_name: str) -> ast.List: """ - Get the tools used by an agent as AST nodes. + Get the list of tools used by an agent as an AST List node. Tool definitions are inside of the methods marked with an `@agent` decorator. The method `bind_tools` is called with a list of tools to bind to the agent. @@ -259,25 +167,6 @@ def get_agent_tools(self, agent_name: str) -> ast.List: return tools_list - def get_agent_tool_nodes(self, agent_name: str) -> list[ast.Starred]: - """ - Get a list of all ast nodes that define agentstack tools used by the agent. - """ - agent_tools_node = self.get_agent_tools(agent_name) - return asttools.find_tool_nodes(agent_tools_node) - - def get_agent_tool_names(self, agent_name: str) -> list[str]: - """ - Get a list of all tools used by the agent. - - Tools are identified by the item name of an `agentstack.tools` attribute node. - """ - tool_names: list[str] = [] - for node in self.get_agent_tool_nodes(agent_name): - # ignore type checking here since `get_agent_tool_nodes` is exhaustive - tool_names.append(node.value.slice.value) # type: ignore[attr-defined] - return tool_names - def add_agent_tools(self, agent_name: str, tool: ToolConfig): """ Add new tools to be used by an agent to the agent's tool list and the @@ -285,7 +174,7 @@ def add_agent_tools(self, agent_name: str, tool: ToolConfig): """ method = asttools.find_method(self.get_agent_methods(), agent_name) if method is None: - raise ValidationError(f"`@agent` method `{agent_name}` does not exist in {ENTRYPOINT}") + raise ValidationError(f"Agent method `{agent_name}` does not exist in {ENTRYPOINT}") try: bind_tools = asttools.find_method_calls(method, 'bind_tools')[0] @@ -302,16 +191,8 @@ def add_agent_tools(self, agent_name: str, tool: ToolConfig): agent = agent.bind_tools([])""" self.edit_node_range(pos, pos, code) - existing_node: ast.List = self.get_agent_tools(agent_name) - existing_elts: list[ast.expr] = existing_node.elts - - new_tool_nodes: list[ast.expr] = [] - if not tool.name in self.get_agent_tool_names(agent_name): - existing_elts.append(asttools.create_tool_node(tool.name)) - - new_node = ast.List(elts=existing_elts, ctx=ast.Load()) - start, end = self.get_node_range(existing_node) - self.edit_node_range(start, end, new_node) + # add the tool to the agent's tools list + super().add_agent_tools(agent_name, tool) # add the tool to the global tools list existing_global_node: ast.List = self.get_global_tools() @@ -330,16 +211,8 @@ def remove_agent_tools(self, agent_name: str, tool: ToolConfig): Remove tools from an agent belonging to `tool` from the agent's tool list and the global ToolNode list. """ - existing_node: ast.List = self.get_agent_tools(agent_name) - start, end = self.get_node_range(existing_node) - # modify the existing node to remove any matching tools - # we're referencing the internal node list from two directions here, - # so it's important that the node tree doesn't get re-parsed in between - for node in self.get_agent_tool_nodes(agent_name): - # ignore type checking here since `get_agent_tool_nodes` is exhaustive - if tool.name == node.value.slice.value: # type: ignore[attr-defined] - existing_node.elts.remove(node) - self.edit_node_range(start, end, existing_node) + # remove the tool from the agent's tools list + super().remove_agent_tools(agent_name, tool) # remove the tool from the global tools list existing_global_node: ast.List = self.get_global_tools() @@ -511,52 +384,17 @@ def _get_node_name(node: ast.expr) -> str: raise ValidationError(f"Node `{node_config.name}` not found in {ENTRYPOINT}") +def get_entrypoint() -> LangGraphFile: + """Get the LangGraph entrypoint file.""" + return LangGraphFile(conf.PATH / ENTRYPOINT) + + def validate_project() -> None: """ Validate that a langgraph project is ready to run. Raises an `agentstack.ValidationError` if the project is not valid. """ - graph_file = LangGraphFile(conf.PATH / ENTRYPOINT) - - # A valid project must have a class in the graph.py file that is named Graph. - # will raise a ValidationError if the class is not found - class_node = graph_file.get_base_class() - - # The base class must implement a method called `run` that accepts `inputs` - # as a keyword argument. - # will raise a ValidationError if the method is not found or does not have the correct signature - _ = graph_file.get_run_method() - - # The base class must have one or more methods decorated with `@task` - if len(graph_file.get_task_methods()) < 1: - raise ValidationError( - f"`@agentstack.task` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new task using `agentstack generate task `." - ) - - # The base class must have one or more methods decorated with `@agent` - if len(graph_file.get_agent_methods()) < 1: - raise ValidationError( - f"`@agentstack.agent` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new agent using `agentstack generate agent `." - ) - - -def parse_llm(llm: str) -> tuple[str, str]: - """ - Parse a language model string into a provider and model. - LangGraph separates providers and models with a forward slash. - """ - provider, model = llm.split('/') - return provider, model - - -def get_task_method_names() -> list[str]: - """ - Get a list of task names (methods with an @task decorator). - """ - entrypoint = LangGraphFile(conf.PATH / ENTRYPOINT) - return [method.name for method in entrypoint.get_task_methods()] + return # No additional validation needed def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None) -> None: @@ -568,7 +406,7 @@ def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None) -> Non if not position in (InsertionPoint.BEGIN, InsertionPoint.END): raise ValidationError(f"Invalid insertion point: {position}") - with LangGraphFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_task_method(task) entrypoint.add_graph_node(task) @@ -629,22 +467,6 @@ def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None) -> Non log.warning(f"Could not find {GRAPH_NODE_START} node to replace in {ENTRYPOINT}") -def get_agent_method_names() -> list[str]: - """ - Get a list of agent names (methods with an @agent decorator). - """ - entrypoint = LangGraphFile(conf.PATH / ENTRYPOINT) - return [method.name for method in entrypoint.get_agent_methods()] - - -def get_agent_tool_names(agent_name: str) -> list[Any]: - """ - Get a list of tools used by an agent. - """ - with LangGraphFile(conf.PATH / ENTRYPOINT) as entrypoint: - return entrypoint.get_agent_tool_names(agent_name) - - def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None) -> None: """ Add an agent method to the LangGraph entrypoint. @@ -654,16 +476,18 @@ def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None) -> if not position in (InsertionPoint.BEGIN, InsertionPoint.END): raise ValidationError(f"Invalid insertion point: {position}") + # individual LLM providers rely on additional dependencies, install them try: provider = PROVIDERS[agent.provider] - packaging.install(provider.dependency) + provider.install_dependencies() except KeyError: raise ValidationError( - f"LangGraph provider '{provider}' has not been implemented. " + f"{NAME} provider '{agent.provider}' has not been implemented. " f"AgentStack currently supports: {', '.join(PROVIDERS.keys())} " ) - with LangGraphFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: + # also include an import statement for the LLM provider if not entrypoint.get_import(provider.module_name, provider.class_name): entrypoint.add_import(provider.module_name, provider.class_name) @@ -747,7 +571,7 @@ def add_tool(tool: ToolConfig, agent_name: str): Add a tool to the LangGraph entrypoint for the specified agent. The agent should already exist in the base class and have a `bind_tools` method call. """ - with LangGraphFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_agent_tools(agent_name, tool) @@ -755,7 +579,7 @@ def remove_tool(tool: ToolConfig, agent_name: str): """ Remove a tool from the CrewAI framework for the specified agent. """ - with LangGraphFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.remove_agent_tools(agent_name, tool) @@ -769,5 +593,4 @@ def wrap_tool(tool_func: Callable) -> Callable: def get_graph() -> list[graph.Edge]: """Get the graph structure of the project.""" - entrypoint = LangGraphFile(conf.PATH / ENTRYPOINT) - return entrypoint.get_graph() + return get_entrypoint().get_graph() diff --git a/agentstack/frameworks/llamaindex.py b/agentstack/frameworks/llamaindex.py new file mode 100644 index 00000000..269dd4b4 --- /dev/null +++ b/agentstack/frameworks/llamaindex.py @@ -0,0 +1,199 @@ +from typing import Optional, Any, Callable +from pathlib import Path +import ast +from agentstack import conf, log +from agentstack.exceptions import ValidationError +from agentstack.generation import InsertionPoint +from agentstack.frameworks import Provider, BaseEntrypointFile +from agentstack._tools import ToolConfig +from agentstack.tasks import TaskConfig +from agentstack.agents import AgentConfig +from agentstack.generation import asttools +from agentstack import graph + +NAME: str = "LLamaIndex" +ENTRYPOINT: Path = Path('src/stack.py') + +PROVIDERS = { + 'openai': Provider( + class_name='OpenAI', + module_name='llama_index.llms.openai', + dependencies=['llama-index-llms-openai', 'llama-index-agent-openai'], + ), + 'anthropic': Provider( + class_name='Anthropic', + module_name='llama_index.llms.anthropic', + dependencies=['llama-index-llms-anthropic'], + ), + 'deepseek': Provider( + class_name='DeepSeek', + module_name='llama_index.llms.deepseek', + dependencies=['llama-index-llms-deepseek'], + ), + 'google': Provider( + class_name='Gemini', + module_name='llama_index.llms.gemini', + dependencies=['llama-index-llms-gemini'], + ), + 'huggingface': Provider( + class_name='HuggingFaceLLM', + module_name='llama_index.llms.huggingface', + dependencies=['llama-index-llms-huggingface'], + ), + 'microsoft': Provider( + class_name='AzureOpenAI', + module_name='llama_index.llms.azure', + dependencies=['llama-index-llms-azure-openai'], + ), + 'mistral': Provider( + class_name='MistralAI', + module_name='llama_index.llms.mistralai', + dependencies=['llama-index-llms-mistralai'], + ), + 'ollama': Provider( + class_name='Ollama', + module_name='llama_index.llms.ollama', + dependencies=['llama-index-llms-ollama'], + ), + 'groq': Provider( + class_name='Groq', + module_name='llama_index.llms.groq', + dependencies=['llama-index-llms-groq'], + ), + 'openrouter': Provider( + class_name='OpenRouter', + module_name='llama_index.llms.openrouter', + dependencies=['llama-index-llms-openrouter'], + ), +} + + +class LlamaIndexFile(BaseEntrypointFile): + """ + Parses and manipulates the entrypoint file. + All AST interactions should happen within the methods of this class. + """ + + def get_new_task_method(self, task: TaskConfig) -> str: + """Get the content of a new task method.""" + return f""" @agentstack.task + def {task.name}(self) -> ChatMessage: + task_config = agentstack.get_task('{task.name}') + return ChatMessage(role="user", content=task_config.prompt)""" + + def get_new_agent_method(self, agent: AgentConfig) -> str: + """Get the content of a new agent method.""" + assert agent.provider in PROVIDERS.keys() # this gets validated in `add_agent` + llm_class_name = PROVIDERS[agent.provider].class_name + return f""" @agentstack.agent + def {agent.name}(self) -> FunctionAgent: + agent_config = agentstack.get_agent('{agent.name}') + llm = {llm_class_name}( + model=agent_config.model, + ) + return FunctionAgent( + name=agent_config.name, + description=agent_config.role, + system_prompt=agent_config.prompt, + llm=llm, + tools=[], + )""" + + def get_agent_tools(self, agent_name: str) -> ast.List: + """Get the list of tools used by an agent as an AST List node.""" + method = asttools.find_method(self.get_agent_methods(), agent_name) + if method is None: + raise ValidationError(f"Method `{agent_name}` does not exist in {ENTRYPOINT}") + + agent_class = asttools.find_class_instantiation(method, 'FunctionAgent') + if agent_class is None: + raise ValidationError(f"Method `{agent_name}` does not call `FunctionAgent` in {ENTRYPOINT}") + + tools_kwarg = asttools.find_kwarg_in_method_call(agent_class, 'tools') + if not tools_kwarg: + raise ValidationError(f"`FunctionAgent` does not have a kwarg `tools` in {ENTRYPOINT}") + + if not isinstance(tools_kwarg.value, ast.List): + raise ValidationError(f"`FunctionAgent` must define a list for kwarg `tools` in {ENTRYPOINT}") + + return tools_kwarg.value + + +def get_entrypoint() -> LlamaIndexFile: + """Get the entrypoint file.""" + return LlamaIndexFile(conf.PATH / ENTRYPOINT) + + +def validate_project() -> None: + """ + Validate that the project is ready to run. + Raises an `agentstack.ValidationError` if the project is not valid. + """ + return # No additional validation needed. + + +def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None) -> None: + """ + Add a task method to the entrypoint. + """ + if position is not None: + raise NotImplementedError(f"Task insertion points are not supported in {NAME}.") + + with get_entrypoint() as entrypoint: + entrypoint.add_task_method(task) + + +def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None) -> None: + """ + Add an agent method to the entrypoint. + """ + if position is not None: + raise NotImplementedError(f"Agent insertion points are not supported in {NAME}.") + + # individual LLM providers rely on additional dependencies, install them + try: + provider = PROVIDERS[agent.provider] + provider.install_dependencies() + except KeyError: + raise ValidationError( + f"{NAME} provider '{agent.provider}' has not been implemented. " + f"AgentStack currently supports: {', '.join(PROVIDERS.keys())} " + ) + + with get_entrypoint() as entrypoint: + # also include an import statement for the LLM provider + if not entrypoint.get_import(provider.module_name, provider.class_name): + entrypoint.add_import(provider.module_name, provider.class_name) + + entrypoint.add_agent_method(agent) + + +def add_tool(tool: ToolConfig, agent_name: str): + """ + Add a tool to the entrypoint for the specified agent. + """ + with get_entrypoint() as entrypoint: + entrypoint.add_agent_tools(agent_name, tool) + + +def remove_tool(tool: ToolConfig, agent_name: str): + """ + Remove a tool from the entrypoint for the specified agent. + """ + with get_entrypoint() as entrypoint: + entrypoint.remove_agent_tools(agent_name, tool) + + +def wrap_tool(tool_func: Callable) -> Callable: + """ + Wrap a tool function with framework-specific functionality. + """ + # TODO llamaindex does have a BaseTool class, but I don't see what additional + # value we offer by wrapping tools in it. + return tool_func + + +def get_graph() -> list[graph.Edge]: + """Get the graph of the user's project.""" + log.debug(f"{NAME} does not support graph generation.") + return [] diff --git a/agentstack/frameworks/new_framework.py.tpl b/agentstack/frameworks/new_framework.py.tpl index ddf78376..a4cebf72 100644 --- a/agentstack/frameworks/new_framework.py.tpl +++ b/agentstack/frameworks/new_framework.py.tpl @@ -1,57 +1,43 @@ -from typing import TYPE_CHECKING, Optional, Any, Callable +from typing import Optional, Any, Callable from pathlib import Path import ast from agentstack import conf, log from agentstack.exceptions import ValidationError +from agentstack.generation import InsertionPoint +from agentstack.frameworks import BaseEntrypointFile from agentstack._tools import ToolConfig from agentstack.tasks import TaskConfig from agentstack.agents import AgentConfig from agentstack.generation import asttools from agentstack import graph -if TYPE_CHECKING: - from agentstack.generation import InsertionPoint + NAME: str = "Framework" ENTRYPOINT: Path = Path('src/.py') -class FrameworkFile(asttools.File): +class FrameworkFile(BaseEntrypointFile): """ Parses and manipulates the entrypoint file. All AST interactions should happen within the methods of this class. """ - - def get_task_methods(self) -> list[ast.FunctionDef]: - """A `task` method is a method decorated with `@task`.""" - pass - def add_task_method(self, task: TaskConfig) -> None: - """Add a new task method to the entrypoint.""" - pass + base_class_pattern = r'\w+Stack$' + agent_decorator_name: str = 'agent' + task_decorator_name: str = 'task' - def get_agent_methods(self) -> list[ast.FunctionDef]: - """An `agent` method is a method decorated with `@agent`.""" + def get_new_task_method(self, task: TaskConfig) -> str: + """Get the content of a new task method. """ pass - def add_agent_method(self, agent: AgentConfig) -> None: - """Add a new agent method to the entrypoint.""" + def get_new_agent_method(self, agent: AgentConfig) -> str: + """Get the content of a new agent method.""" pass - def get_agent_tools(self, agent_name: str) -> ast.List: - """Get the tools used by an agent as AST nodes.""" - pass - def get_agent_tool_names(self, agent_name: str) -> list[str]: - """Get a list of all tools used by the agent.""" - pass - - def add_agent_tools(self, agent_name: str, tool: ToolConfig) -> None: - """Add new tools to be used by an agent.""" - pass - - def remove_agent_tools(self, agent_name: str, tool: ToolConfig) -> None: - """Remove tools from an agent belonging to `tool`.""" - pass +def get_entrypoint() -> FrameworkFile: + """Get the entrypoint file.""" + return FrameworkFile(conf.PATH / ENTRYPOINT) def validate_project() -> None: @@ -59,80 +45,28 @@ def validate_project() -> None: Validate that the project is ready to run. Raises an `agentstack.ValidationError` if the project is not valid. """ - try: - entrypoint = FrameworkFile(conf.PATH / ENTRYPOINT) - except ValidationError as e: - raise e - - # Add additional validation checks here - # ie. check for a base class, check for a `main` method, etc. - - # The class must have one or more methods decorated with `@task` - if len(entrypoint.get_task_methods()) < 1: - raise ValidationError( - f"`@task` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new task using `agentstack generate task `." - ) - - # The class must have one or more methods decorated with `@agent` - if len(entrypoint.get_agent_methods()) < 1: - raise ValidationError( - f"`@agent` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new agent using `agentstack generate agent `." - ) - - -def parse_llm(llm: str) -> tuple[str, str]: - """ - Parse the llm string into a tuple of `provider` and `model`. - """ - provider, model = llm.split('/') - return provider, model - - -def get_task_method_names() -> list[str]: - """ - Get a list of task names (methods with an @task decorator). - """ - entrypoint = FrameworkFile(conf.PATH / ENTRYPOINT) - return [method.name for method in entrypoint.get_task_methods()] + return # No additional validation needed. -def add_task(task: TaskConfig, position: Optional['InsertionPoint'] = None) -> None: +def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None) -> None: """ Add a task method to the entrypoint. """ if position is not None: raise NotImplementedError(f"Task insertion points are not supported in {NAME}.") - with FrameworkFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_task_method(task) -def get_agent_method_names() -> list[str]: - """ - Get a list of agent names (methods with an @agent decorator). - """ - entrypoint = FrameworkFile(conf.PATH / ENTRYPOINT) - return [method.name for method in entrypoint.get_agent_methods()] - - -def get_agent_tool_names(agent_name: str) -> list[Any]: - """ - Get a list of tools used by an agent. - """ - with FrameworkFile(conf.PATH / ENTRYPOINT) as entrypoint: - return entrypoint.get_agent_tool_names(agent_name) - - -def add_agent(agent: AgentConfig, position: Optional['InsertionPoint'] = None) -> None: +def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None) -> None: """ Add an agent method to the entrypoint. """ if position is not None: raise NotImplementedError(f"Agent insertion points are not supported in {NAME}.") - with FrameworkFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_agent_method(agent) @@ -140,7 +74,7 @@ def add_tool(tool: ToolConfig, agent_name: str): """ Add a tool to the entrypoint for the specified agent. """ - with FrameworkFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_agent_tools(agent_name, tool) @@ -148,7 +82,7 @@ def remove_tool(tool: ToolConfig, agent_name: str): """ Remove a tool from the entrypoint for the specified agent. """ - with FrameworkFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.remove_agent_tools(agent_name, tool) diff --git a/agentstack/frameworks/openai_swarm.py b/agentstack/frameworks/openai_swarm.py index c4c6e5ad..026d1a6b 100644 --- a/agentstack/frameworks/openai_swarm.py +++ b/agentstack/frameworks/openai_swarm.py @@ -4,6 +4,7 @@ from agentstack import conf, log from agentstack.exceptions import ValidationError from agentstack.generation import InsertionPoint +from agentstack.frameworks import BaseEntrypointFile from agentstack._tools import ToolConfig from agentstack.tasks import TaskConfig from agentstack.agents import AgentConfig @@ -15,52 +16,15 @@ ENTRYPOINT: Path = Path('src/stack.py') -class SwarmFile(asttools.File): +class SwarmFile(BaseEntrypointFile): """ Parses and manipulates the entrypoint file. All AST interactions should happen within the methods of this class. """ - def get_base_class(self) -> ast.ClassDef: - """ - A base class is the first class inside of the file that follows the - naming convention: `Stack` - """ - try: - return asttools.find_class_with_regex(self.tree, r'\w+Stack$')[0] - except IndexError: - raise ValidationError(f"`Stack` class not found in {ENTRYPOINT}") - - def get_run_method(self) -> ast.FunctionDef: - """A method named `run`.""" - try: - base_class = self.get_base_class() - node = asttools.find_method_in_class(base_class, 'run')[0] - assert 'inputs' in (arg.arg for arg in node.args.args) - return node - except IndexError: - raise ValidationError(f"`run` method not found in `{base_class.name} class in {ENTRYPOINT}.") - except AssertionError: - raise ValidationError( - f"Method `run` of `{base_class.name}` must accept `inputs` as a keyword argument." - ) - - def get_task_methods(self) -> list[ast.FunctionDef]: - """A `task` method is a method decorated with `@task`.""" - return asttools.find_decorated_method_in_class(self.get_base_class(), 'task') - - def add_task_method(self, task: TaskConfig): - """Add a new task method to the entrypoint.""" - task_methods = self.get_task_methods() - if task_methods: - # Add after the existing task methods - _, pos = self.get_node_range(task_methods[-1]) - else: - # Add before the `main` method - main_method = self.get_run_method() - pos, _ = self.get_node_range(main_method) - - code = f""" @agentstack.task + def get_new_task_method(self, task: TaskConfig) -> str: + """Get the content of a new task method.""" + return f""" @agentstack.task def {task.name}(self, messages: list[str] = []) -> Agent: task_config = agentstack.get_task('{task.name}') agent = getattr(self, task_config.agent) @@ -70,33 +34,9 @@ def {task.name}(self, messages: list[str] = []) -> Agent: ] return agent(messages)""" - if not self.source[:pos].endswith('\n'): - code = '\n\n' + code - if not self.source[pos:].startswith('\n'): - code += '\n\n' - self.edit_node_range(pos, pos, code) - - # add a new task to the last agent in the stack - existing_agent_methods = self.get_agent_methods() - if not len(existing_agent_methods): - return # no agents to update - - def get_agent_methods(self) -> list[ast.FunctionDef]: - """An `agent` method is a method decorated with `@agent`.""" - return asttools.find_decorated_method_in_class(self.get_base_class(), 'agent') - - def add_agent_method(self, agent: AgentConfig) -> None: - """Add a new agent method to the entrypoint.""" - agent_methods = self.get_agent_methods() - if agent_methods: - # Add after the existing agent methods - _, pos = self.get_node_range(agent_methods[-1]) - else: - # Add before the `main` method - main_method = self.get_run_method() - pos, _ = self.get_node_range(main_method) - - code = f""" @agentstack.agent + def get_new_agent_method(self, agent: AgentConfig) -> str: + """Get the content of a new agent method.""" + return f""" @agentstack.agent def {agent.name}(self, messages: list[str] = []) -> Agent: agent_config = agentstack.get_agent('{agent.name}') messages = [ @@ -110,14 +50,8 @@ def {agent.name}(self, messages: list[str] = []) -> Agent: functions=[], )""" - if not self.source[:pos].endswith('\n'): - code = '\n\n' + code - if not self.source[pos:].startswith('\n'): - code += '\n\n' - self.edit_node_range(pos, pos, code) - def get_agent_tools(self, agent_name: str) -> ast.List: - """Get the tools used by an agent as AST nodes.""" + """Get the list of tools used by an agent as an AST List node.""" method = asttools.find_method(self.get_agent_methods(), agent_name) if method is None: raise ValidationError(f"Agent method `{agent_name}` does not exist in {ENTRYPOINT}") @@ -131,61 +65,19 @@ def get_agent_tools(self, agent_name: str) -> ast.List: tools_kwarg = asttools.find_kwarg_in_method_call(agent_init, 'functions') if not tools_kwarg: - raise ValidationError( - f"`@agent` method `{agent_name}` does not have a keyword argument `functions` in {ENTRYPOINT}" - ) + raise ValidationError(f"`Agent` does not have a keyword argument `functions` in {ENTRYPOINT}") if not isinstance(tools_kwarg.value, ast.List): - raise ValidationError( - f"`@agent` method `{agent_name}` has a non-list value for the `functions` kwarg in {ENTRYPOINT}" - ) + raise ValidationError(f"`Agent` must define a list for kwarg `tools` in {ENTRYPOINT}") return tools_kwarg.value - def get_agent_tool_nodes(self, agent_name: str) -> list[ast.Starred]: - """ - Get a list of all ast nodes that define agentstack tools used by the agent. - """ - agent_tools_node = self.get_agent_tools(agent_name) - return asttools.find_tool_nodes(agent_tools_node) - - def get_agent_tool_names(self, agent_name: str) -> list[str]: - """Get a list of all tools used by the agent.""" - tool_names: list[str] = [] - for node in self.get_agent_tool_nodes(agent_name): - # ignore type checking here since `get_agent_tool_nodes` is exhaustive - tool_names.append(node.value.slice.value) # type: ignore[attr-defined] - return tool_names - - def add_agent_tools(self, agent_name: str, tool: ToolConfig) -> None: - """Add new tools to be used by an agent.""" - method = asttools.find_method(self.get_agent_methods(), agent_name) - if method is None: - raise ValidationError(f"`@agent` method `{agent_name}` does not exist in {ENTRYPOINT}") - - existing_node: ast.List = self.get_agent_tools(agent_name) - existing_elts: list[ast.expr] = existing_node.elts - new_tool_nodes: list[ast.expr] = [] - if not tool.name in self.get_agent_tool_names(agent_name): - existing_elts.append(asttools.create_tool_node(tool.name)) - - new_node = ast.List(elts=existing_elts, ctx=ast.Load()) - start, end = self.get_node_range(existing_node) - self.edit_node_range(start, end, new_node) - - def remove_agent_tools(self, agent_name: str, tool: ToolConfig) -> None: - """Remove tools from an agent belonging to `tool`.""" - existing_node: ast.List = self.get_agent_tools(agent_name) - start, end = self.get_node_range(existing_node) - - # modify the existing node to remove any matching tools - for node in self.get_agent_tool_nodes(agent_name): - # ignore type checking here since `get_agent_tool_nodes` is exhaustive - if tool.name == node.value.slice.value: # type: ignore[attr-defined] - existing_node.elts.remove(node) - - self.edit_node_range(start, end, existing_node) +def get_entrypoint() -> SwarmFile: + """ + Get the entrypoint file. + """ + return SwarmFile(conf.PATH / ENTRYPOINT) def validate_project() -> None: @@ -193,81 +85,20 @@ def validate_project() -> None: Validate that the project is ready to run. Raises an `agentstack.ValidationError` if the project is not valid. """ - try: - entrypoint = SwarmFile(conf.PATH / ENTRYPOINT) - except ValidationError as e: - raise e - - # A valid project must have a class in the entrypoint file - try: - class_node = entrypoint.get_base_class() - except ValidationError as e: - raise e - - # The class must have a `run` method - try: - entrypoint.get_run_method() - except ValidationError as e: - raise e + return # No additional validation needed - # The class must have one or more methods decorated with `@task` - if len(entrypoint.get_task_methods()) < 1: - raise ValidationError( - f"`@task` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new task using `agentstack generate task `." - ) - # The class must have one or more methods decorated with `@agent` - if len(entrypoint.get_agent_methods()) < 1: - raise ValidationError( - f"`@agent` decorated method not found in `{class_node.name}` class in {ENTRYPOINT}.\n" - "Create a new agent using `agentstack generate agent `." - ) - - -def parse_llm(llm: str) -> tuple[str, str]: - """ - Parse the llm string into a tuple of `provider` and `model`. - """ - provider, model = llm.split('/') - return provider, model - - -def get_task_method_names() -> list[str]: - """ - Get a list of task names (methods with an @task decorator). - """ - entrypoint = SwarmFile(conf.PATH / ENTRYPOINT) - return [method.name for method in entrypoint.get_task_methods()] - - -def add_task(task: TaskConfig, position: Optional['InsertionPoint'] = None) -> None: +def add_task(task: TaskConfig, position: Optional[InsertionPoint] = None) -> None: """ Add a task method to the entrypoint. """ if position is not None: raise NotImplementedError(f"Task insertion points are not supported in {NAME}.") - with SwarmFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_task_method(task) -def get_agent_method_names() -> list[str]: - """ - Get a list of agent names (methods with an @agent decorator). - """ - entrypoint = SwarmFile(conf.PATH / ENTRYPOINT) - return [method.name for method in entrypoint.get_agent_methods()] - - -def get_agent_tool_names(agent_name: str) -> list[Any]: - """ - Get a list of tools used by an agent. - """ - with SwarmFile(conf.PATH / ENTRYPOINT) as entrypoint: - return entrypoint.get_agent_tool_names(agent_name) - - def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None) -> None: """ Add an agent method to the entrypoint. @@ -275,7 +106,7 @@ def add_agent(agent: AgentConfig, position: Optional[InsertionPoint] = None) -> if position is not None: raise NotImplementedError(f"Agent insertion points are not supported in {NAME}.") - with SwarmFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_agent_method(agent) @@ -283,7 +114,7 @@ def add_tool(tool: ToolConfig, agent_name: str): """ Add a tool to the entrypoint for the specified agent. """ - with SwarmFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.add_agent_tools(agent_name, tool) @@ -291,7 +122,7 @@ def remove_tool(tool: ToolConfig, agent_name: str): """ Remove a tool from the entrypoint for the specified agent. """ - with SwarmFile(conf.PATH / ENTRYPOINT) as entrypoint: + with get_entrypoint() as entrypoint: entrypoint.remove_agent_tools(agent_name, tool) diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py b/agentstack/frameworks/templates/__init__.py similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py rename to agentstack/frameworks/templates/__init__.py diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.env.example b/agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.env.example similarity index 100% rename from agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.env.example rename to agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.env.example diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.gitignore b/agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.gitignore similarity index 100% rename from agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.gitignore rename to agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/.gitignore diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md b/agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md similarity index 100% rename from agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md rename to agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/README.md b/agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/README.md similarity index 100% rename from agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/README.md rename to agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/README.md diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/agentstack.json b/agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/agentstack.json similarity index 100% rename from agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/agentstack.json rename to agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/agentstack.json diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml b/agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml similarity index 100% rename from agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml rename to agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/src/main.py b/agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/src/main.py similarity index 100% rename from agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/src/main.py rename to agentstack/frameworks/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/src/main.py diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.env.example b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.env.example similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.env.example rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.env.example diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.gitignore b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.gitignore similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.gitignore rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.gitignore diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/README.md b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/README.md similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/README.md rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/README.md diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/agentstack.json b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/agentstack.json similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/agentstack.json rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/agentstack.json diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/crew.py b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/crew.py similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/crew.py rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/crew.py diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/main.py b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/main.py similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/main.py rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/main.py diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py b/agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py rename to agentstack/frameworks/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.env.example b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.env.example similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.env.example rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.env.example diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.gitignore b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.gitignore similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.gitignore rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/.gitignore diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/README.md b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/README.md similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/README.md rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/README.md diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/agentstack.json b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/agentstack.json similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/agentstack.json rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/agentstack.json diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/graph.py b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/graph.py similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/graph.py rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/graph.py diff --git a/agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/main.py b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/main.py similarity index 100% rename from agentstack/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/main.py rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/main.py diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py b/agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py rename to agentstack/frameworks/templates/langgraph/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.env.example b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/.env.example similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.env.example rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/.env.example diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.gitignore b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/.gitignore similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.gitignore rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/.gitignore diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md diff --git a/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/README.md b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/README.md new file mode 100644 index 00000000..06df5f4f --- /dev/null +++ b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/README.md @@ -0,0 +1,26 @@ +# {{ cookiecutter.project_metadata.project_name }} +{{ cookiecutter.project_metadata.description }} + +## How to build your LlamaIndex Agent +### With the CLI +Add an agent using AgentStack with the CLI: +`agentstack generate agent ` +You can also shorten this to `agentstack g a ` +For wizard support use `agentstack g a --wizard` +Finally for creation in the CLI alone, use `agentstack g a --role/-r --goal/-g --backstory/-b --model/-m ` + +This will automatically create a new agent in the `agents.yaml` config as well as in your code. Either placeholder strings will be used, or data included in the wizard. + +Similarly, tasks can be created with `agentstack g t ` + +Add tools with `agentstack tools add` and view tools available with `agentstack tools list` + +## How to use your Agent +In this directory, run `uv pip install --requirements pyproject.toml` + +To run your project, use the following command: +`agentstack run` + +This will initialize your AI agent project and begin task execution as defined in your configuration in the main.py file. + +> 🪩 Project built with [AgentStack](https://github.com/AgentOps-AI/AgentStack) diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/agentstack.json b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/agentstack.json similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/agentstack.json rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/agentstack.json diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml diff --git a/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/main.py b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/main.py new file mode 100644 index 00000000..1fd56bfc --- /dev/null +++ b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/main.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +import asyncio +import agentstack +import agentops +from stack import {{ cookiecutter.project_metadata.class_name }}Stack + + +agentops.init(default_tags=agentstack.get_tags()) + +instance = {{ cookiecutter.project_metadata.class_name }}Stack() + +async def run(): + """ + Run the agent. + """ + await instance.run(inputs=agentstack.get_inputs()) + agentops.end_session(end_state='Success') + +if __name__ == '__main__': + asyncio.run(run) \ No newline at end of file diff --git a/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/stack.py b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/stack.py new file mode 100644 index 00000000..c2302371 --- /dev/null +++ b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/stack.py @@ -0,0 +1,35 @@ +import asyncio +from llama_index.core.llms import ChatMessage +from llama_index.core.agent.workflow import ( + FunctionAgent, + AgentWorkflow, + AgentOutput, + ToolCallResult, +) +import agentstack + + +class {{ cookiecutter.project_metadata.class_name }}Stack: + + async def run(self, inputs: dict[str, str]): + # TODO interpolate inputs into prompts + history: list[ChatMessage] = [] + for task_config in agentstack.get_all_tasks(): + task = getattr(self, task_config.name) + agent = getattr(self, task_config.agent) + workflow = AgentWorkflow( + agents=[agent(), ], + ) + history.append(task()) + handler = workflow.run( + chat_history=history, + ) + + async for event in handler.stream_events(): + if isinstance(event, AgentOutput) and event.response.content: + agentstack.log.notify(event.current_agent_name) + agentstack.log.info(event.response.content) + history.append(ChatMessage(role="assistant", content=event.response.content)) + elif isinstance(event, ToolCallResult): + agentstack.log.notify(f"tool: {event.tool_name}") + agentstack.log.info(event.tool_output) \ No newline at end of file diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/agentstack.log b/agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/agentstack.log rename to agentstack/frameworks/templates/llamaindex/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py diff --git a/agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.env b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.env.example similarity index 100% rename from agentstack/templates/crewai/{{cookiecutter.project_metadata.project_slug}}/.env rename to agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.env.example diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.gitignore b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.gitignore new file mode 100644 index 00000000..8ce42678 --- /dev/null +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/.gitignore @@ -0,0 +1,164 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +.agentops/ diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md new file mode 100644 index 00000000..5ea2f54d --- /dev/null +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/LICENSE.md @@ -0,0 +1,404 @@ +{%- if cookiecutter.project_metadata.license == "MIT" %} +MIT License + +Copyright (c) {{ cookiecutter.project_metadata.year }} {{ cookiecutter.project_metadata.author_name }} + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +{%- endif %} + + +{%- if cookiecutter.project_metadata.license == "Apache-2.0" %} + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {{ cookiecutter.project_metadata.year }} {{ cookiecutter.project_metadata.author_name }} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +{%- endif %} + +{%- if cookiecutter.project_metadata.license == "GNU" %} +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +0. Definitions. +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS +{%- endif %} \ No newline at end of file diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/README.md b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/README.md similarity index 100% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/README.md rename to agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/README.md diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/agentstack.json b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/agentstack.json new file mode 100644 index 00000000..5511a17a --- /dev/null +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/agentstack.json @@ -0,0 +1,6 @@ +{ + "framework": "{{ cookiecutter.framework }}", + "agentstack_version": "{{ cookiecutter.project_metadata.agentstack_version }}", + "template": "{{ cookiecutter.project_metadata.template }}", + "template_version": "{{ cookiecutter.project_metadata.template_version }}" +} \ No newline at end of file diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml new file mode 100644 index 00000000..f6dc4cf6 --- /dev/null +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/pyproject.toml @@ -0,0 +1,13 @@ +[project] +name = "{{cookiecutter.project_metadata.project_name}}" +version = "{{cookiecutter.project_metadata.version}}" +description = "{{cookiecutter.project_metadata.description}}" +authors = [ + { name = "{{cookiecutter.project_metadata.author_name}}" } +] +license = { text = "{{cookiecutter.project_metadata.license}}" } +requires-python = ">=3.10" + +dependencies = [ + "agentstack[{{cookiecutter.framework}}]>={{cookiecutter.project_metadata.agentstack_version}}", +] \ No newline at end of file diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml new file mode 100644 index 00000000..eed47206 --- /dev/null +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/agents.yaml @@ -0,0 +1,10 @@ +{%- for agent in cookiecutter.structure.agents %} +{{agent.name}}: + role: > + {{agent.role}} + goal: > + {{agent.goal}} + backstory: > + {{agent.backstory}} + llm: {{agent.llm}} +{%- endfor %} \ No newline at end of file diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml new file mode 100644 index 00000000..fcac19a9 --- /dev/null +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/inputs.yaml @@ -0,0 +1,4 @@ +{%- for key, value in cookiecutter.structure.inputs.items() %} +{{key}}: > + {{value}} +{%- endfor %} \ No newline at end of file diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml new file mode 100644 index 00000000..63e43048 --- /dev/null +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/config/tasks.yaml @@ -0,0 +1,8 @@ +{%- for task in cookiecutter.structure.tasks %} +{{task.name}}: + description: > + {{task.description}} + expected_output: > + {{task.expected_output}} + agent: {{task.agent}} +{%- endfor %} \ No newline at end of file diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/main.py b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/main.py similarity index 56% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/main.py rename to agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/main.py index 0d6d25cb..364242c2 100644 --- a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/main.py +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/main.py @@ -1,12 +1,12 @@ #!/usr/bin/env python import agentstack import agentops -from stack import {{cookiecutter.project_metadata.project_name|replace('-', '')|replace('_', '')|capitalize}}Stack +from stack import {{ cookiecutter.project_metadata.class_name }}Stack agentops.init(default_tags=agentstack.get_tags()) -instance = {{cookiecutter.project_metadata.project_name|replace('-', '')|replace('_', '')|capitalize}}Stack() +instance = {{ cookiecutter.project_metadata.class_name }}Stack() def run(): """ diff --git a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/stack.py b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/stack.py similarity index 88% rename from agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/stack.py rename to agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/stack.py index b0592a2b..30caf808 100644 --- a/agentstack/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/stack.py +++ b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/stack.py @@ -2,7 +2,7 @@ import agentstack -class {{ cookiecutter.project_metadata.project_name|replace('-', '')|replace('_', '')|capitalize }}Stack: +class {{ cookiecutter.project_metadata.class_name }}Stack: def run(self, inputs: list[str]): app = Swarm() diff --git a/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py b/agentstack/frameworks/templates/openai_swarm/{{cookiecutter.project_metadata.project_slug}}/src/tools/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/agentstack/generation/asttools.py b/agentstack/generation/asttools.py index 72d4b368..991d34fd 100644 --- a/agentstack/generation/asttools.py +++ b/agentstack/generation/asttools.py @@ -64,17 +64,22 @@ def write(self): with open(self.filename, 'w', encoding='utf-8') as f: f.write(self.source) + def _render_node(self, node: Union[str, ASTT]) -> str: + if isinstance(node, ast.AST): + _node: ast.AST = node + if isinstance(node, ast.expr): + _node = ast.Module(body=[ast.Expr(value=node)], type_ignores=[]) + return astor.to_source(_node).strip() + + return node # already a string + def get_node_range(self, node: ast.AST) -> tuple[int, int]: """Get the string start and end indexes for a node in the source code.""" return self.atok.get_text_range(node) - def edit_node_range(self, start: int, end: int, node: Union[str, ast.AST]): + def edit_node_range(self, start: int, end: int, node: Union[str, ASTT]): """Splice a new node or string into the source code at the given range.""" - if isinstance(node, ast.expr): - module = ast.Module(body=[ast.Expr(value=node)], type_ignores=[]) - _node = astor.to_source(module).strip() - else: - _node = node + _node = self._render_node(node) self.source = self.source[:start] + _node + self.source[end:] # In order to continue accurately modifying the AST, we need to re-parse the source. @@ -85,6 +90,23 @@ def edit_node_range(self, start: int, end: int, node: Union[str, ast.AST]): else: raise ValidationError(f"Failed to parse {self.filename} after edit") + def insert_method(self, pos: int, node: Union[str, ast.FunctionDef]) -> None: + """Insert a method node into the source code at the given position.""" + # since this is a method, we can make assumptions about the formatting + _node = self._render_node(node).strip('\n') + + if not self.source[:pos].endswith('\n'): + _node = '\n\n' + _node + elif not self.source[:pos].endswith('\n\n'): + _node = '\n' + _node + + if not self.source[pos:].startswith('\n'): + _node += '\n\n' + elif not self.source[pos:].startswith('\n\n'): + _node += '\n' + + self.edit_node_range(pos, pos, _node) + def remove_node(self, node: ast.AST) -> None: """Remove a node from the source code.""" start, end = self.get_node_range(node) @@ -184,6 +206,14 @@ def find_class_instantiation(tree: Union[Iterable[ast.AST], ast.AST], class_name return None +def find_class(tree: ast.Module, class_name: str) -> Optional[ast.ClassDef]: + """Find a class definition in an AST.""" + for node in ast.iter_child_nodes(tree): + if isinstance(node, ast.ClassDef) and node.name == class_name: + return node + return None + + def find_class_with_decorator(tree: ast.Module, decorator_name: str) -> list[ast.ClassDef]: """Find a class definition that is marked by a decorator in an AST.""" nodes = [] @@ -206,14 +236,16 @@ def find_class_with_regex(tree: ast.Module, expr: str) -> list[ast.ClassDef]: return nodes -def find_method_in_class(classdef: ast.ClassDef, method_name: str) -> list[ast.FunctionDef]: +def find_method_in_class(classdef: ast.ClassDef, method_name: str) -> Union[None, ast.FunctionDef, ast.AsyncFunctionDef]: """Find all methods named `method_name`.""" - nodes = [] for node in ast.iter_child_nodes(classdef): if isinstance(node, ast.FunctionDef): if node.name == method_name: - nodes.append(node) - return nodes + return node + elif isinstance(node, ast.AsyncFunctionDef): + if node.name == method_name: + return node + return None def find_decorated_method_in_class(classdef: ast.ClassDef, decorator_name: str) -> list[ast.FunctionDef]: diff --git a/agentstack/proj_templates.py b/agentstack/proj_templates.py deleted file mode 100644 index e678a9af..00000000 --- a/agentstack/proj_templates.py +++ /dev/null @@ -1,308 +0,0 @@ -from typing import Optional, Literal, Union -import os, sys -from pathlib import Path -import pydantic -import requests -import json -from agentstack.exceptions import ValidationError -from agentstack.utils import get_package_path - -CURRENT_VERSION: Literal[4] = 4 - - -def _model_dump_agent(agent: Union[dict, pydantic.BaseModel]) -> dict: - """Between template version 3 and 4 we fixed the naming of the model/llm field. """ - if isinstance(agent, pydantic.BaseModel): - agent = agent.model_dump() - return { - "name": agent['name'], - "role": agent['role'], - "goal": agent['goal'], - "backstory": agent['backstory'], - "llm": agent['model'], # model -> llm - } - - -class TemplateConfig_v1(pydantic.BaseModel): - name: str - description: str - template_version: Literal[1] - framework: str - method: str - agents: list[dict] - tasks: list[dict] - tools: list[dict] - inputs: list[str] - - def to_v4(self) -> 'TemplateConfig': - return TemplateConfig( - name=self.name, - description=self.description, - template_version=CURRENT_VERSION, - framework=self.framework, - method=self.method, - manager_agent=None, - agents=[TemplateConfig.Agent(**_model_dump_agent(agent)) for agent in self.agents], - tasks=[TemplateConfig.Task(**task) for task in self.tasks], - tools=[TemplateConfig.Tool(**tool) for tool in self.tools], - graph=[], - inputs={key: "" for key in self.inputs}, - ) - - -class TemplateConfig_v2(pydantic.BaseModel): - class Agent(pydantic.BaseModel): - name: str - role: str - goal: str - backstory: str - model: str - - class Task(pydantic.BaseModel): - name: str - description: str - expected_output: str - agent: str - - class Tool(pydantic.BaseModel): - name: str - agents: list[str] - - name: str - description: str - template_version: Literal[2] - framework: str - method: str - agents: list[Agent] - tasks: list[Task] - tools: list[Tool] - inputs: dict[str, str] - - def to_v4(self) -> 'TemplateConfig': - return TemplateConfig( - name=self.name, - description=self.description, - template_version=CURRENT_VERSION, - framework=self.framework, - method=self.method, - manager_agent=None, - agents=[TemplateConfig.Agent(**_model_dump_agent(agent)) for agent in self.agents], - tasks=[TemplateConfig.Task(**task.model_dump()) for task in self.tasks], - tools=[TemplateConfig.Tool(**tool.model_dump()) for tool in self.tools], - graph=[], - inputs=self.inputs, - ) - - -class TemplateConfig_v3(pydantic.BaseModel): - class Agent(pydantic.BaseModel): - name: str - role: str - goal: str - backstory: str - allow_delegation: bool = False - model: str - - class Task(pydantic.BaseModel): - name: str - description: str - expected_output: str - agent: str - - class Tool(pydantic.BaseModel): - name: str - agents: list[str] - - name: str - description: str - template_version: Literal[3] - framework: str - method: str - manager_agent: Optional[str] - agents: list[Agent] - tasks: list[Task] - tools: list[Tool] - inputs: dict[str, str] - - def to_v4(self) -> 'TemplateConfig': - return TemplateConfig( - name=self.name, - description=self.description, - template_version=CURRENT_VERSION, - framework=self.framework, - method=self.method, - manager_agent=self.manager_agent, - agents=[TemplateConfig.Agent(**_model_dump_agent(agent)) for agent in self.agents], - tasks=[TemplateConfig.Task(**task.model_dump()) for task in self.tasks], - tools=[TemplateConfig.Tool(**tool.model_dump()) for tool in self.tools], - graph=[], - inputs=self.inputs, - ) - - -class TemplateConfig(pydantic.BaseModel): - """ - Interface for interacting with template configuration files. - - Templates are read-only. - - Template Schema - ------------- - name: str - The name of the project. - description: str - A description of the template. - template_version: int - The version of the template. - framework: str - The framework the template is for. - method: str - The method used by the project. ie. "sequential" - manager_agent: Optional[str] - The name of the agent that manages the project. - agents: list[TemplateConfig.Agent] - A list of agents used by the project. - tasks: list[TemplateConfig.Task] - A list of tasks used by the project. - tools: list[TemplateConfig.Tool] - A list of tools used by the project. - graph: list[list[TemplateConfig.Node]] - A list of graph relationships. Each edge must have exactly 2 nodes. - inputs: dict[str, str] - Key/value pairs of inputs used by the project. - """ - - class Agent(pydantic.BaseModel): - name: str - role: str - goal: str - backstory: str - allow_delegation: bool = False - llm: str - - class Task(pydantic.BaseModel): - name: str - description: str - expected_output: str - agent: str # TODO this is redundant with the graph - - class Tool(pydantic.BaseModel): - name: str - agents: list[str] - - class Node(pydantic.BaseModel): - type: Literal["agent", "task", "special"] - name: str - - name: str - description: str - template_version: Literal[4] = CURRENT_VERSION - framework: str - method: str = "sequential" - manager_agent: Optional[str] = None - agents: list[Agent] = pydantic.Field(default_factory=list) - tasks: list[Task] = pydantic.Field(default_factory=list) - tools: list[Tool] = pydantic.Field(default_factory=list) - graph: list[list[Node]] = pydantic.Field(default_factory=list) - inputs: dict[str, str] = pydantic.Field(default_factory=dict) - - @pydantic.field_validator('graph') - @classmethod - def validate_graph_edges(cls, value: list[list[Node]]) -> list[list[Node]]: - for i, edge in enumerate(value): - if len(edge) != 2: - raise ValueError(f"Graph edge {i} must have exactly 2 nodes.") - return value - - def write_to_file(self, filename: Path): - if not filename.suffix == '.json': - filename = filename.with_suffix('.json') - - with open(filename, 'w') as f: - model_dump = self.model_dump() - f.write(json.dumps(model_dump, indent=4)) - - @classmethod - def from_user_input(cls, identifier: str): - """ - Load a template from a user-provided identifier. - Three cases will be tried: A URL, a file path, or a template name. - """ - if identifier.startswith('https://'): - return cls.from_url(identifier) - - if identifier.endswith('.json'): - path = Path() / identifier - return cls.from_file(path) - - return cls.from_template_name(identifier) - - @classmethod - def from_template_name(cls, name: str) -> 'TemplateConfig': - path = get_package_path() / f'templates/proj_templates/{name}.json' - if not name in get_all_template_names(): - raise ValidationError(f"Template {name} not bundled with agentstack.") - return cls.from_file(path) - - @classmethod - def from_file(cls, path: Path) -> 'TemplateConfig': - if not os.path.exists(path): - raise ValidationError(f"Template {path} not found.") - try: - with open(path, 'r') as f: - return cls.from_json(json.load(f)) - except json.JSONDecodeError as e: - raise ValidationError(f"Error decoding template JSON.\n{e}") - except ValidationError as e: - raise ValidationError(f"{e}\nTemplateConfig.from_file({path})") - - @classmethod - def from_url(cls, url: str) -> 'TemplateConfig': - if not url.startswith("https://"): - raise ValidationError(f"Invalid URL: {url}") - response = requests.get(url) - if response.status_code != 200: - raise ValidationError(f"Failed to fetch template from {url}") - try: - return cls.from_json(response.json()) - except json.JSONDecodeError as e: - raise ValidationError(f"Error decoding template JSON.\n{e}") - except ValidationError as e: - raise ValidationError(f"{e}\nTemplateConfig.from_url({url})") - - @classmethod - def from_json(cls, data: dict) -> 'TemplateConfig': - try: - match data.get('template_version'): - case 1: - return TemplateConfig_v1(**data).to_v4() - case 2: - return TemplateConfig_v2(**data).to_v4() - case 3: - return TemplateConfig_v3(**data).to_v4() - case 4: - return cls(**data) # current version - case _: - raise ValidationError(f"Unsupported template version: {data.get('template_version')}") - except pydantic.ValidationError as e: - err_msg = "Error validating template config JSON:\n" - for error in e.errors(): - err_msg += f"{' '.join([str(loc) for loc in error['loc']])}: {error['msg']}\n" - raise ValidationError(err_msg) - - -def get_all_template_paths() -> list[Path]: - paths = [] - templates_dir = get_package_path() / 'templates/proj_templates' - for file in templates_dir.iterdir(): - if file.suffix == '.json': - paths.append(file) - return paths - - -def get_all_template_names() -> list[str]: - return [path.stem for path in get_all_template_paths()] - - -def get_all_templates() -> list[TemplateConfig]: - return [TemplateConfig.from_file(path) for path in get_all_template_paths()] diff --git a/agentstack/providers.py b/agentstack/providers.py new file mode 100644 index 00000000..f433d59e --- /dev/null +++ b/agentstack/providers.py @@ -0,0 +1,15 @@ +from agentstack.exceptions import ValidationError + + +def parse_provider_model(model_id: str) -> tuple[str, str]: + """Parse the provider and model name from the model ID""" + # most providers are in the format "/" + # openrouter models are in the format "openrouter//" + parts = tuple(model_id.split('/')) + if len(parts) == 2: + return parts + elif len(parts) == 3: + return '/'.join(parts[:2]), parts[2] + else: + raise ValidationError(f"Model id '{model_id}' does not match expected format.") + diff --git a/agentstack/templates/__init__.py b/agentstack/templates/__init__.py index e69de29b..1602fc56 100644 --- a/agentstack/templates/__init__.py +++ b/agentstack/templates/__init__.py @@ -0,0 +1,313 @@ +from typing import Optional, Literal, Union +import os, sys +from pathlib import Path +import pydantic +import requests +import json +from agentstack.exceptions import ValidationError +from agentstack.utils import get_package_path + +CURRENT_VERSION: Literal[4] = 4 + + +def _get_builtin_templates_path() -> Path: + return get_package_path() / 'templates' + + +def _model_dump_agent(agent: Union[dict, pydantic.BaseModel]) -> dict: + """Between template version 3 and 4 we fixed the naming of the model/llm field.""" + if isinstance(agent, pydantic.BaseModel): + agent = agent.model_dump() + return { + "name": agent['name'], + "role": agent['role'], + "goal": agent['goal'], + "backstory": agent['backstory'], + "llm": agent['model'], # model -> llm + } + + +class TemplateConfig_v1(pydantic.BaseModel): + name: str + description: str + template_version: Literal[1] + framework: str + method: str + agents: list[dict] + tasks: list[dict] + tools: list[dict] + inputs: list[str] + + def to_v4(self) -> 'TemplateConfig': + return TemplateConfig( + name=self.name, + description=self.description, + template_version=CURRENT_VERSION, + framework=self.framework, + method=self.method, + manager_agent=None, + agents=[TemplateConfig.Agent(**_model_dump_agent(agent)) for agent in self.agents], + tasks=[TemplateConfig.Task(**task) for task in self.tasks], + tools=[TemplateConfig.Tool(**tool) for tool in self.tools], + graph=[], + inputs={key: "" for key in self.inputs}, + ) + + +class TemplateConfig_v2(pydantic.BaseModel): + class Agent(pydantic.BaseModel): + name: str + role: str + goal: str + backstory: str + model: str + + class Task(pydantic.BaseModel): + name: str + description: str + expected_output: str + agent: str + + class Tool(pydantic.BaseModel): + name: str + agents: list[str] + + name: str + description: str + template_version: Literal[2] + framework: str + method: str + agents: list[Agent] + tasks: list[Task] + tools: list[Tool] + inputs: dict[str, str] + + def to_v4(self) -> 'TemplateConfig': + return TemplateConfig( + name=self.name, + description=self.description, + template_version=CURRENT_VERSION, + framework=self.framework, + method=self.method, + manager_agent=None, + agents=[TemplateConfig.Agent(**_model_dump_agent(agent)) for agent in self.agents], + tasks=[TemplateConfig.Task(**task.model_dump()) for task in self.tasks], + tools=[TemplateConfig.Tool(**tool.model_dump()) for tool in self.tools], + graph=[], + inputs=self.inputs, + ) + + +class TemplateConfig_v3(pydantic.BaseModel): + class Agent(pydantic.BaseModel): + name: str + role: str + goal: str + backstory: str + allow_delegation: bool = False + model: str + + class Task(pydantic.BaseModel): + name: str + description: str + expected_output: str + agent: str + + class Tool(pydantic.BaseModel): + name: str + agents: list[str] + + name: str + description: str + template_version: Literal[3] + framework: str + method: str + manager_agent: Optional[str] + agents: list[Agent] + tasks: list[Task] + tools: list[Tool] + inputs: dict[str, str] + + def to_v4(self) -> 'TemplateConfig': + return TemplateConfig( + name=self.name, + description=self.description, + template_version=CURRENT_VERSION, + framework=self.framework, + method=self.method, + manager_agent=self.manager_agent, + agents=[TemplateConfig.Agent(**_model_dump_agent(agent)) for agent in self.agents], + tasks=[TemplateConfig.Task(**task.model_dump()) for task in self.tasks], + tools=[TemplateConfig.Tool(**tool.model_dump()) for tool in self.tools], + graph=[], + inputs=self.inputs, + ) + + +class TemplateConfig(pydantic.BaseModel): + """ + Interface for interacting with template configuration files. + + Templates are read-only. + + Template Schema + ------------- + name: str + The name of the project. + description: str + A description of the template. + template_version: int + The version of the template. + framework: str + The framework the template is for. + method: str + The method used by the project. ie. "sequential" + manager_agent: Optional[str] + The name of the agent that manages the project. + agents: list[TemplateConfig.Agent] + A list of agents used by the project. + tasks: list[TemplateConfig.Task] + A list of tasks used by the project. + tools: list[TemplateConfig.Tool] + A list of tools used by the project. + graph: list[list[TemplateConfig.Node]] + A list of graph relationships. Each edge must have exactly 2 nodes. + inputs: dict[str, str] + Key/value pairs of inputs used by the project. + """ + + class Agent(pydantic.BaseModel): + name: str + role: str + goal: str + backstory: str + allow_delegation: bool = False + llm: str + + class Task(pydantic.BaseModel): + name: str + description: str + expected_output: str + agent: str # TODO this is redundant with the graph + + class Tool(pydantic.BaseModel): + name: str + agents: list[str] + + class Node(pydantic.BaseModel): + type: Literal["agent", "task", "special"] + name: str + + name: str + description: str + template_version: Literal[4] = CURRENT_VERSION + framework: str + method: str = "sequential" + manager_agent: Optional[str] = None + agents: list[Agent] = pydantic.Field(default_factory=list) + tasks: list[Task] = pydantic.Field(default_factory=list) + tools: list[Tool] = pydantic.Field(default_factory=list) + graph: list[list[Node]] = pydantic.Field(default_factory=list) + inputs: dict[str, str] = pydantic.Field(default_factory=dict) + + @pydantic.field_validator('graph') + @classmethod + def validate_graph_edges(cls, value: list[list[Node]]) -> list[list[Node]]: + for i, edge in enumerate(value): + if len(edge) != 2: + raise ValueError(f"Graph edge {i} must have exactly 2 nodes.") + return value + + def write_to_file(self, filename: Path): + if not filename.suffix == '.json': + filename = filename.with_suffix('.json') + + with open(filename, 'w') as f: + model_dump = self.model_dump() + f.write(json.dumps(model_dump, indent=4)) + + @classmethod + def from_user_input(cls, identifier: str): + """ + Load a template from a user-provided identifier. + Three cases will be tried: A URL, a file path, or a template name. + """ + if identifier.startswith('https://'): + return cls.from_url(identifier) + + if identifier.endswith('.json'): + path = Path() / identifier + return cls.from_file(path) + + return cls.from_template_name(identifier) + + @classmethod + def from_template_name(cls, name: str) -> 'TemplateConfig': + if not name in get_all_template_names(): + raise ValidationError(f"Template {name} not bundled with agentstack.") + + path = _get_builtin_templates_path() / f"{name}.json" + return cls.from_file(path) + + @classmethod + def from_file(cls, path: Path) -> 'TemplateConfig': + if not os.path.exists(path): + raise ValidationError(f"Template {path} not found.") + try: + with open(path, 'r') as f: + return cls.from_json(json.load(f)) + except json.JSONDecodeError as e: + raise ValidationError(f"Error decoding template JSON.\n{e}") + except ValidationError as e: + raise ValidationError(f"{e}\nTemplateConfig.from_file({path})") + + @classmethod + def from_url(cls, url: str) -> 'TemplateConfig': + if not url.startswith("https://"): + raise ValidationError(f"Invalid URL: {url}") + response = requests.get(url) + if response.status_code != 200: + raise ValidationError(f"Failed to fetch template from {url}") + try: + return cls.from_json(response.json()) + except json.JSONDecodeError as e: + raise ValidationError(f"Error decoding template JSON.\n{e}") + except ValidationError as e: + raise ValidationError(f"{e}\nTemplateConfig.from_url({url})") + + @classmethod + def from_json(cls, data: dict) -> 'TemplateConfig': + try: + match data.get('template_version'): + case 1: + return TemplateConfig_v1(**data).to_v4() + case 2: + return TemplateConfig_v2(**data).to_v4() + case 3: + return TemplateConfig_v3(**data).to_v4() + case 4: + return cls(**data) # current version + case _: + raise ValidationError(f"Unsupported template version: {data.get('template_version')}") + except pydantic.ValidationError as e: + err_msg = "Error validating template config JSON:\n" + for error in e.errors(): + err_msg += f"{' '.join([str(loc) for loc in error['loc']])}: {error['msg']}\n" + raise ValidationError(err_msg) + + +def get_all_template_paths() -> list[Path]: + paths = [] + templates_dir = _get_builtin_templates_path() + for file in templates_dir.iterdir(): + if file.suffix == '.json': + paths.append(file) + return paths + + +def get_all_template_names() -> list[str]: + return [path.stem for path in get_all_template_paths()] + + +def get_all_templates() -> list[TemplateConfig]: + return [TemplateConfig.from_file(path) for path in get_all_template_paths()] diff --git a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/OAI_CONFIG_LIST b/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/OAI_CONFIG_LIST deleted file mode 100644 index 231afdb6..00000000 --- a/agentstack/templates/autogen/{{cookiecutter.project_metadata.project_slug}}/OAI_CONFIG_LIST +++ /dev/null @@ -1,7 +0,0 @@ -[ - { - "model": "gpt-4", - "api_key": "", - "tags": ["gpt-4", "tool"] - } -] diff --git a/agentstack/templates/proj_templates/content_creator.json b/agentstack/templates/content_creator.json similarity index 100% rename from agentstack/templates/proj_templates/content_creator.json rename to agentstack/templates/content_creator.json diff --git a/agentstack/templates/proj_templates/graph.json.example b/agentstack/templates/graph.json.example similarity index 100% rename from agentstack/templates/proj_templates/graph.json.example rename to agentstack/templates/graph.json.example diff --git a/agentstack/templates/proj_templates/hello_alex.json b/agentstack/templates/hello_alex.json similarity index 100% rename from agentstack/templates/proj_templates/hello_alex.json rename to agentstack/templates/hello_alex.json diff --git a/agentstack/templates/proj_templates/hola_alex.json b/agentstack/templates/hola_alex.json similarity index 100% rename from agentstack/templates/proj_templates/hola_alex.json rename to agentstack/templates/hola_alex.json diff --git a/agentstack/templates/proj_templates/reasoning.json b/agentstack/templates/reasoning.json similarity index 100% rename from agentstack/templates/proj_templates/reasoning.json rename to agentstack/templates/reasoning.json diff --git a/agentstack/templates/proj_templates/research.json b/agentstack/templates/research.json similarity index 100% rename from agentstack/templates/proj_templates/research.json rename to agentstack/templates/research.json diff --git a/agentstack/templates/proj_templates/system_analyzer.json b/agentstack/templates/system_analyzer.json similarity index 100% rename from agentstack/templates/proj_templates/system_analyzer.json rename to agentstack/templates/system_analyzer.json diff --git a/docs/cli-reference/cli.mdx b/docs/cli-reference/cli.mdx index c9dfda3f..841b1a8f 100644 --- a/docs/cli-reference/cli.mdx +++ b/docs/cli-reference/cli.mdx @@ -47,7 +47,7 @@ You can pass the `--wizard` flag to `agentstack init` to use an interactive proj You can also pass a `--template=` argument to `agentstack init` which will pre-populate your project with functionality from a built-in template, or one found on the internet. A `template_name` can be one of three identifiers: -- A built-in AgentStack template (see the `templates/proj_templates` directory in the AgentStack repo for bundled templates). +- A built-in AgentStack template (see the `templates` directory in the AgentStack repo for bundled templates). - A template file from the internet; pass the full https URL of the template. - A local template file; pass an absolute or relative path. diff --git a/docs/contributing/project-structure.mdx b/docs/contributing/project-structure.mdx index af2c65b8..1de36feb 100644 --- a/docs/contributing/project-structure.mdx +++ b/docs/contributing/project-structure.mdx @@ -234,10 +234,6 @@ which adheres to a common pattern or exporting your project to share. Templates are versioned, and each previous version provides a method to convert it's content to the current version. -> TODO: Templates are currently identified as `proj_templates` since they conflict -with the templates used by `generation`. Move existing templates to be part of -the generation package. - ### `TemplateConfig.from_user_input(identifier: str)` `` Returns a `TemplateConfig` object for either a URL, file path, or builtin template name. diff --git a/docs/templates/content_creator.mdx b/docs/templates/content_creator.mdx index 524b3271..b5d4678a 100644 --- a/docs/templates/content_creator.mdx +++ b/docs/templates/content_creator.mdx @@ -3,4 +3,4 @@ title: 'Content Creator' description: 'Research a topic and create content on it' --- -[View Template](https://github.com/AgentOps-AI/AgentStack/blob/main/agentstack/templates/proj_templates/content_creator.json) \ No newline at end of file +[View Template](https://github.com/AgentOps-AI/AgentStack/blob/main/agentstack/templates/content_creator.json) \ No newline at end of file diff --git a/docs/templates/researcher.mdx b/docs/templates/researcher.mdx index bd12ecca..3e989b85 100644 --- a/docs/templates/researcher.mdx +++ b/docs/templates/researcher.mdx @@ -3,7 +3,7 @@ title: 'Researcher' description: 'Research and report result from a query' --- -[View Template](https://github.com/AgentOps-AI/AgentStack/blob/main/agentstack/templates/proj_templates/research.json) +[View Template](https://github.com/AgentOps-AI/AgentStack/blob/main/agentstack/templates/research.json) ```bash agentstack init --template=research diff --git a/docs/templates/system_analyzer.mdx b/docs/templates/system_analyzer.mdx index 6d47e9be..303ddcc5 100644 --- a/docs/templates/system_analyzer.mdx +++ b/docs/templates/system_analyzer.mdx @@ -3,7 +3,7 @@ title: 'System Analyzer' description: 'Inspect a project directory and improve it' --- -[View Template](https://github.com/AgentOps-AI/AgentStack/blob/main/agentstack/templates/proj_templates/system_analyzer.json) +[View Template](https://github.com/AgentOps-AI/AgentStack/blob/main/agentstack/templates/system_analyzer.json) ```bash agentstack init --template=system_analyzer diff --git a/pyproject.toml b/pyproject.toml index b11c07c3..e8a17589 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,9 +56,12 @@ langgraph = [ openai_swarm = [ "agentstack-openai-swarm>=0.0.1" ] +llamaindex = [ + "llama-index-core>=0.12.16" +] [tool.setuptools.package-data] -agentstack = ["templates/**/*"] +agentstack = ["frameworks/templates/**/*"] [project.scripts] @@ -75,7 +78,7 @@ exclude = [ "build", "dist", "*.egg-info", - "agentstack/templates/", + "agentstack/frameworks/templates/", "examples" ] line-length = 110 @@ -85,7 +88,7 @@ quote-style = "preserve" [tool.mypy] exclude = [ - "templates/.*" # cookiecutter paths are not compatible + "frameworks/templates/.*" # cookiecutter paths are not compatible ] allow_untyped_defs = true disable_error_code = ["var-annotated", "import-untyped"] diff --git a/tests/fixtures/frameworks/llamaindex/entrypoint_max.py b/tests/fixtures/frameworks/llamaindex/entrypoint_max.py new file mode 100644 index 00000000..552559aa --- /dev/null +++ b/tests/fixtures/frameworks/llamaindex/entrypoint_max.py @@ -0,0 +1,81 @@ +import asyncio +from llama_index.core.llms import ChatMessage +from llama_index.core.agent.workflow import ( + FunctionAgent, + AgentWorkflow, + AgentOutput, + ToolCallResult, +) +from llama_index.llms.openai import OpenAI + +import agentstack + + +class LlamaindexStack: + def _format_history(self, history: list[ChatMessage]) -> str: + # ideally we would pass these directly to `chat_history`, but passing + # messages directly overrides the system prompt. this allows us to + # pass them as a string to `user_msg`. + return "\n\n".join([f"{msg.role}: {msg.content}" for msg in history]) + + @agentstack.task + def task_name(self) -> ChatMessage: + task_config = agentstack.get_task('task_name') + return ChatMessage(role="user", content=task_config.prompt) + + @agentstack.task + def task_name_two(self) -> ChatMessage: + task_config = agentstack.get_task('task_name_two') + return ChatMessage(role="user", content=task_config.prompt) + + @agentstack.agent + def agent_name(self) -> FunctionAgent: + agent_config = agentstack.get_agent('agent_name') + llm = OpenAI( + model=agent_config.model, + ) + return FunctionAgent( + name=agent_config.name, + description=agent_config.role, + system_prompt=agent_config.prompt, + llm=llm, + tools=[], + ) + + @agentstack.agent + def second_agent_name(self) -> FunctionAgent: + agent_config = agentstack.get_agent('second_agent_name') + llm = OpenAI( + model=agent_config.model, + ) + return FunctionAgent( + name=agent_config.name, + description=agent_config.role, + system_prompt=agent_config.prompt, + llm=llm, + tools=[], + ) + + async def run(self, inputs: dict[str, str]): + # TODO interpolate inputs into prompts + history: list[ChatMessage] = [] + for task_config in agentstack.get_all_tasks(): + task = getattr(self, task_config.name) + agent = getattr(self, task_config.agent) + workflow = AgentWorkflow( + agents=[agent(), ], + ) + history.append(task()) + handler = workflow.run( + user_msg=self._format_history(history), + # chat_history=history, + ) + + async for event in handler.stream_events(): + if isinstance(event, AgentOutput) and event.response.content: + agentstack.log.notify(event.current_agent_name) + agentstack.log.info(event.response.content) + history.append(ChatMessage(role="assistant", content=event.response.content)) + elif isinstance(event, ToolCallResult): + agentstack.log.notify(f"tool: {event.tool_name}") + agentstack.log.info(event.tool_output) \ No newline at end of file diff --git a/tests/fixtures/frameworks/llamaindex/entrypoint_min.py b/tests/fixtures/frameworks/llamaindex/entrypoint_min.py new file mode 100644 index 00000000..99691914 --- /dev/null +++ b/tests/fixtures/frameworks/llamaindex/entrypoint_min.py @@ -0,0 +1,42 @@ +import asyncio +from llama_index.core.llms import ChatMessage +from llama_index.core.agent.workflow import ( + FunctionAgent, + AgentWorkflow, + AgentOutput, + ToolCallResult, +) + +import agentstack + + +class LlamaindexStack: + def _format_history(self, history: list[ChatMessage]) -> str: + # ideally we would pass these directly to `chat_history`, but passing + # messages directly overrides the system prompt. this allows us to + # pass them as a string to `user_msg`. + return "\n\n".join([f"{msg.role}: {msg.content}" for msg in history]) + + async def run(self, inputs: dict[str, str]): + # TODO interpolate inputs into prompts + history: list[ChatMessage] = [] + for task_config in agentstack.get_all_tasks(): + task = getattr(self, task_config.name) + agent = getattr(self, task_config.agent) + workflow = AgentWorkflow( + agents=[agent(), ], + ) + history.append(task()) + handler = workflow.run( + user_msg=self._format_history(history), + # chat_history=history, + ) + + async for event in handler.stream_events(): + if isinstance(event, AgentOutput) and event.response.content: + agentstack.log.notify(event.current_agent_name) + agentstack.log.info(event.response.content) + history.append(ChatMessage(role="assistant", content=event.response.content)) + elif isinstance(event, ToolCallResult): + agentstack.log.notify(f"tool: {event.tool_name}") + agentstack.log.info(event.tool_output) \ No newline at end of file diff --git a/tests/test_cli_init.py b/tests/test_cli_init.py index 9b2e6b53..17eefb33 100644 --- a/tests/test_cli_init.py +++ b/tests/test_cli_init.py @@ -4,7 +4,7 @@ from pathlib import Path import shutil from cli_test_utils import run_cli -from agentstack.proj_templates import get_all_templates +from agentstack.templates import get_all_templates BASE_PATH = Path(__file__).parent diff --git a/tests/test_cli_templates.py b/tests/test_cli_templates.py index 86a0220b..0dbcdbc5 100644 --- a/tests/test_cli_templates.py +++ b/tests/test_cli_templates.py @@ -4,7 +4,7 @@ from parameterized import parameterized from pathlib import Path import shutil -from agentstack.proj_templates import get_all_template_names +from agentstack.templates import get_all_template_names from cli_test_utils import run_cli BASE_PATH = Path(__file__).parent @@ -22,7 +22,8 @@ def tearDown(self): @parameterized.expand([(x,) for x in get_all_template_names()]) def test_init_command_for_template(self, template_name): """Test the 'init' command to create a project directory with a template.""" - result = run_cli('init', 'test_project', '--template', template_name) + # initialize templates using the current framework regardless of their setting + result = run_cli('init', 'test_project', '--template', template_name, '--framework', self.framework) self.assertEqual(result.returncode, 0) self.assertTrue((self.project_dir / 'test_project').exists()) diff --git a/tests/test_generation_asttools.py b/tests/test_generation_asttools.py new file mode 100644 index 00000000..8e3397fc --- /dev/null +++ b/tests/test_generation_asttools.py @@ -0,0 +1,164 @@ +import os +import unittest +from pathlib import Path +import shutil +from agentstack.generation import asttools +import ast + +BASE_PATH = Path(__file__).parent + +class TestGenerationASTTools(unittest.TestCase): + def setUp(self): + self.project_dir = BASE_PATH / 'tmp' / 'asttools' + os.makedirs(self.project_dir, exist_ok=True) + + def tearDown(self): + shutil.rmtree(self.project_dir) + + def test_edit_node_range(self): + # Create a sample Python file + sample_code = """ +def hello(): + print("Hello, World!") + +def goodbye(): + print("Goodbye, World!") +""" + file_path = self.project_dir / "sample.py" + with open(file_path, "w") as f: + f.write(sample_code) + + # Use the File class to manipulate the file + with asttools.File(file_path) as f: + # Find the range of the hello function + hello_func = next(node for node in f.tree.body if isinstance(node, ast.FunctionDef) and node.name == "hello") + start, end = f.get_node_range(hello_func) + + # Replace the hello function with a new implementation + new_func = """def hello(): + print("Hello, Universe!")""" + f.edit_node_range(start, end, new_func) + + # Read the modified file and check its contents + with open(file_path, "r") as f: + modified_code = f.read() + + expected_code = """ +def hello(): + print("Hello, Universe!") + +def goodbye(): + print("Goodbye, World!") +""" + self.assertEqual(modified_code.strip(), expected_code.strip()) + + def test_render_node(self): + file_path = self.project_dir / "sample.py" + file_path.touch() + file = asttools.File(file_path) + + # Test rendering a string + string_input = "print('Hello, World!')" + self.assertEqual(file._render_node(string_input), string_input) + + # Test rendering an AST node + ast_node = ast.Expr(value=ast.Call( + func=ast.Name(id='print', ctx=ast.Load()), + args=[ast.Constant(value='Hello, AST!')], + keywords=[] + )) + expected_output = "print('Hello, AST!')" + self.assertEqual(file._render_node(ast_node), expected_output) + + # Test rendering a more complex AST node + complex_ast_node = ast.FunctionDef( + name='greet', + args=ast.arguments( + posonlyargs=[], + args=[ast.arg(arg='name')], + kwonlyargs=[], + kw_defaults=[], + defaults=[] + ), + body=[ + ast.Return( + value=ast.BinOp( + left=ast.Constant(value='Hello, '), + op=ast.Add(), + right=ast.Name(id='name', ctx=ast.Load()) + ) + ) + ], + decorator_list=[] + ) + expected_complex_output = "def greet(name):\n return 'Hello, ' + name" + self.assertEqual(file._render_node(complex_ast_node).strip(), expected_complex_output) + + def test_insert_method(self): + file_path = self.project_dir / "sample.py" + with open(file_path, "w") as f: + f.write("""class TestClass: + def existing(self): + pass""") + + file = asttools.File(file_path) + + # Test inserting method when there's no newline at the end + new_method = """ def method1(self): + pass""" + class_node = asttools.find_class(file.tree, "TestClass") + method_node = asttools.find_method_in_class(class_node, "existing") + start, end = file.get_node_range(method_node) + + file.insert_method(end, new_method) + self.assertEqual(file.source, """class TestClass: + def existing(self): + pass + + def method1(self): + pass + +""") + + # Test inserting method when there's already a newline at the end + new_method = """ def method2(self): + return True""" + class_node = asttools.find_class(file.tree, "TestClass") + method_node = asttools.find_method_in_class(class_node, "method1") + start, end = file.get_node_range(method_node) + + file.insert_method(end, new_method) + self.assertEqual(file.source, """class TestClass: + def existing(self): + pass + + def method1(self): + pass + + def method2(self): + return True + +""") + + # Test inserting method in the middle of existing methods + new_method = """ def method_middle(self): + print('middle')""" + class_node = asttools.find_class(file.tree, "TestClass") + method_node = asttools.find_method_in_class(class_node, "method1") + start, end = file.get_node_range(method_node) + + file.insert_method(end, new_method) + self.assertEqual(file.source, """class TestClass: + def existing(self): + pass + + def method1(self): + pass + + def method_middle(self): + print('middle') + + def method2(self): + return True + +""") diff --git a/tests/test_providers.py b/tests/test_providers.py new file mode 100644 index 00000000..42d6e41a --- /dev/null +++ b/tests/test_providers.py @@ -0,0 +1,30 @@ +import unittest +from agentstack.exceptions import ValidationError +from agentstack.providers import ( + parse_provider_model, +) + + +class ProvidersTest(unittest.TestCase): + def test_parse_provider_model(self): + cases = [ + "deepseek/deepseek-reasoner", + "openrouter/deepseek/deepseek-r1", + "openai/gpt-4o", + "anthropic/claude-3-opus", + "provider/model", + ] + expected = [ + ("deepseek", "deepseek-reasoner"), + ("openrouter/deepseek", "deepseek-r1"), + ("openai", "gpt-4o"), + ("anthropic", "claude-3-opus"), + ("provider", "model"), + ] + for case, expect in zip(cases, expected): + self.assertEqual(parse_provider_model(case), expect) + + def test_invalid_provider_model(self): + with self.assertRaises(ValidationError): + parse_provider_model("invalid_provider_model") + diff --git a/tests/test_templates_config.py b/tests/test_templates_config.py index bb0d715a..8c99848f 100644 --- a/tests/test_templates_config.py +++ b/tests/test_templates_config.py @@ -6,7 +6,7 @@ from unittest.mock import patch from parameterized import parameterized from agentstack.exceptions import ValidationError -from agentstack.proj_templates import ( +from agentstack.templates import ( CURRENT_VERSION, TemplateConfig, get_all_template_names, @@ -130,7 +130,7 @@ def test_from_url_invalid_url(self): with self.assertRaises(ValidationError) as context: TemplateConfig.from_url(invalid_url) - @patch('agentstack.proj_templates.requests.get') + @patch('agentstack.templates.requests.get') def test_from_url_non_200_response(self, mock_get): mock_response = mock_get.return_value mock_response.status_code = 404 @@ -192,7 +192,7 @@ def test_from_file_invalid_json(self): finally: os.unlink(temp_file) - @patch('agentstack.proj_templates.requests.get') + @patch('agentstack.templates.requests.get') def test_from_url_invalid_json(self, mock_get): mock_response = mock_get.return_value mock_response.status_code = 200 @@ -215,7 +215,7 @@ def test_get_all_template_paths(self): for path in get_all_template_paths(): self.assertIsInstance(path, Path) - @patch('agentstack.proj_templates.get_package_path') + @patch('agentstack.templates.get_package_path') @patch('pathlib.Path.iterdir') def test_get_all_template_paths_no_json_files(self, mock_iterdir, mock_get_package_path): mock_get_package_path.return_value = Path('/mock/path') diff --git a/tox.ini b/tox.ini index 85ea3dfc..4d2d016a 100644 --- a/tox.ini +++ b/tox.ini @@ -9,9 +9,9 @@ # codecov is configured to run on all frameworks and then be combined at the end. [tox] -envlist = py{310,311,312}-{crewai,langgraph,openai_swarm} +envlist = py{310,311,312}-{crewai,langgraph,openai_swarm,llamaindex} labels = - quick = py312-{crewai,langgraph,openai_swarm},report + quick = py312-{crewai,langgraph,openai_swarm,llamaindex},report [gh-actions] # converts python versions to tox envlist values for github actions @@ -26,6 +26,7 @@ extras = crewai: crewai # installs agentstack[crewai] langgraph: langgraph openai_swarm: openai_swarm + llamaindex: llamaindex deps = pytest parameterized @@ -42,6 +43,7 @@ setenv = crewai: TEST_FRAMEWORK = crewai langgraph: TEST_FRAMEWORK = langgraph openai_swarm: TEST_FRAMEWORK = openai_swarm + llamaindex: TEST_FRAMEWORK = llamaindex [testenv:report] deps = coverage