-
Notifications
You must be signed in to change notification settings - Fork 192
File abstractions for project config and env #71
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d526266
Merge branch 'issue-57' into file-abstractions
tcdent 7d0eba9
Abstract interactions with agentstack config file and env file into w…
tcdent 8851c38
Merge branch 'main' into file-abstractions
tcdent 0003eb5
Use ConfigFile object to verify existence of agentstack.json fie in p…
tcdent d66f78b
typo, typing
tcdent d264c04
Merge branch 'main' into file-abstractions
bboynton97 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| from .agent_generation import generate_agent | ||
| from .task_generation import generate_task | ||
| from .tool_generation import add_tool, remove_tool | ||
| from .files import ConfigFile, EnvFile, CONFIG_FILENAME |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| from typing import Optional, Union | ||
| import os | ||
| import json | ||
| from pathlib import Path | ||
| from pydantic import BaseModel | ||
|
|
||
|
|
||
| DEFAULT_FRAMEWORK = "crewai" | ||
| CONFIG_FILENAME = "agentstack.json" | ||
| ENV_FILEMANE = ".env" | ||
|
|
||
| class ConfigFile(BaseModel): | ||
| """ | ||
| Interface for interacting with the agentstack.json file inside a project directory. | ||
| Handles both data validation and file I/O. | ||
|
|
||
| `path` is the directory where the agentstack.json file is located. Defaults | ||
| to the current working directory. | ||
|
|
||
| Use it as a context manager to make and save edits: | ||
| ```python | ||
| with ConfigFile() as config: | ||
| config.tools.append('tool_name') | ||
| ``` | ||
|
|
||
| Config Schema | ||
| ------------- | ||
| framework: str | ||
| The framework used in the project. Defaults to 'crewai'. | ||
| tools: list[str] | ||
| A list of tools that are currently installed in the project. | ||
| telemetry_opt_out: Optional[bool] | ||
| Whether the user has opted out of telemetry. | ||
| """ | ||
| framework: Optional[str] = DEFAULT_FRAMEWORK | ||
| tools: list[str] = [] | ||
| telemetry_opt_out: Optional[bool] = None | ||
|
|
||
| def __init__(self, path: Union[str, Path, None] = None): | ||
| path = Path(path) if path else Path.cwd() | ||
| if os.path.exists(path / CONFIG_FILENAME): | ||
| with open(path / CONFIG_FILENAME, 'r') as f: | ||
| super().__init__(**json.loads(f.read())) | ||
| else: | ||
| raise FileNotFoundError(f"File {path / CONFIG_FILENAME} does not exist.") | ||
| self._path = path # attribute needs to be set after init | ||
|
|
||
| def model_dump(self, *args, **kwargs) -> dict: | ||
| # Ignore None values | ||
| dump = super().model_dump(*args, **kwargs) | ||
| return {key: value for key, value in dump.items() if value is not None} | ||
|
|
||
| def write(self): | ||
| with open(self._path / CONFIG_FILENAME, 'w') as f: | ||
| f.write(json.dumps(self.model_dump(), indent=4)) | ||
|
|
||
| def __enter__(self) -> 'ConfigFile': return self | ||
| def __exit__(self, *args): self.write() | ||
|
|
||
|
|
||
| class EnvFile: | ||
| """ | ||
| Interface for interacting with the .env file inside a project directory. | ||
| Unlike the ConfigFile, we do not re-write the entire file on every change, | ||
| and instead just append new lines to the end of the file. This preseres | ||
| comments and other formatting that the user may have added and prevents | ||
| opportunities for data loss. | ||
|
|
||
| `path` is the directory where the .env file is located. Defaults to the | ||
| current working directory. | ||
| `filename` is the name of the .env file, defaults to '.env'. | ||
|
|
||
| Use it as a context manager to make and save edits: | ||
| ```python | ||
| with EnvFile() as env: | ||
| env.append_if_new('ENV_VAR', 'value') | ||
| ``` | ||
| """ | ||
| variables: dict[str, str] | ||
|
|
||
| def __init__(self, path: Union[str, Path, None] = None, filename: str = ENV_FILEMANE): | ||
| self._path = Path(path) if path else Path.cwd() | ||
| self._filename = filename | ||
| self.read() | ||
|
|
||
| def __getitem__(self, key): | ||
| return self.variables[key] | ||
|
|
||
| def __setitem__(self, key, value): | ||
| if key in self.variables: | ||
| raise ValueError("EnvFile does not allow overwriting values.") | ||
| self.append_if_new(key, value) | ||
|
|
||
| def __contains__(self, key) -> bool: | ||
| return key in self.variables | ||
|
|
||
| def append_if_new(self, key, value): | ||
| if not key in self.variables: | ||
| self.variables[key] = value | ||
| self._new_variables[key] = value | ||
|
|
||
| def read(self): | ||
| def parse_line(line): | ||
| key, value = line.split('=') | ||
| return key.strip(), value.strip() | ||
|
|
||
| if os.path.exists(self._path / self._filename): | ||
| with open(self._path / self._filename, 'r') as f: | ||
| self.variables = dict([parse_line(line) for line in f.readlines() if '=' in line]) | ||
| else: | ||
| self.variables = {} | ||
| self._new_variables = {} | ||
|
|
||
| def write(self): | ||
| with open(self._path / self._filename, 'a') as f: | ||
| for key, value in self._new_variables.items(): | ||
| f.write(f"\n{key}={value}") | ||
|
|
||
| def __enter__(self) -> 'EnvFile': return self | ||
| def __exit__(self, *args): self.write() | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
|
|
||
| ENV_VAR1=value1 | ||
| ENV_VAR2=value2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| { | ||
| "framework": "crewai", | ||
| "tools": ["tool1", "tool2"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import os, sys | ||
| import unittest | ||
| import importlib.resources | ||
| from pathlib import Path | ||
| import shutil | ||
| from agentstack.generation.files import ConfigFile, EnvFile | ||
| from agentstack.utils import verify_agentstack_project, get_framework, get_telemetry_opt_out | ||
|
|
||
| BASE_PATH = Path(__file__).parent | ||
|
|
||
| class GenerationFilesTest(unittest.TestCase): | ||
| def test_read_config(self): | ||
| config = ConfigFile(BASE_PATH / "fixtures") # + agentstack.json | ||
| assert config.framework == "crewai" | ||
| assert config.tools == ["tool1", "tool2"] | ||
| assert config.telemetry_opt_out is None | ||
|
|
||
| def test_write_config(self): | ||
| try: | ||
| os.makedirs(BASE_PATH/"tmp", exist_ok=True) | ||
| shutil.copy(BASE_PATH/"fixtures/agentstack.json", | ||
| BASE_PATH/"tmp/agentstack.json") | ||
|
|
||
| with ConfigFile(BASE_PATH/"tmp") as config: | ||
| config.framework = "crewai" | ||
| config.tools = ["tool1", "tool2"] | ||
| config.telemetry_opt_out = True | ||
|
|
||
| tmp_data = open(BASE_PATH/"tmp/agentstack.json").read() | ||
| assert tmp_data == """{ | ||
| "framework": "crewai", | ||
| "tools": [ | ||
| "tool1", | ||
| "tool2" | ||
| ], | ||
| "telemetry_opt_out": true | ||
| }""" | ||
| except Exception as e: | ||
| raise e | ||
| finally: | ||
| os.remove(BASE_PATH / "tmp/agentstack.json") | ||
| #os.rmdir(BASE_PATH / "tmp") | ||
|
|
||
| def test_read_missing_config(self): | ||
| with self.assertRaises(FileNotFoundError) as context: | ||
| config = ConfigFile(BASE_PATH / "missing") | ||
|
|
||
| def test_verify_agentstack_project_valid(self): | ||
| verify_agentstack_project(BASE_PATH / "fixtures") | ||
|
|
||
| def test_verify_agentstack_project_invalid(self): | ||
| with self.assertRaises(SystemExit) as context: | ||
| verify_agentstack_project(BASE_PATH / "missing") | ||
|
|
||
| def test_get_framework(self): | ||
| assert get_framework(BASE_PATH / "fixtures") == "crewai" | ||
| with self.assertRaises(SystemExit) as context: | ||
| get_framework(BASE_PATH / "missing") | ||
|
|
||
| def test_get_telemetry_opt_out(self): | ||
| assert get_telemetry_opt_out(BASE_PATH / "fixtures") is False | ||
| with self.assertRaises(SystemExit) as context: | ||
| get_telemetry_opt_out(BASE_PATH / "missing") | ||
|
|
||
| def test_read_env(self): | ||
| env = EnvFile(BASE_PATH / "fixtures") | ||
| assert env.variables == {"ENV_VAR1": "value1", "ENV_VAR2": "value2"} | ||
| assert env["ENV_VAR1"] == "value1" | ||
| assert env["ENV_VAR2"] == "value2" | ||
| with self.assertRaises(KeyError) as context: | ||
| env["ENV_VAR3"] | ||
|
|
||
| def test_write_env(self): | ||
| try: | ||
| os.makedirs(BASE_PATH/"tmp", exist_ok=True) | ||
| shutil.copy(BASE_PATH/"fixtures/.env", | ||
| BASE_PATH/"tmp/.env") | ||
|
|
||
| with EnvFile(BASE_PATH/"tmp") as env: | ||
| env.append_if_new("ENV_VAR1", "value100") # Should not be updated | ||
| env.append_if_new("ENV_VAR100", "value2") # Should be added | ||
|
|
||
| tmp_data = open(BASE_PATH/"tmp/.env").read() | ||
| assert tmp_data == """\nENV_VAR1=value1\nENV_VAR2=value2\nENV_VAR100=value2""" | ||
| except Exception as e: | ||
| raise e | ||
| finally: | ||
| os.remove(BASE_PATH / "tmp/.env") | ||
| #os.rmdir(BASE_PATH / "tmp") | ||
|
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.