Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "hai-agents"
version = "1.0.16"
version = "1.0.17"
description = "Python SDK for H Company's Agents API: autonomous agents powered by Holo."
requires-python = ">=3.10"
readme = "README.md"
Expand Down
46 changes: 45 additions & 1 deletion src/hai_agents/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@

Fern emits the API surface as ``BaseClient``/``AsyncBaseClient``; these thin
subclasses add the object-oriented sugar (``run_session``, ``start_session``,
``session``) that delegates to the hand-written polling helpers.
``session``) that delegates to the hand-written polling helpers, and default
``api_key`` to the key ``hai login`` stored.
"""

from __future__ import annotations

import asyncio
import functools
import os
import typing
from pathlib import Path

import typing_extensions

from .base_client import AsyncBaseClient, BaseClient
from .core.api_error import ApiError
from .polling import (
AnswerT,
AsyncSessionHandle,
Expand All @@ -31,8 +36,46 @@
if typing.TYPE_CHECKING:
from hai_agents_local.runtime import Inference, LocalRuntime

API_KEY_VAR = "HAI_API_KEY"

_P = typing_extensions.ParamSpec("_P")


def credentials_path() -> Path:
"""The global `.env` that `hai login` writes: `$XDG_CONFIG_HOME/hai/.env`, else `~/.config/hai/.env`."""
return Path(os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config")) / "hai" / ".env"


def _stored_api_key() -> typing.Optional[str]:
"""The `HAI_API_KEY` that `hai login` stored, if any."""
try:
lines = credentials_path().read_text(encoding="utf-8").splitlines()
except (OSError, RuntimeError, UnicodeDecodeError):
return None
for line in lines:
name, sep, value = line.strip().removeprefix("export ").partition("=")
if sep and name.strip() == API_KEY_VAR:
return value.strip().strip("'\"") or None
return None


def _default_api_key(init: typing.Callable[_P, None]) -> typing.Callable[_P, None]:
"""Resolve `api_key` as: argument, then `HAI_API_KEY`, then the key stored by `hai login`."""

@functools.wraps(init)
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None:
if kwargs.get("api_key") is None:
api_key = os.getenv(API_KEY_VAR) or _stored_api_key()
if api_key is None:
raise ApiError(body=f"No API key found. Pass api_key, set {API_KEY_VAR}, or run `hai login`.")
kwargs["api_key"] = api_key
init(*args, **kwargs)

return wrapper


class Client(BaseClient):
__init__ = _default_api_key(BaseClient.__init__)
local_runtime: typing.Optional[LocalRuntime] = None
_owns_runtime = False
_auto_bridges = True
Expand Down Expand Up @@ -138,6 +181,7 @@ def sessions(self) -> SessionsClient:


class AsyncClient(AsyncBaseClient):
__init__ = _default_api_key(AsyncBaseClient.__init__)
local_runtime: typing.Optional[LocalRuntime] = None
_owns_runtime = False
_auto_bridges = True
Expand Down
4 changes: 2 additions & 2 deletions src/hai_agents/core/client_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def get_headers(self) -> typing.Dict[str, str]:
import platform

headers: typing.Dict[str, str] = {
"User-Agent": "hai_agents/1.0.16",
"User-Agent": "hai_agents/1.0.17",
"X-HCompany-Client-Name": "hai_agents",
"X-HCompany-Client-Version": "1.0.16",
"X-HCompany-Client-Version": "1.0.17",
"X-HCompany-Client-Type": "sdk",
"X-HCompany-Language": "Python",
"X-HCompany-Runtime": f"python/{platform.python_version()}",
Expand Down
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading