feat: agent files
This commit is contained in:
0
__init__.py
Normal file
0
__init__.py
Normal file
0
core/__init__.py
Normal file
0
core/__init__.py
Normal file
BIN
core/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
core/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
0
core/agent/__init__.py
Normal file
0
core/agent/__init__.py
Normal file
BIN
core/agent/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
core/agent/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
core/agent/__pycache__/agent.cpython-312.pyc
Normal file
BIN
core/agent/__pycache__/agent.cpython-312.pyc
Normal file
Binary file not shown.
32
core/agent/agent.py
Normal file
32
core/agent/agent.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
from langchain_core.messages import HumanMessage, AIMessage
|
||||||
|
from langgraph.graph import StateGraph, MessagesState, START, END
|
||||||
|
from ..backend import llm
|
||||||
|
|
||||||
|
def call_llama_server(state: MessagesState):
|
||||||
|
"""Call the local llama-server with the configured model using LangChain."""
|
||||||
|
# Get the last user message
|
||||||
|
messages = state["messages"]
|
||||||
|
if not messages:
|
||||||
|
return {"messages": [AIMessage(content="No message provided")]}
|
||||||
|
|
||||||
|
# Get the content of the last message
|
||||||
|
last_message = messages[-1]
|
||||||
|
user_content = last_message.content
|
||||||
|
|
||||||
|
# Invoke the LLM with the user message
|
||||||
|
response = llm.invoke(user_content)
|
||||||
|
|
||||||
|
return {"messages": [response]}
|
||||||
|
|
||||||
|
|
||||||
|
def create_agent_graph():
|
||||||
|
"""Create a simple agent graph that processes messages and calls the llama server."""
|
||||||
|
|
||||||
|
# Build the LangGraph workflow
|
||||||
|
graph = StateGraph(MessagesState)
|
||||||
|
graph.add_node(call_llama_server)
|
||||||
|
graph.add_edge(START, "call_llama_server")
|
||||||
|
graph.add_edge("call_llama_server", END)
|
||||||
|
graph = graph.compile()
|
||||||
|
|
||||||
|
return graph
|
||||||
14
core/backend/__init__.py
Normal file
14
core/backend/__init__.py
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from langchain_openai import ChatOpenAI
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# Get configuration from environment variables
|
||||||
|
LLAMA_SERVER_URL = os.getenv("LLAMA_SERVER_URL", "http://127.0.0.1:8013")
|
||||||
|
LLAMA_MODEL_NAME = os.getenv("LLAMA_MODEL_NAME", "ggml-org_gpt-oss-20b-GGUF_gpt-oss-20b-mxfp4.gguf")
|
||||||
|
|
||||||
|
llm = None
|
||||||
|
if "gpt-oss-20b" in LLAMA_MODEL_NAME:
|
||||||
|
from core.backend.llama_gpt_oss import get_llama_oss_20b_llm
|
||||||
|
llm = get_llama_oss_20b_llm(LLAMA_SERVER_URL, LLAMA_MODEL_NAME)
|
||||||
BIN
core/backend/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
core/backend/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
core/backend/__pycache__/llama_gpt_oss.cpython-312.pyc
Normal file
BIN
core/backend/__pycache__/llama_gpt_oss.cpython-312.pyc
Normal file
Binary file not shown.
9
core/backend/llama_gpt_oss.py
Normal file
9
core/backend/llama_gpt_oss.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
from langchain_openai import ChatOpenAI
|
||||||
|
|
||||||
|
def get_llama_oss_20b_llm(server_url, model_name):
|
||||||
|
"""Initialize and return a ChatOpenAI instance configured for llama-oss-20b."""
|
||||||
|
return ChatOpenAI(
|
||||||
|
base_url=f"{server_url}/v1",
|
||||||
|
api_key="not-needed",
|
||||||
|
model=model_name
|
||||||
|
)
|
||||||
371
core/tools/file_operations.py
Normal file
371
core/tools/file_operations.py
Normal file
@@ -0,0 +1,371 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from typing import Optional, List, Dict, Any
|
||||||
|
from langchain import tools
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("read_file")
|
||||||
|
def read_file(file_path: str, start_line: Optional[int] = None, end_line: Optional[int] = None) -> str:
|
||||||
|
"""
|
||||||
|
Reads the content of a file and returns it as a string.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path: Path to the file to read
|
||||||
|
start_line: Starting line number (1-based, inclusive). If None, starts from the beginning.
|
||||||
|
end_line: Ending line number (1-based, inclusive). If None, reads to the end.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The content of the file as a string
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r') as file:
|
||||||
|
lines = file.readlines()
|
||||||
|
|
||||||
|
# Convert 1-based to 0-based indexing
|
||||||
|
if start_line is not None:
|
||||||
|
start_idx = max(0, start_line - 1)
|
||||||
|
else:
|
||||||
|
start_idx = 0
|
||||||
|
|
||||||
|
if end_line is not None:
|
||||||
|
end_idx = end_line # end_line is already correct for slicing (1-based inclusive -> 0-based exclusive)
|
||||||
|
else:
|
||||||
|
end_idx = len(lines)
|
||||||
|
|
||||||
|
selected_lines = lines[start_idx:end_idx]
|
||||||
|
return ''.join(selected_lines)
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise FileNotFoundError(f"File not found: {file_path}")
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied reading: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error reading file '{file_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("write_file")
|
||||||
|
def write_file(file_path: str, content: str, overwrite: bool = False) -> str:
|
||||||
|
"""
|
||||||
|
Writes the given content to a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path: Path to the file to write
|
||||||
|
content: Content to write to the file
|
||||||
|
overwrite: If True, overwrites existing file. If False, raises error if file exists.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Ensure directory exists
|
||||||
|
dir_path = os.path.dirname(file_path)
|
||||||
|
if dir_path and not os.path.exists(dir_path):
|
||||||
|
os.makedirs(dir_path, exist_ok=True)
|
||||||
|
|
||||||
|
if os.path.exists(file_path) and not overwrite:
|
||||||
|
raise FileExistsError(
|
||||||
|
f"File '{file_path}' already exists. Set overwrite=True to replace it, "
|
||||||
|
"or use 'replace_in_file' to modify content."
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(file_path, 'w') as file:
|
||||||
|
file.write(content)
|
||||||
|
|
||||||
|
return f"Successfully wrote to file: {file_path}"
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied writing to: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error writing file '{file_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("replace_in_file")
|
||||||
|
def replace_in_file(file_path: str, old_content: str, new_content: str, count: int = -1) -> str:
|
||||||
|
"""
|
||||||
|
Replaces occurrences of old_content with new_content in a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path: Path to the file to modify
|
||||||
|
old_content: Content to replace
|
||||||
|
new_content: Content to replace with
|
||||||
|
count: Maximum number of occurrences to replace. -1 means all occurrences.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message with replacement count
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
content = read_file(file_path)
|
||||||
|
new_content_str, replacement_count = content.replace(old_content, new_content, count), content.count(old_content) if count == -1 else min(count, content.count(old_content))
|
||||||
|
|
||||||
|
with open(file_path, 'w') as file:
|
||||||
|
file.write(new_content_str)
|
||||||
|
|
||||||
|
return f"Successfully replaced {replacement_count} occurrence(s) in '{file_path}'"
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise FileNotFoundError(f"File not found: {file_path}")
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied modifying: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error replacing content in '{file_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("delete_in_file")
|
||||||
|
def delete_in_file(file_path: str, content_to_delete: str, count: int = -1) -> str:
|
||||||
|
"""
|
||||||
|
Deletes occurrences of content_to_delete from a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path: Path to the file to modify
|
||||||
|
content_to_delete: Content to delete
|
||||||
|
count: Maximum number of occurrences to delete. -1 means all occurrences.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message with deletion count
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
content = read_file(file_path)
|
||||||
|
new_content_str = content.replace(content_to_delete, '', count)
|
||||||
|
deletion_count = content.count(content_to_delete) if count == -1 else min(count, content.count(content_to_delete))
|
||||||
|
|
||||||
|
with open(file_path, 'w') as file:
|
||||||
|
file.write(new_content_str)
|
||||||
|
|
||||||
|
return f"Successfully deleted {deletion_count} occurrence(s) from '{file_path}'"
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise FileNotFoundError(f"File not found: {file_path}")
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied modifying: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error deleting content from '{file_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("delete_file")
|
||||||
|
def delete_file(file_path: str) -> str:
|
||||||
|
"""
|
||||||
|
Deletes a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path: Path to the file to delete
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not os.path.exists(file_path):
|
||||||
|
raise FileNotFoundError(f"File not found: {file_path}")
|
||||||
|
os.remove(file_path)
|
||||||
|
return f"Successfully deleted file: {file_path}"
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied deleting: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error deleting file '{file_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("copy_file")
|
||||||
|
def copy_file(source_path: str, destination_path: str, overwrite: bool = False) -> str:
|
||||||
|
"""
|
||||||
|
Copies a file from source_path to destination_path.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_path: Path to the source file
|
||||||
|
destination_path: Path to the destination
|
||||||
|
overwrite: If True, overwrites existing destination file
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not os.path.exists(source_path):
|
||||||
|
raise FileNotFoundError(f"Source file not found: {source_path}")
|
||||||
|
|
||||||
|
if os.path.exists(destination_path) and not overwrite:
|
||||||
|
raise FileExistsError(
|
||||||
|
f"Destination '{destination_path}' already exists. Set overwrite=True to replace it."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ensure destination directory exists
|
||||||
|
dir_path = os.path.dirname(destination_path)
|
||||||
|
if dir_path and not os.path.exists(dir_path):
|
||||||
|
os.makedirs(dir_path, exist_ok=True)
|
||||||
|
|
||||||
|
shutil.copy(source_path, destination_path)
|
||||||
|
return f"Successfully copied '{source_path}' to '{destination_path}'"
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied during copy operation")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error copying file: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("move_file")
|
||||||
|
def move_file(source_path: str, destination_path: str, overwrite: bool = False) -> str:
|
||||||
|
"""
|
||||||
|
Moves a file from source_path to destination_path.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_path: Path to the source file
|
||||||
|
destination_path: Path to the destination
|
||||||
|
overwrite: If True, overwrites existing destination file
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not os.path.exists(source_path):
|
||||||
|
raise FileNotFoundError(f"Source file not found: {source_path}")
|
||||||
|
|
||||||
|
if os.path.exists(destination_path) and not overwrite:
|
||||||
|
raise FileExistsError(
|
||||||
|
f"Destination '{destination_path}' already exists. Set overwrite=True to replace it."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ensure destination directory exists
|
||||||
|
dir_path = os.path.dirname(destination_path)
|
||||||
|
if dir_path and not os.path.exists(dir_path):
|
||||||
|
os.makedirs(dir_path, exist_ok=True)
|
||||||
|
|
||||||
|
shutil.move(source_path, destination_path)
|
||||||
|
return f"Successfully moved '{source_path}' to '{destination_path}'"
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied during move operation")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error moving file: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("create_directory")
|
||||||
|
def create_directory(directory_path: str, parents: bool = True) -> str:
|
||||||
|
"""
|
||||||
|
Creates a new directory at the specified path.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
directory_path: Path to the directory to create
|
||||||
|
parents: If True, creates parent directories as needed
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
os.makedirs(directory_path, exist_ok=parents)
|
||||||
|
return f"Successfully created directory: {directory_path}"
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied creating directory: {directory_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error creating directory '{directory_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("delete_directory")
|
||||||
|
def delete_directory(directory_path: str, recursive: bool = True) -> str:
|
||||||
|
"""
|
||||||
|
Deletes a directory at the specified path.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
directory_path: Path to the directory to delete
|
||||||
|
recursive: If True, deletes directory and all contents
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Success message
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not os.path.exists(directory_path):
|
||||||
|
raise FileNotFoundError(f"Directory not found: {directory_path}")
|
||||||
|
if not os.path.isdir(directory_path):
|
||||||
|
raise NotADirectoryError(f"Path is not a directory: {directory_path}")
|
||||||
|
|
||||||
|
shutil.rmtree(directory_path)
|
||||||
|
return f"Successfully deleted directory: {directory_path}"
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied deleting directory: {directory_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error deleting directory '{directory_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("list_directory")
|
||||||
|
def list_directory(directory_path: str, level: int = 1, recursive: bool = False) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Lists the contents of a directory.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
directory_path: Path to the directory to list
|
||||||
|
level: Depth level for recursive listing (1 = immediate children only)
|
||||||
|
recursive: If True, lists all contents recursively
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of dictionaries containing file/folder information with keys:
|
||||||
|
- 'name': Name of the item
|
||||||
|
- 'path': Full path of the item
|
||||||
|
- 'type': 'file' or 'directory'
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not os.path.exists(directory_path):
|
||||||
|
raise FileNotFoundError(f"Directory not found: {directory_path}")
|
||||||
|
if not os.path.isdir(directory_path):
|
||||||
|
raise NotADirectoryError(f"Path is not a directory: {directory_path}")
|
||||||
|
|
||||||
|
def get_directory_contents(path: str, current_level: int, max_level: int) -> List[Dict[str, Any]]:
|
||||||
|
contents = []
|
||||||
|
try:
|
||||||
|
for item in os.listdir(path):
|
||||||
|
item_path = os.path.join(path, item)
|
||||||
|
is_dir = os.path.isdir(item_path)
|
||||||
|
|
||||||
|
item_info = {
|
||||||
|
'name': item,
|
||||||
|
'path': item_path,
|
||||||
|
'type': 'directory' if is_dir else 'file'
|
||||||
|
}
|
||||||
|
contents.append(item_info)
|
||||||
|
|
||||||
|
# Recursively get contents if needed
|
||||||
|
if is_dir and current_level < max_level:
|
||||||
|
sub_contents = get_directory_contents(item_path, current_level + 1, max_level)
|
||||||
|
item_info['contents'] = sub_contents
|
||||||
|
|
||||||
|
except PermissionError:
|
||||||
|
item_info = {'name': path, 'path': path, 'type': 'directory', 'error': 'Permission denied'}
|
||||||
|
contents.append(item_info)
|
||||||
|
|
||||||
|
return contents
|
||||||
|
|
||||||
|
if recursive:
|
||||||
|
return get_directory_contents(directory_path, 1, level)
|
||||||
|
else:
|
||||||
|
return get_directory_contents(directory_path, 1, 1)
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied listing directory: {directory_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error listing directory '{directory_path}': {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
@tools.tool("get_file_info")
|
||||||
|
def get_file_info(file_path: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Gets information about a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path: Path to the file
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dictionary containing file information:
|
||||||
|
- 'name': File name
|
||||||
|
- 'path': Full path
|
||||||
|
- 'size': Size in bytes
|
||||||
|
- 'is_file': True if it's a file
|
||||||
|
- 'is_directory': True if it's a directory
|
||||||
|
- 'modified': Last modified timestamp
|
||||||
|
- 'created': Created timestamp
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not os.path.exists(file_path):
|
||||||
|
raise FileNotFoundError(f"File not found: {file_path}")
|
||||||
|
|
||||||
|
stat_info = os.stat(file_path)
|
||||||
|
return {
|
||||||
|
'name': os.path.basename(file_path),
|
||||||
|
'path': file_path,
|
||||||
|
'size': stat_info.st_size,
|
||||||
|
'is_file': os.path.isfile(file_path),
|
||||||
|
'is_directory': os.path.isdir(file_path),
|
||||||
|
'modified': stat_info.st_mtime,
|
||||||
|
'created': stat_info.st_ctime
|
||||||
|
}
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied getting info for: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Error getting file info for '{file_path}': {str(e)}")
|
||||||
13
main.py
Normal file
13
main.py
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
from core.agent.agent import create_agent_graph
|
||||||
|
from langchain_core.messages import HumanMessage, AIMessage
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Hello from oss-agent!")
|
||||||
|
graph = create_agent_graph()
|
||||||
|
graph.invoke({"messages": []})
|
||||||
|
# Invoke the graph with a test message
|
||||||
|
output = graph.invoke({"messages": [HumanMessage(content="hi!")]})
|
||||||
|
print("Agent response:", output)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
14
pyproject.toml
Normal file
14
pyproject.toml
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
[project]
|
||||||
|
name = "oss-agent"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Add your description here"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.12"
|
||||||
|
dependencies = [
|
||||||
|
"langchain>=1.2.12",
|
||||||
|
"langchain-community>=0.4.1",
|
||||||
|
"langchain-ollama>=1.0.1",
|
||||||
|
"langchain-openai>=0.3.0",
|
||||||
|
"langgraph>=1.1.3",
|
||||||
|
"python-dotenv>=1.0.0",
|
||||||
|
]
|
||||||
Reference in New Issue
Block a user