Skip to content

Commit

Permalink
chore: lazy importing
Browse files Browse the repository at this point in the history
  • Loading branch information
phil65 committed Feb 1, 2025
1 parent 3d35d79 commit 0cc27d9
Show file tree
Hide file tree
Showing 12 changed files with 32 additions and 16 deletions.
3 changes: 2 additions & 1 deletion src/llmling_agent/agent/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from llmling import BasePrompt, PromptMessage, StaticPrompt
from llmling.config.models import BaseResource
from psygnal import Signal
from upath import UPath

from llmling_agent.log import get_logger
from llmling_agent.messaging.messages import ChatMessage
Expand Down Expand Up @@ -449,6 +448,8 @@ async def add_context_from_path(
Raises:
ValueError: If content cannot be loaded or converted
"""
from upath import UPath

path_obj = UPath(path)
if convert_to_md:
content = await self._agent.context.converter.convert_file(path)
Expand Down
3 changes: 2 additions & 1 deletion src/llmling_agent/models/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
from pydantic import BaseModel, ConfigDict, Field, model_validator
from toprompt import render_prompt
from typing_extensions import TypeVar
from upath.core import UPath

from llmling_agent.common_types import EndStrategy # noqa: TC001
from llmling_agent.config import Capabilities, Knowledge
Expand Down Expand Up @@ -355,6 +354,8 @@ def get_environment_display(self) -> str:
@staticmethod
def _resolve_environment_path(env: str, config_file_path: str | None = None) -> str:
"""Resolve environment path from config store or relative path."""
from upath import UPath

try:
config_store = ConfigStore()
return config_store.get_config(env)
Expand Down
7 changes: 6 additions & 1 deletion src/llmling_agent/models/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from typing import TYPE_CHECKING, Annotated, Any, Literal, Self

from pydantic import BaseModel, ConfigDict, Field
from upath import UPath

from llmling_agent.utils.async_read import read_path

Expand Down Expand Up @@ -65,6 +64,8 @@ async def from_path(
detail: Optional detail level for processing
description: Optional description of the image
"""
from upath import UPath

path_obj = UPath(path)

# For http(s) URLs, pass through as URL content
Expand Down Expand Up @@ -160,6 +161,8 @@ async def from_path(
detail: Optional detail level for processing
description: Optional description of the document
"""
from upath import UPath

path_obj = UPath(path)

# For http(s) URLs, pass through as URL content
Expand Down Expand Up @@ -259,6 +262,8 @@ def from_path(cls, path: StrPath) -> Self:
"""Create from file path with auto format detection."""
import mimetypes

from upath import UPath

path_obj = UPath(path)
mime_type, _ = mimetypes.guess_type(str(path_obj))
fmt = (
Expand Down
3 changes: 2 additions & 1 deletion src/llmling_agent/models/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

from llmling import Config
from pydantic import BaseModel, ConfigDict, Field
from upath import UPath


class FileEnvironment(BaseModel):
Expand Down Expand Up @@ -33,6 +32,8 @@ def get_display_name(self) -> str:

def get_file_path(self) -> str:
"""Get resolved file path."""
from upath import UPath

if self.config_file_path:
base_dir = UPath(self.config_file_path).parent
return str(base_dir / self.uri)
Expand Down
6 changes: 5 additions & 1 deletion src/llmling_agent/models/forward_targets.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
from typing import TYPE_CHECKING, Annotated, Any, Literal

from pydantic import BaseModel, ConfigDict, Field, ImportString
from upath import UPath

from llmling_agent.models.conditions import Condition # noqa: TC001


if TYPE_CHECKING:
from upath import UPath

from llmling_agent.messaging.messages import ChatMessage
from llmling_agent_providers.callback import CallbackProvider

Expand Down Expand Up @@ -132,6 +133,8 @@ def format_message(self, message: ChatMessage[Any]) -> str:

def resolve_path(self, context: dict[str, str]) -> UPath:
"""Resolve path template with context variables."""
from upath import UPath

now = datetime.now()
date = now.strftime("%Y-%m-%d")
time_ = now.strftime("%H-%M-%S")
Expand All @@ -141,6 +144,7 @@ def resolve_path(self, context: dict[str, str]) -> UPath:
def get_provider(self) -> CallbackProvider[str]:
"""Get provider for file writing."""
from jinja2 import Template
from upath import UPath

from llmling_agent_providers.callback import CallbackProvider

Expand Down
4 changes: 2 additions & 2 deletions src/llmling_agent/models/storage.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import os
from pathlib import Path
from typing import Annotated, Final, Literal

from platformdirs import user_data_dir
from pydantic import BaseModel, ConfigDict, Field
from upath import UPath


LogFormat = Literal["chronological", "conversations"]
Expand All @@ -13,7 +13,7 @@

APP_NAME: Final = "llmling-agent"
APP_AUTHOR: Final = "llmling"
DATA_DIR: Final = UPath(user_data_dir(APP_NAME, APP_AUTHOR))
DATA_DIR: Final = Path(user_data_dir(APP_NAME, APP_AUTHOR))
DEFAULT_DB_NAME: Final = "history.db"


Expand Down
2 changes: 1 addition & 1 deletion src/llmling_agent/prompts/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from typing import TYPE_CHECKING

from toprompt import AnyPromptType, to_prompt
from upath import UPath

from llmling_agent.models.content import (
BaseContent,
Expand Down Expand Up @@ -36,6 +35,7 @@ async def convert_prompts(
- Content objects -> pass through
"""
import PIL.Image
from upath import UPath

result: list[str | Content] = []
for p in prompts:
Expand Down
3 changes: 1 addition & 2 deletions src/llmling_agent/utils/async_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from typing import TYPE_CHECKING, Literal, overload

from upath import UPath

from llmling_agent.log import get_logger


Expand Down Expand Up @@ -39,6 +37,7 @@ async def read_path(
from fsspec.asyn import AsyncFileSystem
from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
from morefs.asyn_local import AsyncLocalFileSystem
from upath import UPath

path_obj = UPath(path)

Expand Down
3 changes: 2 additions & 1 deletion src/llmling_agent_cli/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from llmling.cli.constants import output_format_opt, verbose_opt
from llmling.cli.utils import format_output
import typer as t
from upath import UPath

from llmling_agent_cli import agent_store, resolve_agent_config

Expand All @@ -32,6 +31,8 @@ def init_agent_config(
automatically registered and set as active.
"""
# Create config
from upath import UPath

if interactive:
from promptantic import ModelGenerator

Expand Down
3 changes: 2 additions & 1 deletion src/llmling_agent_commands/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from llmling import Config, RuntimeConfig
from slashed import Command, CommandContext, CommandError, PathCompleter
from upath import UPath

from llmling_agent.models.environment import FileEnvironment, InlineEnvironment

Expand Down Expand Up @@ -44,6 +43,8 @@ async def set_env(
kwargs: dict[str, str],
):
"""Change the environment file path."""
from upath import UPath

if not args:
await ctx.output.print("Usage: /set-env <path>")
return
Expand Down
5 changes: 3 additions & 2 deletions src/llmling_agent_tools/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
from urllib.parse import urlparse

from annotated_types import Ge, Le
import httpx
from upath import UPath


PaperType = Literal[
Expand All @@ -22,6 +20,9 @@ async def download_file(
verify_ssl: bool = False, # For testing, in prod should be True
) -> str:
"""Download a file and return status information."""
import httpx
from upath import UPath

start_time = time.time()
target_path = UPath(target_dir)
target_path.mkdir(exist_ok=True)
Expand Down
6 changes: 4 additions & 2 deletions src/llmling_agent_tools/file.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

from upath import UPath


def list_source_files(
directory: str,
Expand All @@ -22,6 +20,8 @@ def list_source_files(
Example:
list_source_files("src", [".py"]) -> ["/full/path/src/models/user.py", ...]
"""
from upath import UPath

path = UPath(directory).resolve() # Get absolute path
if not path.exists():
msg = f"Directory not found: {directory}"
Expand Down Expand Up @@ -55,6 +55,8 @@ def read_source_file(filepath: str) -> str:
Content of the file as text
"""
from upath import UPath

path = UPath(filepath).resolve() # Convert to absolute path
if not path.exists():
msg = f"File not found: {filepath}"
Expand Down

0 comments on commit 0cc27d9

Please sign in to comment.