Skip to content
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ run the benchmarks with Freehand.
| Anthropic | `freehand login anthropic`, then `freehand --provider anthropic` |
| GitHub Copilot (experimental) | [Install the optional SDK](docs/copilot.md), then `freehand login copilot` |
| Amazon Bedrock | `freehand login bedrock` (Claude) or `freehand login bedrock-openai`, with a Bedrock API key and a region |
| Amazon Bedrock with your AWS login | `pip install 'freehand-ai[bedrock]'`, then `freehand login bedrock-aws --region us-east-1 --aws-profile <name>` (Claude); leave the profile empty to use your current AWS login (`AWS_PROFILE`, `aws sso login`) |
| Azure OpenAI, Claude in Microsoft Foundry | `freehand login azure` or `freehand login azure-claude`, with an API key, the resource and the deployment |
| Google Vertex AI | `pip install 'freehand-ai[vertex]'` and `gcloud auth application-default login`, then `freehand login vertex` (Gemini) or `freehand login vertex-claude`, with the project |
| Any OpenAI-compatible Chat Completions API | `freehand --provider openai-chat --api-base <url> --api-key-env <VAR>` |
Expand Down
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ Issues = "https://github.com/microsoft/FreeHand/issues"
freehand = "freehand.cli:main"

[project.optional-dependencies]
dev = ["pytest>=8", "pyflakes>=3"]
dev = ["pytest>=8", "pyflakes>=3", "boto3>=1.28.57,<2"]
copilot = ["microsoft-copilot-sdk==2.0.6; python_version >= '3.11'"]
vertex = ["google-auth[requests]>=2,<3"]
# Claude on Bedrock signed with an AWS profile or the current AWS login (the Anthropic SDK's own Bedrock extra)
bedrock = ["boto3>=1.28.57,<2", "botocore>=1.31.57,<2"]

[tool.setuptools.dynamic]
version = { attr = "freehand.__version__" }
Expand Down
45 changes: 43 additions & 2 deletions src/freehand/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
# services that take the person's Google Cloud sign-in instead of a key: `login` only names the project
GOOGLE_SERVICES = {"vertex": ("Google Vertex AI", providers.CHAT),
"vertex-claude": ("Vertex AI Claude", providers.ANTHROPIC)}
# services that take the person's AWS sign-in instead of a key: `login` names the region and, optionally, a profile
AWS_SERVICES = {"bedrock-aws": ("Amazon Bedrock (AWS sign-in)", providers.ANTHROPIC)}
UNTRUSTED_HEADLESS = ("This folder is not trusted, so its AGENTS.md and project skills are left out. To load them, "
"run `freehand` here once and trust the folder.")
CHECK_TASK = ("This is a connectivity check of the Freehand harness. Call the bash tool with command "
Expand Down Expand Up @@ -173,6 +175,41 @@ def login_google(args: argparse.Namespace) -> int:
return 0


def aws_settings(service: str, places: dict[str, str], profile: str) -> dict[str, Any]:
"""What an AWS sign-in service sets: its address in the region, and the profile when one is named (none: the
AWS CLI's default, which follows AWS_PROFILE and whatever `aws sso login` last signed in)."""
from freehand import session
return {**session.service_settings(service, places), "aws_profile": profile or None}


def login_aws(args: argparse.Namespace) -> int:
"""Point new sessions at Claude on Bedrock signed with an AWS profile. Nothing secret is saved: the AWS tools
keep the credentials, and boto3 reads them for each request."""
from freehand import session
label, provider = AWS_SERVICES[args.service]
if auth.aws_problem() == auth.AWS_INSTALL:
print(auth.AWS_INSTALL, file=sys.stderr)
return 1
try:
places = ask_places(args, label)
if places is None:
return 1
profile = (args.aws_profile if args.aws_profile is not None
else read_line("AWS profile (empty: your current AWS login)")).strip()
except KeyboardInterrupt:
print()
return 1
problem = auth.aws_problem(profile or None)
if problem:
print(problem + " Nothing was saved.", file=sys.stderr)
return 1
dropped = session.set_default_provider(provider, aws_settings(args.service, places, profile))
who = f"the AWS profile {profile}" if profile else "your current AWS login"
print(f"New sessions use {label} in {places['region']} with {who}" + (
f" (removed the previous provider's {', '.join(dropped)} from {session.settings_path()})." if dropped else "."))
return 0


def login_key(args: argparse.Namespace, label: str, provider: str | None, name: str) -> int:
from freehand import session
preset = {} if args.key_env else session.SERVICES.get(args.service) or {}
Expand Down Expand Up @@ -252,6 +289,8 @@ def cmd_login(args: argparse.Namespace) -> int:
return login_copilot(args)
if args.service in GOOGLE_SERVICES and not args.key_env:
return login_google(args)
if args.service in AWS_SERVICES and not args.key_env:
return login_aws(args)
target = key_target(args)
if target:
return login_key(args, *target)
Expand Down Expand Up @@ -1186,15 +1225,17 @@ def main(argv: list[str] | None = None) -> int:
p = sub.add_parser("login", help="Continue with ChatGPT (your ChatGPT plan), or save an API key: "
"`login openai`, `login anthropic`, or sign in with `login copilot`")
p.add_argument("service", nargs="?", default="chatgpt", choices=["chatgpt", "copilot", *KEY_SERVICES,
*GOOGLE_SERVICES],
*GOOGLE_SERVICES, *AWS_SERVICES],
help="chatgpt (the default) signs in through the browser; openai and anthropic ask for an API key; "
"vertex and vertex-claude use the Google Cloud sign-in")
"vertex and vertex-claude use the Google Cloud sign-in; bedrock-aws uses an AWS profile")
p.add_argument("--key-env", metavar="NAME", help="save a key under this variable's name instead, for a gateway "
'or another service that config.json names with "api_key_env"')
p.add_argument("--default", action="store_true", help="make this the provider of new sessions")
p.add_argument("--region", help="the region of a regional service (bedrock: default AWS_REGION or us-east-1)")
p.add_argument("--resource", help="the resource name in an Azure service's address (azure, azure-claude)")
p.add_argument("--deployment", help="the deployment name an Azure service calls the model by")
p.add_argument("--aws-profile", metavar="NAME", help="the AWS profile that signs bedrock-aws requests "
'(default: your current AWS login; "" for it without being asked)')
p.add_argument("--project", help="the Google Cloud project of a Vertex AI service (default GOOGLE_CLOUD_PROJECT)")
p.add_argument("--new-account", action="store_true", help="register another ChatGPT account")
p.add_argument("--port", type=int, default=auth.DEFAULT_PORT, help="local callback port (default 1455)")
Expand Down
19 changes: 14 additions & 5 deletions src/freehand/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Any
import uuid
import urllib.error
import urllib.parse

