From a7ff15ab2e34442e76bf9a2a4ce6f63310575611 Mon Sep 17 00:00:00 2001 From: Jeremy Howard Date: Thu, 5 Dec 2024 11:53:02 +1000 Subject: [PATCH] start moving to nbdev --- .github/workflows/deploy.yaml | 14 + .github/workflows/test.yaml.off | 7 + .gitignore | 156 ++++++++++- LICENSE | 201 ++++++++++++++ MANIFEST.in | 5 + README.md | 94 +++---- nbs/00_core.ipynb | 468 ++++++++++++++++++++++++++++++++ nbs/_quarto.yml | 22 ++ nbs/index.ipynb | 192 +++++++++++++ nbs/nbdev.yml | 9 + nbs/styles.css | 37 +++ pyproject.toml | 17 +- settings.ini | 45 +++ setup.py | 64 +++++ vertexauth/__init__.py | 8 +- vertexauth/_modidx.py | 8 + vertexauth/anthropic.py | 24 -- vertexauth/claudette.py | 20 -- vertexauth/core.py | 114 +------- 19 files changed, 1281 insertions(+), 224 deletions(-) create mode 100644 .github/workflows/deploy.yaml create mode 100644 .github/workflows/test.yaml.off create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 nbs/00_core.ipynb create mode 100644 nbs/_quarto.yml create mode 100644 nbs/index.ipynb create mode 100644 nbs/nbdev.yml create mode 100644 nbs/styles.css create mode 100644 settings.ini create mode 100644 setup.py create mode 100644 vertexauth/_modidx.py delete mode 100644 vertexauth/anthropic.py delete mode 100644 vertexauth/claudette.py diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml new file mode 100644 index 0000000..29bfc57 --- /dev/null +++ b/.github/workflows/deploy.yaml @@ -0,0 +1,14 @@ +name: Deploy to GitHub Pages + +permissions: + contents: write + pages: write + +on: + push: + branches: [ "main", "master" ] + workflow_dispatch: +jobs: + deploy: + runs-on: ubuntu-latest + steps: [uses: fastai/workflows/quarto-ghp@master] diff --git a/.github/workflows/test.yaml.off b/.github/workflows/test.yaml.off new file mode 100644 index 0000000..5608592 --- /dev/null +++ b/.github/workflows/test.yaml.off @@ -0,0 +1,7 @@ +name: CI +on: [workflow_dispatch, pull_request, push] + +jobs: + test: + runs-on: ubuntu-latest + steps: [uses: fastai/workflows/nbdev-ci@master] diff --git a/.gitignore b/.gitignore index 04546a0..a0a0ddc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,154 @@ -.venv/ +*.json +*.old +posts/ +.quarto +.sesskey +*.db-* +*.db +.gitattributes +_proc/ +sidebar.yml +Gemfile.lock +token +_docs/ +conda/ +.last_checked +.gitconfig +*.bak +*.log +*~ +~* +_tmp* +tmp* +tags + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ dist/ -__pycache__ -clean_cache +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.vscode +*.swp + +# osx generated files +.DS_Store +.DS_Store? +.Trashes +ehthumbs.db +Thumbs.db +.idea + +# pytest +.pytest_cache + +# tools/trust-doc-nbs +docs_src/.last_checked + +# symlinks to fastai +docs_src/fastai +tools/fastai + +# link checker +checklink/cookies.txt + +# .gitconfig is now autogenerated +.gitconfig + +_docs diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3b106e8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022, fastai + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..5c0e7ce --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,5 @@ +include settings.ini +include LICENSE +include CONTRIBUTING.md +include README.md +recursive-exclude * __pycache__ diff --git a/README.md b/README.md index 2440dfd..cdac7e9 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,67 @@ -# VertexAuth +# vertexauth -This is a helper library for accessing Google Vertex AI models -To use it, get a GCloud _Service Account Key File_ (SAKF), then save a default "superkey" file into your `.config` dir, like so: + -``` python -from vertexauth import create_superkey_file -path=create_superkey_file(SAKF_path='/path/to/gcloud/service_auth_key_file.json', - region='us-east5', - save_as_default=True) -``` +This file will become your README and also the index of your +documentation. -The superkey file is just the SAKF file with region information added. +## Developer Guide -Then later, you can create a [claudette](https://claudette.answer.ai/) client or [AnthropicVertex](https://docs.anthropic.com/en/api/claude-on-vertex-ai) client object like so: +If you are new to using `nbdev` here are some useful pointers to get you +started. -``` python -from vertexauth import get_anthropic_client, get_claudette_client, load_vertex_vals -from claudette import Chat +### Install vertexauth in Development mode + +``` sh +# make sure vertexauth package is installed in development mode +$ pip install -e . + +# make changes under nbs/ directory +# ... + +# compile to have changes apply to vertexauth +$ nbdev_prepare +``` + +## Usage -# AnthropicVertex -anthropic_client = get_anthropic_client() +### Installation -# claudette.Client -claudette_client = get_claudette_client() -cl_chat = Chat(cli=claudette_client) -cl_chat("Hi, there!") +Install latest from the GitHub +[repository](https://github.com/AnswerDotAI/vertexauth): -# just read the vals -val_dict = load_vertex_vals() +``` sh +$ pip install git+https://github.com/AnswerDotAI/vertexauth.git ``` -These functions also let you pass a path to a specific superkey, instad of loading the default one. +or from [conda](https://anaconda.org/AnswerDotAI/vertexauth) -Alternatively, they can read an env var, `VERTEXAUTH_SUPERKEY`, which contains a superkey as a string. This lets you share it and use it like a normal API key. However, it's a bit long -- around 2,500 characters, since it's simply the gzipped, base64-encoded contents of the file. Use `create_superkey_env_value` to create one. +``` sh +$ conda install -c AnswerDotAI vertexauth +``` -## Huh, what's a Service Account Key File? +or from [pypi](https://pypi.org/project/vertexauth/) -Yes it would be easier of course if Google just gave us a single API key value. But they don't. +``` sh +$ pip install vertexauth +``` -afaict the closest you can get to this with Google Vertex AI is to generate a "Service Account Key File" (SAKF), a JSON file with embedded credentials. But even once you have this, you need to supply it along with other coordinated pieces of information (like project ID and region) in order to make an API request against a VertexAI model. So it's a bit of a hassle., and that's what this library helps with. That's all. +### Documentation -## But how do I get this blessed Service Account Key File from Google +Documentation can be found hosted on this GitHub +[repository](https://github.com/AnswerDotAI/vertexauth)’s +[pages](https://AnswerDotAI.github.io/vertexauth/). Additionally you can +find package manager specific guidelines on +[conda](https://anaconda.org/AnswerDotAI/vertexauth) and +[pypi](https://pypi.org/project/vertexauth/) respectively. -It's not pretty. Here's approximately what you need to do: +## How to use -- Go to Google Cloud console -- Select a project -- Go to APIs & Services -- Go to Enabled APIs and Services -- Select "Vertex AI API" from the list and ensure that it is Enabled" -- Within that panel, select "Quotas and System Limits" - - In the filter control, enter the property name "Online - prediction requests per base model per minute per region per - base_model" to find that row. - - Scope to a particular `region` (e.g., "us-east5") and and - `base_model` (e.g., "anthropic-claude-3-5-sonnet-v2") - - Use "Edit Quota" to ensure that you have a non-zero quote for it -- Also, within that same panel, select "Credentials" - - Click "+ Create Credentials" - - Select "Service Account" - - Enter a name like "vertexaiserviceaccount" etc for the account, - - For permissions, give it the "Vertex AI Service Agent" role. - - Go to keys, select "Add key" and select "JSON" +Fill me in please! Don’t forget code examples: +``` python +1+1 +``` + 2 diff --git a/nbs/00_core.ipynb b/nbs/00_core.ipynb new file mode 100644 index 0000000..8dba7c3 --- /dev/null +++ b/nbs/00_core.ipynb @@ -0,0 +1,468 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "#| default_exp core" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# core\n", + "\n", + "> Fill in a module description here" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#| export\n", + "import json, base64\n", + "from fastcore.utils import *" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [], + "source": [ + "from IPython.display import Markdown\n", + "from playwrightnb import url2md,read_page\n", + "from ContextKit import read_gist" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "sak_docs = read_gist('https://gist.github.com/jph00/3d12ac8ac76c7e7b3ef62dc889284838')" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# !pip install -q google-cloud-service-usage" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "%%ai 0 -c\n", + "I want to create a service account key file using the Python API documented in $`sak_docs`. Can you read the docs and confirm that all the needed info is there, before we begin?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. We'll need to use the `google.cloud.iam_admin_v1` client library\n", + "2. The documentation notes that we'll need:\n", + " - project_id: The Google Cloud project ID\n", + " - account: The service account ID or email" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "#| export\n", + "import google.auth\n", + "from google.cloud import iam_admin_v1\n", + "from google.cloud.iam_admin_v1 import types\n", + "from google.cloud import resourcemanager_v3\n", + "from google.iam.v1 import policy_pb2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can work with Google's IAM API by using a client, assuming you have first run `gcloud auth application-default login`." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'projects/jph001'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cli = iam_admin_v1.IAMClient()\n", + "credentials, project_id = google.auth.default()\n", + "project = f\"projects/{project_id}\"\n", + "project" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will need a \"service account\" with the appropriate permissions. You can check your account list like so:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "accounts = cli.list_service_accounts(name = project)\n", + "# accounts" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "...and here is how to create an account:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "account_id=\"aiservice\"\n", + "display_name=\"Vertex AI Service Account\"\n", + "description=\"Access Vertex AI\"" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "svc = dict(display_name=display_name, description=description)\n", + "account = cli.create_service_account(name=project, account_id=account_id, service_account=svc)\n", + "# account" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "polcli = resourcemanager_v3.ProjectsClient()\n", + "policy = polcli.get_iam_policy(resource=project)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "member = f\"serviceAccount:{account.email}\"\n", + "roles = [ \"roles/aiplatform.user\", \"roles/servicemanagement.quotaViewer\", \"roles/servicemanagement.quotaAdmin\" ]" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [], + "source": [ + "for role in roles:\n", + " binding = policy_pb2.Binding()\n", + " binding.role = role\n", + " binding.members.append(member)\n", + " policy.bindings.append(binding)\n", + " \n", + "polres = polcli.set_iam_policy(request={\"resource\": project, \"policy\": policy})" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "key = cli.create_service_account_key(name = f\"projects/{project_id}/serviceAccounts/{account.email}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [], + "source": [ + "keyd = json.loads(key.private_key_data.decode())\n", + "keyd['region'] = 'us-east5'\n", + "keyb = json.dumps(keyd).encode()" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2331" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "path = Path('service-account-key.json')\n", + "path.write_bytes(keyb)" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": {}, + "outputs": [], + "source": [ + "nk = json.loads(path.read_text())\n", + "# nk" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [], + "source": [ + "from anthropic import AnthropicVertex, AsyncAnthropicVertex\n", + "from operator import itemgetter" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [], + "source": [ + "nk['SAKF_path']=str(path)" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": {}, + "outputs": [], + "source": [ + "gauth_proj_id,gauth_creds,region = itemgetter('project_id','SAKF_path','region')(nk)" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": {}, + "outputs": [], + "source": [ + "os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = gauth_creds\n", + "os.environ[\"GOOGLE_CLOUD_PROJECT\"] = gauth_proj_id\n", + "acli = AnthropicVertex(region=region, project_id=gauth_proj_id)" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [], + "source": [ + "from claudette import *" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": {}, + "outputs": [], + "source": [ + "cla = Client('claude-3-5-sonnet-v2@20241022', acli)" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": {}, + "outputs": [ + { + "data": { + "text/markdown": [ + "Hello! How can I help you today?\n", + "\n", + "
\n", + "\n", + "- id: `msg_vrtx_01UfBEg5LPiemupWnBsAQh8n`\n", + "- content: `[{'text': 'Hello! How can I help you today?', 'type': 'text'}]`\n", + "- model: `claude-3-5-sonnet-v2-20241022`\n", + "- role: `assistant`\n", + "- stop_reason: `end_turn`\n", + "- stop_sequence: `None`\n", + "- type: `message`\n", + "- usage: `{'input_tokens': 8, 'output_tokens': 12}`\n", + "\n", + "
" + ], + "text/plain": [ + "Message(id='msg_vrtx_01UfBEg5LPiemupWnBsAQh8n', content=[TextBlock(text='Hello! How can I help you today?', type='text')], model='claude-3-5-sonnet-v2-20241022', role='assistant', stop_reason='end_turn', stop_sequence=None, type='message', usage=In: 8; Out: 12; Cache create: 0; Cache read: 0; Total: 20)" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cla('hi')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json, base64\n", + "\n", + "# Decode the private key data\n", + "key_data = base64.b64decode(key.private_key_data)\n", + "json_key_file = json.loads(key_data)\n", + "\n", + "# Save to file\n", + "with open('service-account-key.json', 'w') as f:\n", + " json.dump(json_key_file, f)" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": {}, + "outputs": [], + "source": [ + "# cli.delete_service_account(name=f\"projects/{project_id}/serviceAccounts/aiservice@jph001.iam.gserviceaccount.com\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Todo: quota management" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [], + "source": [ + "quota_docs = read_gist('https://gist.github.com/jph00/943c51623abfe0deae65cfad2d821169')\n", + "svcuse_docs = read_gist('https://gist.github.com/jph00/042580724e98ae0cce2db50de92abd1b')" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [], + "source": [ + "from google.cloud import service_usage_v1" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": {}, + "outputs": [], + "source": [ + "%%ai 0 -c\n", + "I want to make sure we have all the quotas we need. See the docs in $`quota_docs` for examples of the quota API, and $`svcuse_docs` for service usage API docs. Do you see anything in the docs which might help here?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Yes I see some options we could use -- do you want me to outline them now?" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": {}, + "outputs": [], + "source": [ + "scli = service_usage_v1.ServiceUsageClient()\n", + "services = scli.list_services(request={\"parent\": project, \"filter\":\"state:ENABLED\"})" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## export -" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#| hide\n", + "import nbdev; nbdev.nbdev_export()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.8" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/nbs/_quarto.yml b/nbs/_quarto.yml new file mode 100644 index 0000000..59a1e49 --- /dev/null +++ b/nbs/_quarto.yml @@ -0,0 +1,22 @@ +project: + type: website + +format: + html: + theme: cosmo + css: styles.css + toc: true + keep-md: true + commonmark: default + +website: + twitter-card: true + open-graph: true + repo-actions: [issue] + navbar: + background: primary + search: true + sidebar: + style: floating + +metadata-files: [nbdev.yml, sidebar.yml] \ No newline at end of file diff --git a/nbs/index.ipynb b/nbs/index.ipynb new file mode 100644 index 0000000..03ab436 --- /dev/null +++ b/nbs/index.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#| hide\n", + "from vertexauth.core import *" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# vertexauth\n", + "\n", + "> A helper library for accessing Google Vertex AI models" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This file will become your README and also the index of your documentation." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Developer Guide" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you are new to using `nbdev` here are some useful pointers to get you started." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Install vertexauth in Development mode" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```sh\n", + "# make sure vertexauth package is installed in development mode\n", + "$ pip install -e .\n", + "\n", + "# make changes under nbs/ directory\n", + "# ...\n", + "\n", + "# compile to have changes apply to vertexauth\n", + "$ nbdev_prepare\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Usage" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Installation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Install latest from the GitHub [repository][repo]:\n", + "\n", + "```sh\n", + "$ pip install git+https://github.com/AnswerDotAI/vertexauth.git\n", + "```\n", + "\n", + "or from [conda][conda]\n", + "\n", + "```sh\n", + "$ conda install -c AnswerDotAI vertexauth\n", + "```\n", + "\n", + "or from [pypi][pypi]\n", + "\n", + "\n", + "```sh\n", + "$ pip install vertexauth\n", + "```\n", + "\n", + "\n", + "[repo]: https://github.com/AnswerDotAI/vertexauth\n", + "[docs]: https://AnswerDotAI.github.io/vertexauth/\n", + "[pypi]: https://pypi.org/project/vertexauth/\n", + "[conda]: https://anaconda.org/AnswerDotAI/vertexauth" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Documentation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Documentation can be found hosted on this GitHub [repository][repo]'s [pages][docs]. Additionally you can find package manager specific guidelines on [conda][conda] and [pypi][pypi] respectively.\n", + "\n", + "[repo]: https://github.com/AnswerDotAI/vertexauth\n", + "[docs]: https://AnswerDotAI.github.io/vertexauth/\n", + "[pypi]: https://pypi.org/project/vertexauth/\n", + "[conda]: https://anaconda.org/AnswerDotAI/vertexauth" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## How to use" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fill me in please! Don't forget code examples:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1+1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.8" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/nbs/nbdev.yml b/nbs/nbdev.yml new file mode 100644 index 0000000..eca4f54 --- /dev/null +++ b/nbs/nbdev.yml @@ -0,0 +1,9 @@ +project: + output-dir: _docs + +website: + title: "vertexauth" + site-url: "https://AnswerDotAI.github.io/vertexauth" + description: "A helper library for accessing Google Vertex AI models" + repo-branch: main + repo-url: "https://github.com/AnswerDotAI/vertexauth" diff --git a/nbs/styles.css b/nbs/styles.css new file mode 100644 index 0000000..66ccc49 --- /dev/null +++ b/nbs/styles.css @@ -0,0 +1,37 @@ +.cell { + margin-bottom: 1rem; +} + +.cell > .sourceCode { + margin-bottom: 0; +} + +.cell-output > pre { + margin-bottom: 0; +} + +.cell-output > pre, .cell-output > .sourceCode > pre, .cell-output-stdout > pre { + margin-left: 0.8rem; + margin-top: 0; + background: none; + border-left: 2px solid lightsalmon; + border-top-left-radius: 0; + border-top-right-radius: 0; +} + +.cell-output > .sourceCode { + border: none; +} + +.cell-output > .sourceCode { + background: none; + margin-top: 0; +} + +div.description { + padding-left: 2px; + padding-top: 5px; + font-style: italic; + font-size: 135%; + opacity: 70%; +} diff --git a/pyproject.toml b/pyproject.toml index b6ce7c5..f2c07bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,16 +1,3 @@ -[tool.poetry] -name = "vertexauth" -version = "0.2.0" -description = "Helper for authenticating with VertexAI" -authors = ["Alexis Gallagher "] -readme = "README.md" - -[tool.poetry.dependencies] -python = ">=3.10" -anthropic = {version = ">=0.37.1", extras = ["vertex"]} -claudette = {version = ">=0.1.0"} - [build-system] -requires = ["poetry-core"] -build-backend = "poetry.core.masonry.api" - +requires = ["setuptools>=64.0"] +build-backend = "setuptools.build_meta" diff --git a/settings.ini b/settings.ini new file mode 100644 index 0000000..532a7f4 --- /dev/null +++ b/settings.ini @@ -0,0 +1,45 @@ +[DEFAULT] +# All sections below are required unless otherwise specified. +# See https://github.com/AnswerDotAI/nbdev/blob/main/settings.ini for examples. + +### Python library ### +repo = vertexauth +lib_name = %(repo)s +version = 0.3.0 +min_python = 3.9 +license = apache2 +black_formatting = False + +### nbdev ### +doc_path = _docs +lib_path = vertexauth +nbs_path = nbs +recursive = True +tst_flags = notest +put_version_in_init = True + +### Docs ### +branch = main +custom_sidebar = False +doc_host = https://%(user)s.github.io +doc_baseurl = /%(repo)s +git_url = https://github.com/%(user)s/%(repo)s +title = %(lib_name)s + +### PyPI ### +audience = Developers +author = Alexis Gallagher +author_email = alexis@alexisgallagher.com +copyright = 2024 onwards, %(author)s +description = A helper library for accessing Google Vertex AI models +keywords = nbdev jupyter notebook python +language = English +status = 3 +user = AnswerDotAI +requirements = anthropic[vertex]>=0.37.1 claudette>=0.1.0 + +### Optional ### +# dev_requirements = +# console_scripts = +# conda_user = +# package_data = diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..21b001e --- /dev/null +++ b/setup.py @@ -0,0 +1,64 @@ +from pkg_resources import parse_version +from configparser import ConfigParser +import setuptools, shlex +assert parse_version(setuptools.__version__)>=parse_version('36.2') + +# note: all settings are in settings.ini; edit there, not here +config = ConfigParser(delimiters=['=']) +config.read('settings.ini', encoding='utf-8') +cfg = config['DEFAULT'] + +cfg_keys = 'version description keywords author author_email'.split() +expected = cfg_keys + "lib_name user branch license status min_python audience language".split() +for o in expected: assert o in cfg, "missing expected setting: {}".format(o) +setup_cfg = {o:cfg[o] for o in cfg_keys} + +licenses = { + 'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'), + 'mit': ('MIT License', 'OSI Approved :: MIT License'), + 'gpl2': ('GNU General Public License v2', 'OSI Approved :: GNU General Public License v2 (GPLv2)'), + 'gpl3': ('GNU General Public License v3', 'OSI Approved :: GNU General Public License v3 (GPLv3)'), + 'bsd3': ('BSD License', 'OSI Approved :: BSD License'), +} +statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha', + '4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ] +py_versions = '3.6 3.7 3.8 3.9 3.10 3.11 3.12'.split() + +requirements = shlex.split(cfg.get('requirements', '')) +if cfg.get('pip_requirements'): requirements += shlex.split(cfg.get('pip_requirements', '')) +min_python = cfg['min_python'] +lic = licenses.get(cfg['license'].lower(), (cfg['license'], None)) +dev_requirements = (cfg.get('dev_requirements') or '').split() + +package_data = dict() +pkg_data = cfg.get('package_data', None) +if pkg_data: + package_data[cfg['lib_name']] = pkg_data.split() # split as multiple files might be listed +# Add package data to setup_cfg for setuptools.setup(..., **setup_cfg) +setup_cfg['package_data'] = package_data + +setuptools.setup( + name = cfg['lib_name'], + license = lic[0], + classifiers = [ + 'Development Status :: ' + statuses[int(cfg['status'])], + 'Intended Audience :: ' + cfg['audience'].title(), + 'Natural Language :: ' + cfg['language'].title(), + ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]] + (['License :: ' + lic[1] ] if lic[1] else []), + url = cfg['git_url'], + packages = setuptools.find_packages(), + include_package_data = True, + install_requires = requirements, + extras_require={ 'dev': dev_requirements }, + dependency_links = cfg.get('dep_links','').split(), + python_requires = '>=' + cfg['min_python'], + long_description = open('README.md', encoding='utf-8').read(), + long_description_content_type = 'text/markdown', + zip_safe = False, + entry_points = { + 'console_scripts': cfg.get('console_scripts','').split(), + 'nbdev': [f'{cfg.get("lib_path")}={cfg.get("lib_path")}._modidx:d'] + }, + **setup_cfg) + + diff --git a/vertexauth/__init__.py b/vertexauth/__init__.py index 5dc130e..f102a9c 100644 --- a/vertexauth/__init__.py +++ b/vertexauth/__init__.py @@ -1,7 +1 @@ -from .core import load_vertex_vals, create_superkey_env_value, create_superkey_file -from .claudette import get_claudette_client -from .anthropic import get_anthropic_client - -__all__ = ["load_vertex_vals", "create_superkey_env_value", "create_superkey_file", - "get_claudette_client", - "get_anthropic_client"] +__version__ = "0.0.1" diff --git a/vertexauth/_modidx.py b/vertexauth/_modidx.py new file mode 100644 index 0000000..e896576 --- /dev/null +++ b/vertexauth/_modidx.py @@ -0,0 +1,8 @@ +# Autogenerated by nbdev + +d = { 'settings': { 'branch': 'main', + 'doc_baseurl': '/vertexauth', + 'doc_host': 'https://AnswerDotAI.github.io', + 'git_url': 'https://github.com/AnswerDotAI/vertexauth', + 'lib_path': 'vertexauth'}, + 'syms': {'vertexauth.core': {'vertexauth.core.foo': ('core.html#foo', 'vertexauth/core.py')}}} diff --git a/vertexauth/anthropic.py b/vertexauth/anthropic.py deleted file mode 100644 index 027d0c3..0000000 --- a/vertexauth/anthropic.py +++ /dev/null @@ -1,24 +0,0 @@ -import os -from operator import itemgetter -from anthropic import AnthropicVertex, AsyncAnthropicVertex -from .core import load_vertex_vals as _lvv - -def get_anthropic_client(asink=False, anthropic_kwargs=None, **kwargs) -> AnthropicVertex: - """ - Creates an AnthropicVertex client configured with VertexAI info. - - Loads info from args, or env var VERTEXAUTH_SUPERKEY, or file at SUPERKEY_DEFAULT_PATH. - - superkey: str, superkey value returned by create_superkey_env_value. - - superkey_path: path to a superkey file, whose path was returned by create_superkey_file - - Returns: AnthropicVertex object - """ - d = _lvv(**kwargs) - (gauth_proj_id, gauth_creds, region) = itemgetter('project_id','SAKF_path','region')(d) - os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = gauth_creds - os.environ["GOOGLE_CLOUD_PROJECT"] = gauth_proj_id - anthropic_kwargs = anthropic_kwargs or {} - if asink: return AsyncAnthropicVertex(region=region, project_id=gauth_proj_id, **anthropic_kwargs) - else: return AnthropicVertex(region=region, project_id=gauth_proj_id, **anthropic_kwargs) diff --git a/vertexauth/claudette.py b/vertexauth/claudette.py deleted file mode 100644 index 906e297..0000000 --- a/vertexauth/claudette.py +++ /dev/null @@ -1,20 +0,0 @@ -import claudette -from .anthropic import get_anthropic_client - -def get_claudette_client(vertex_model='claude-3-5-sonnet-v2@20241022', asink=False, anthropic_kwargs=None, **kwargs) -> claudette.Client: - """ - Creates a claudette.Client configured with VertexAI info. - - Loads info from args, or env var VERTEXAUTH_SUPERKEY, or file at SUPERKEY_DEFAULT_PATH. - - vertex_model : str, valid VertexAI model name (e.g., 'claude-3-5-sonnet-v2@20241022') - - superkey: str, superkey value returned by create_superkey_env_value. - - superkey_path: path to a superkey file, whose path was returned by create_superkey_file - - Returns: a claudette Client object - """ - vertex_client = get_anthropic_client(asink, anthropic_kwargs, **kwargs) - if asink: return claudette.AsyncClient(vertex_model, vertex_client) - else: return claudette.Client(vertex_model, vertex_client) diff --git a/vertexauth/core.py b/vertexauth/core.py index c994379..0843519 100644 --- a/vertexauth/core.py +++ b/vertexauth/core.py @@ -1,111 +1,9 @@ -import json, hashlib,gzip,base64, os, shutil -from pathlib import Path +"""Fill in a module description here""" -SUPERKEY_ENV_VAR = 'VERTEXAUTH_SUPERKEY' +# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb. -_superkey_path_root = Path.home() / ".config" / "vertexauth" -SUPERKEY_DEFAULT_PATH = _superkey_path_root / "default" / "superkey.json" +# %% auto 0 +__all__ = ['foo'] -def load_vertex_vals(superkey:str|None=None,superkey_path:str|None=None) -> dict: - """ - Loads VertexAI vals from arg, or env var VERTEXAUTH_SUPERKEY, or file at SUPERKEY_DEFAULT_PATH. - - superkey: str, superkey value returned by create_superkey_env_value. - - superkey_path: path to a superkey file, whose path was returned by create_superkey_file - - Returns: dict with {project_id, SAKF_path, region} - """ - if superkey is not None: path = _superkey_from_env_value(superkey) - elif superkey_path is not None: path = Path(superkey_path) - elif SUPERKEY_ENV_VAR in os.environ: path = _superkey_from_env_value(os.getenv(SUPERKEY_ENV_VAR)) - elif SUPERKEY_DEFAULT_PATH.is_file(): path = SUPERKEY_DEFAULT_PATH - else: raise Exception(f"No superkey file found in {SUPERKEY_DEFAULT_PATH} and no value found in the environment variable {SUPERKEY_ENV_VAR}. Please either install a superkey file in that path, generating a new one if necessary with create_superkey_file. Or, please add that environment variable, generating it if needed with create_superkey_env_value.") - try: d = json.loads(path.read_text()) - except (json.JSONDecodeError, FileNotFoundError) as e: - raise Exception(f"Failed to read JSON from {path}: {e}") - if 'region' not in d or 'type' not in d or d['type'] != 'service_account': - raise Exception(f"""The superkey path {path} does not contain both the expected key 'region' and the expected k/v 'type':'service_cconut'. This is not a superkey file saved by create_superkey_file. Aborting""") - return dict(project_id=d['project_id'], - SAKF_path=str(path), - region=d['region']) - - -def create_superkey_env_value(SAKF_path, region) -> str: - """Generates a superkey value, from VertexAI values. - - This value can be saved and loaded from the env var VERTEXAUTH_SUPERKEY - - SAKF_path : str - path to a GCloud Service Account Key File, associated with a - GCloud project, which permissions to access the model of - interest in the specified region. region: region - - region : str - region where the project has permissions to access the model - """ - d = _superkey_dict_from_vals(SAKF_path, region) - p = _save_dict(d) - return _env_value(p) - - - -def create_superkey_file(SAKF_path, region, save_as_default=False) -> Path: - """Saves a Vertex AI auth to a superkey file, returning its path. - - SAKF_path : str - path to a GCloud Service Account Key File, associated with a - GCloud project, which permissions to access the model of - interest in the specified region. region: region - - region : str - region where the project has permissions to access the model - """ - d = _superkey_dict_from_vals(SAKF_path, region) - path = _save_dict(d) - if save_as_default: - SUPERKEY_DEFAULT_PATH.parent.mkdir(parents=True,exist_ok=True) - shutil.copy2(path,SUPERKEY_DEFAULT_PATH) - path = SUPERKEY_DEFAULT_PATH - return path - - -def _superkey_dict_from_vals(SAKF_path, region) -> dict: - """Generates a superkey dict from VAI auth vals """ - try: - d = json.loads(Path(SAKF_path).read_text()) - except (json.JSONDecodeError, FileNotFoundError) as e: - raise Exception(f"Failed to read JSON from {path_SAKF}: {e}") - if 'type' not in d or d['type'] != 'service_account': - raise Exception(f"The SAKF_path {SAKF_path} is to a JSON file which does not contain a k/v pair indicating it is a service account file. Aborting") - d["region"]=region - return d - - -def _save_dict(d:dict) -> Path: - """Saves dictionary in managed location, returning its path""" - s = json.dumps(d) - md5h = hashlib.md5(s.encode()).hexdigest() - path = _superkey_path_root / md5h / "superkey.json" - path.parent.mkdir(parents=True,exist_ok=True) - path.write_text(s) - path.chmod(0o600) - return path - - -def _env_value(superkey_path:Path) -> str: - "Generates a str value to use for the env var VERTEX_SUPERKEY" - content = open(str(superkey_path),'r').read() - compressed = gzip.compress(content.encode()) - return base64.b64encode(compressed).decode() - - -def _superkey_from_env_value(val) -> Path: - "Returns a superkey path built from val, an env var val" - compressed = base64.b64decode(val) - s = gzip.decompress(compressed).decode() - d = json.loads(s) - p = _save_dict(d) - return p - - +# %% ../nbs/00_core.ipynb 3 +def foo(): pass