from freehand import session
from freehand.runtime import auth, providers
Expand Down Expand Up @@ -39,7 +40,7 @@ def identity(config: dict) -> tuple:
if mode == "auto" and (name != providers.RESPONSES or base != prov.api_base.rstrip("/")):
mode = "api_key"
return (name, base, config.get("api_key_env") or prov.api_key_env, mode,
config.get("gateway"))
config.get("gateway"), config.get("aws_profile") or None)


def materialize(settings: dict) -> dict:
Expand Down Expand Up @@ -96,8 +97,8 @@ def credential(config: dict) -> dict:
return {"source": "sign-in" if copilot.ready() else "", "variable": "COPILOT_GITHUB_TOKEN",
"ready": copilot.ready(), "saved": False}
mode = config.get("auth") or "auto"
if mode == "google": # Vertex AI: the Google Cloud sign-in, never a saved key
ready = auth.google_problem() is None
if mode in ("google", "aws"): # Vertex AI or Bedrock: the cloud's own sign-in, never a saved key
ready = (auth.google_problem() if mode == "google" else auth.aws_problem(config.get("aws_profile"))) is None
return {"source": "sign-in" if ready else "", "variable": "", "ready": ready, "saved": False}
env = (config.get("gateway") or {}).get("api_key_env") or config.get("api_key_env") or prov.api_key_env
source = ""
Expand Down Expand Up @@ -129,7 +130,8 @@ def service_preset(name: str, spec: dict) -> dict:
return {"id": name, "name": spec["label"], "config": {**config, "auth": spec.get("auth", "api_key")},
**({"places": places, "address": spec["api_base"]} if places else {}),
**({"deployment": True} if spec.get("deployment") else {}),
**({"signin": auth.google_problem() or ""} if spec.get("auth") == "google" else {})}
**({"signin": auth.google_problem() or ""} if spec.get("auth") == "google" else {}),
**({"signin": auth.aws_problem() or ""} if spec.get("auth") == "aws" else {})}


def overview() -> dict:
Expand Down Expand Up @@ -173,6 +175,13 @@ def validate(config: Any) -> dict:
require(config["provider"] != providers.ANTHROPIC or providers.VERTEX.fullmatch(str(config.get("api_base"))),
"Claude on Vertex AI is reached at https://aiplatform.googleapis.com/v1/projects/<project>/locations/"
"<location>.")
require(config.get("aws_profile") is None or config.get("auth") == "aws",
"An AWS profile is used only by the AWS sign-in.")
if config.get("auth") == "aws":
require(config["provider"] == providers.ANTHROPIC and not config.get("gateway")
and providers.BEDROCK_REGION.search(urllib.parse.urlsplit(str(config.get("api_base") or "")).hostname
or ""),
"The AWS sign-in is for Claude on Bedrock, at https://bedrock-runtime.<region>.amazonaws.com.")
if config.get("auth") == "chatgpt":
require(config["provider"] == providers.RESPONSES and not config.get("gateway")
and (config.get("api_base") or "https://api.openai.com/v1").rstrip("/")
Expand Down Expand Up @@ -260,7 +269,7 @@ def mutate(request: dict) -> dict:
# Custom connections get isolated credentials unless the person explicitly shares a variable (and those
# signed by a sign-in, Copilot's or Google's, take none).
if (not config.get("api_key_env") and not config.get("gateway") and cid != "current"
and config["provider"] != providers.COPILOT and config.get("auth") != "google"):
and config["provider"] != providers.COPILOT and config.get("auth") not in ("google", "aws")):
config["api_key_env"] = f"FREEHAND_CONNECTION_{cid.upper()}_API_KEY"
previous = profiles.get(cid)
check_required = (previous is None or identity(previous["config"]) != identity(config)
Expand Down
20 changes: 14 additions & 6 deletions src/freehand/runtime/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,12 @@ def base_model(model: Any) -> str:
"api_base": "OpenAI-compatible Responses API base URL including the version; POST {api_base}/responses",
"provider": "openai-responses | anthropic | openai-chat: the API, and the native format of transcript.json",
"api_key_env": "environment variable holding the API key; unset = no key (e.g. behind a proxy)",
"auth": "auto | chatgpt | api_key | google | none: auto uses the ChatGPT sign-in (`freehand login`) when there "
"is one, otherwise the API key from api_key_env, otherwise no Authorization header; google sends an "
"access token from the Google Cloud sign-in (Vertex AI)",
"auth": "auto | chatgpt | api_key | google | aws | none: auto uses the ChatGPT sign-in (`freehand login`) "
"when there is one, otherwise the API key from api_key_env, otherwise no Authorization header; google "
"sends an access token from the Google Cloud sign-in (Vertex AI); aws signs Claude on Bedrock with "
"the AWS sign-in",
"aws_profile": "with auth aws: the AWS profile to sign with; unset = the AWS CLI's default (AWS_PROFILE, "
"AWS_* variables, SSO)",
"stream": "stream responses as server-sent events; always on with a ChatGPT sign-in, which requires it",
"prompt_cache_key": "send the session ID as prompt_cache_key and as the session_id header, so the provider routes "
"every turn of the session to the same prompt cache",
Expand Down Expand Up @@ -1088,13 +1091,16 @@ def load_state(self) -> bool:
return True

# ---- model ------------------------------------------------------------------------------------------------------ #
def credentials(self, force_refresh: bool = False) -> tuple[str | None, str]:
"""The secret for the next call and which credential it is: "chatgpt", "google", "api_key" or "none"."""
def credentials(self, force_refresh: bool = False) -> tuple[Any, str]:
"""The secret for the next call and which credential it is: "chatgpt", "google", "aws", "api_key" or
"none"."""
if self.provider.name == _providers.COPILOT:
return None, "copilot"
mode = str(self.cfg.get("auth") or "auto")
if mode == "google":
return _auth.google_token(force_refresh), "google"
if mode == "aws":
return _auth.aws_credentials(self.cfg.get("aws_profile") or None, force_refresh), "aws"
if plan_signs(self.cfg):
return _auth.Store().access_token(force_refresh), "chatgpt"
if mode in ("auto", "api_key"):
Expand Down Expand Up @@ -1274,7 +1280,9 @@ def call_model(self) -> dict[str, Any]:
except _providers.HTTPStatusError as exc:
self._check_cancel()
last = ModelError(exc.status, exc.body)
if exc.status == 401 and kind in ("chatgpt", "google") and not refreshed:
# Bedrock refuses an expired or unsigned AWS request with 403, not 401.
if (exc.status == 401 and kind in ("chatgpt", "google") or exc.status == 403 and kind == "aws") \
and not refreshed:
refreshed = force_refresh = True
continue
if last.code in NON_RETRYABLE_CODES:
Expand Down
99 changes: 99 additions & 0 deletions src/freehand/runtime/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,3 +496,102 @@ def google_token(force_refresh: bool = False) -> str:
except google.auth.exceptions.TransportError as exc:
raise AuthError(f"Google's sign-in service could not be reached: {exc}") from None
return str(creds.token)


# ---- Amazon Web Services (Bedrock) --------------------------------------------------------------------------------- #
# Claude on Bedrock can also be signed with the person's AWS sign-in instead of a Bedrock API key: a named profile, or
# whatever the AWS CLI would use (AWS_PROFILE, the AWS_* variables, an SSO session, assume-role, credential_process).
# boto3 finds those credentials; it is optional and imported only here, so this module still imports without it.
AWS_INSTALL = "Signing in with an AWS profile needs boto3: pip install 'freehand-ai[bedrock]'"
_aws: dict[str, Any] = {}
_aws_lock = threading.Lock()


class AwsCredentials(tuple):
"""(access key, secret key, session token or None), the order AnthropicBedrock takes them in."""

def __repr__(self) -> str: # a log or a traceback never shows the keys
return "AwsCredentials(...)"


def aws_installed() -> bool:
"""Whether boto3 is there to import (`freehand-ai[bedrock]`), without importing it."""
try:
return importlib.util.find_spec("boto3") is not None
except (ImportError, ValueError):
return False


def aws_login_hint(profile: str | None) -> str:
flag = f" --profile {profile}" if profile else ""
return f"Run `aws sso login{flag}` (or `aws configure{flag}`), then try again."


def aws_profiles() -> set[str]:
"""The profiles named in the AWS config and credentials files, read the way the AWS CLI reads them."""
import configparser
names: set[str] = set()
aws = Path.home() / ".aws"
for env, default, prefix in (("AWS_CONFIG_FILE", aws / "config", "profile "),
("AWS_SHARED_CREDENTIALS_FILE", aws / "credentials", "")):
parser = configparser.RawConfigParser()
try:
parser.read(Path(os.environ.get(env) or default).expanduser(), encoding="utf-8")
except (configparser.Error, OSError, UnicodeDecodeError):
continue
for section in parser.sections():
# in the config file only [default] and [profile x] are profiles; [sso-session x] and [services x] are not
if prefix and section.strip() != "default" and not section.startswith(prefix):
continue
names.add(section[len(prefix):].strip() if prefix and section.startswith(prefix) else section.strip())
return names


# what makes boto3's default chain find credentials without a profile in the AWS files
AWS_SIGN_IN_VARIABLES = ("AWS_ACCESS_KEY_ID", "AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_WEB_IDENTITY_TOKEN_FILE",
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI")


def aws_problem(profile: str | None = None) -> str | None:
"""Why there is no AWS sign-in to use, in words for the person; None when there seems to be one. Reads files and
variables only, so whether the sign-in still works (an SSO session lasts hours) is learned when credentials are
asked for. Like Google's, a machine whose only credentials are its instance role is not recognised here."""
if not aws_installed():
return AWS_INSTALL
if profile:
if profile not in aws_profiles():
return f"There is no AWS profile named {profile!r} in ~/.aws/config or ~/.aws/credentials."
return None
if any(os.environ.get(name) for name in AWS_SIGN_IN_VARIABLES) or aws_profiles():
return None
return "No AWS sign-in was found on this computer. Run `aws configure sso` (or `aws configure`)."


def aws_credentials(profile: str | None = None, force_refresh: bool = False) -> AwsCredentials:
"""Credentials from the AWS sign-in, *profile*'s or the default one, renewed by boto3 when they are about to
expire. *force_refresh* (the service refused the last ones) reads the files again, so that a sign-in renewed
since (`aws sso login`) is used. NeedLogin when there are none; AuthError when AWS could not be reached."""
try:
import boto3
import botocore.exceptions as errors
except ImportError:
raise NeedLogin(AWS_INSTALL) from None
with _aws_lock:
key = profile or ""
try:
sess = _aws.get(key)
if sess is None or force_refresh:
sess = _aws[key] = boto3.Session(profile_name=profile or None)
creds = sess.get_credentials()
if creds is None:
raise NeedLogin(f"No AWS credentials were found. {aws_login_hint(profile)}")
frozen = creds.get_frozen_credentials()
except NeedLogin:
_aws.pop(key, None)
raise
except errors.ConnectionError as exc:
raise AuthError(f"AWS could not be reached for credentials: {exc}") from None
except (errors.BotoCoreError, errors.ClientError) as exc:
_aws.pop(key, None) # an expired SSO session: read it again once it is renewed
raise NeedLogin(f"The AWS credentials could not be used ({exc}). {aws_login_hint(profile)}") from None
return AwsCredentials((frozen.access_key, frozen.secret_key, frozen.token))
Loading