rnet-oauth 1.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rnet_oauth-1.0.1/LICENSE +21 -0
- rnet_oauth-1.0.1/PKG-INFO +143 -0
- rnet_oauth-1.0.1/README.md +129 -0
- rnet_oauth-1.0.1/pyproject.toml +20 -0
- rnet_oauth-1.0.1/rnet_oauth/__init__.py +4 -0
- rnet_oauth-1.0.1/rnet_oauth/client.py +286 -0
- rnet_oauth-1.0.1/rnet_oauth.egg-info/PKG-INFO +143 -0
- rnet_oauth-1.0.1/rnet_oauth.egg-info/SOURCES.txt +9 -0
- rnet_oauth-1.0.1/rnet_oauth.egg-info/dependency_links.txt +1 -0
- rnet_oauth-1.0.1/rnet_oauth.egg-info/top_level.txt +1 -0
- rnet_oauth-1.0.1/setup.cfg +4 -0
rnet_oauth-1.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 rNet Ai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rnet-oauth
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: RNet OAuth Python client library
|
|
5
|
+
Author: rNet Ai
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://rnetai.org
|
|
8
|
+
Project-URL: Repository, https://github.com/rNetAi/rnet-oauth-python
|
|
9
|
+
Keywords: oauth2,rnet,authentication
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# RNet OAuth Python Library
|
|
16
|
+
|
|
17
|
+
A Python backend library for integrating **RNet OAuth** and **AI Provider** services. This library allows users to authenticate via RNet and pay for AI model token costs directly using their RNet account.
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- **OAuth2 PKCE Support**: Secure authorization code flow with automatic code verifier and challenge generation.
|
|
22
|
+
- **Token Management**: Exchange authorization codes for tokens and refresh expired tokens.
|
|
23
|
+
- **UserInfo Endpoint**: Fetch the authenticated user's RNet profile with an access token.
|
|
24
|
+
- **AI Integration**: Easy methods to chat with AI models using standard or streaming responses.
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install rnet-oauth
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick Start
|
|
33
|
+
|
|
34
|
+
### 1. Initialize the Clients
|
|
35
|
+
```python
|
|
36
|
+
from rnet_oauth import RNetAuth, RNetAi
|
|
37
|
+
|
|
38
|
+
auth = RNetAuth(
|
|
39
|
+
client_id='client-id',
|
|
40
|
+
client_secret='client-secret',
|
|
41
|
+
redirect_uri='redirect-uri'
|
|
42
|
+
)
|
|
43
|
+
ai = RNetAi()
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### 2. Generate Authorization URL (OAuth2 PKCE)
|
|
47
|
+
```python
|
|
48
|
+
# 1. Generate PKCE
|
|
49
|
+
pkce = auth.generate_pkce()
|
|
50
|
+
verifier = pkce['verifier']
|
|
51
|
+
challenge = pkce['challenge']
|
|
52
|
+
|
|
53
|
+
# 2. Get Authorization URL
|
|
54
|
+
# challenge: PKCE code challenge (optional)
|
|
55
|
+
# state: An optional string to maintain state between the request and callback (recommended for security)
|
|
56
|
+
auth_url = auth.get_authorization_url(challenge, state='optional-state')
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### 3. Exchange Code for Tokens
|
|
60
|
+
```python
|
|
61
|
+
# 3. Exchange code for tokens
|
|
62
|
+
tokens = auth.exchange_code_for_token(code, verifier)
|
|
63
|
+
access_token = tokens['access_token']
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 4. Get User Info
|
|
67
|
+
```python
|
|
68
|
+
user_info = auth.get_user_info(access_token)
|
|
69
|
+
print(user_info['email'])
|
|
70
|
+
print(user_info['name'])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The UserInfo response comes from RNet's `/userinfo` endpoint and may include:
|
|
74
|
+
`sub`, `email`, `email_verified`, `name`, `preferred_username`, `user_id`, `role`, and `status`.
|
|
75
|
+
|
|
76
|
+
### 5. Chat with AI
|
|
77
|
+
```python
|
|
78
|
+
response = ai.chat({
|
|
79
|
+
"contents": [
|
|
80
|
+
{
|
|
81
|
+
"role": "user",
|
|
82
|
+
"parts": [{"text": "Hello!"}]
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
}, access_token, "gemini-2.5-flash-lite")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### 6. Streaming AI Response (Untested)
|
|
89
|
+
```python
|
|
90
|
+
for chunk in ai.chat_stream({
|
|
91
|
+
"contents": [
|
|
92
|
+
{
|
|
93
|
+
"role": "user",
|
|
94
|
+
"parts": [{"text": "Hello!"}]
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
}, access_token, "gemini-2.5-flash-lite"):
|
|
98
|
+
print(chunk)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### 7. File Upload (Untested)
|
|
102
|
+
```python
|
|
103
|
+
with open("document.pdf", "rb") as f:
|
|
104
|
+
file_buffer = f.read()
|
|
105
|
+
|
|
106
|
+
# Upload to Gemini
|
|
107
|
+
gemini_upload = ai.gemini_file_upload(access_token, "gemini-2.5-flash-lite", file_buffer, "application/pdf", "document.pdf")
|
|
108
|
+
print(gemini_upload['fileReference']) # Use this in chat payload
|
|
109
|
+
|
|
110
|
+
# Upload to OpenAI
|
|
111
|
+
openai_upload = ai.openai_file_upload(access_token, "gpt-4o", file_buffer, "application/pdf", "document.pdf")
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 8. File Deletion (Untested)
|
|
115
|
+
```python
|
|
116
|
+
# Gemini files auto-delete after 48 hours, so there is no delete method.
|
|
117
|
+
# Delete an OpenAI file:
|
|
118
|
+
ai.openai_file_delete(access_token, "gpt-4o", openai_upload['fileReference'])
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 9. AI Chat with File & Tools (Untested)
|
|
122
|
+
```python
|
|
123
|
+
payload = {
|
|
124
|
+
"contents": [
|
|
125
|
+
{
|
|
126
|
+
"role": "user",
|
|
127
|
+
"parts": [
|
|
128
|
+
{ "text": "Based on this document, what is my name? Also search the web for the current weather in London." },
|
|
129
|
+
{ "fileData": { "fileUri": gemini_upload['fileReference'], "mimeType": gemini_upload['mimeType'] } }
|
|
130
|
+
]
|
|
131
|
+
}
|
|
132
|
+
],
|
|
133
|
+
"tools": [
|
|
134
|
+
{ "googleSearch": {} } # Enable Google Search tool
|
|
135
|
+
]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
response = ai.chat(payload, access_token, "gemini-2.5-flash-lite")
|
|
139
|
+
print(response)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
MIT
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# RNet OAuth Python Library
|
|
2
|
+
|
|
3
|
+
A Python backend library for integrating **RNet OAuth** and **AI Provider** services. This library allows users to authenticate via RNet and pay for AI model token costs directly using their RNet account.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **OAuth2 PKCE Support**: Secure authorization code flow with automatic code verifier and challenge generation.
|
|
8
|
+
- **Token Management**: Exchange authorization codes for tokens and refresh expired tokens.
|
|
9
|
+
- **UserInfo Endpoint**: Fetch the authenticated user's RNet profile with an access token.
|
|
10
|
+
- **AI Integration**: Easy methods to chat with AI models using standard or streaming responses.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install rnet-oauth
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
### 1. Initialize the Clients
|
|
21
|
+
```python
|
|
22
|
+
from rnet_oauth import RNetAuth, RNetAi
|
|
23
|
+
|
|
24
|
+
auth = RNetAuth(
|
|
25
|
+
client_id='client-id',
|
|
26
|
+
client_secret='client-secret',
|
|
27
|
+
redirect_uri='redirect-uri'
|
|
28
|
+
)
|
|
29
|
+
ai = RNetAi()
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### 2. Generate Authorization URL (OAuth2 PKCE)
|
|
33
|
+
```python
|
|
34
|
+
# 1. Generate PKCE
|
|
35
|
+
pkce = auth.generate_pkce()
|
|
36
|
+
verifier = pkce['verifier']
|
|
37
|
+
challenge = pkce['challenge']
|
|
38
|
+
|
|
39
|
+
# 2. Get Authorization URL
|
|
40
|
+
# challenge: PKCE code challenge (optional)
|
|
41
|
+
# state: An optional string to maintain state between the request and callback (recommended for security)
|
|
42
|
+
auth_url = auth.get_authorization_url(challenge, state='optional-state')
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### 3. Exchange Code for Tokens
|
|
46
|
+
```python
|
|
47
|
+
# 3. Exchange code for tokens
|
|
48
|
+
tokens = auth.exchange_code_for_token(code, verifier)
|
|
49
|
+
access_token = tokens['access_token']
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### 4. Get User Info
|
|
53
|
+
```python
|
|
54
|
+
user_info = auth.get_user_info(access_token)
|
|
55
|
+
print(user_info['email'])
|
|
56
|
+
print(user_info['name'])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The UserInfo response comes from RNet's `/userinfo` endpoint and may include:
|
|
60
|
+
`sub`, `email`, `email_verified`, `name`, `preferred_username`, `user_id`, `role`, and `status`.
|
|
61
|
+
|
|
62
|
+
### 5. Chat with AI
|
|
63
|
+
```python
|
|
64
|
+
response = ai.chat({
|
|
65
|
+
"contents": [
|
|
66
|
+
{
|
|
67
|
+
"role": "user",
|
|
68
|
+
"parts": [{"text": "Hello!"}]
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
}, access_token, "gemini-2.5-flash-lite")
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### 6. Streaming AI Response (Untested)
|
|
75
|
+
```python
|
|
76
|
+
for chunk in ai.chat_stream({
|
|
77
|
+
"contents": [
|
|
78
|
+
{
|
|
79
|
+
"role": "user",
|
|
80
|
+
"parts": [{"text": "Hello!"}]
|
|
81
|
+
}
|
|
82
|
+
]
|
|
83
|
+
}, access_token, "gemini-2.5-flash-lite"):
|
|
84
|
+
print(chunk)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 7. File Upload (Untested)
|
|
88
|
+
```python
|
|
89
|
+
with open("document.pdf", "rb") as f:
|
|
90
|
+
file_buffer = f.read()
|
|
91
|
+
|
|
92
|
+
# Upload to Gemini
|
|
93
|
+
gemini_upload = ai.gemini_file_upload(access_token, "gemini-2.5-flash-lite", file_buffer, "application/pdf", "document.pdf")
|
|
94
|
+
print(gemini_upload['fileReference']) # Use this in chat payload
|
|
95
|
+
|
|
96
|
+
# Upload to OpenAI
|
|
97
|
+
openai_upload = ai.openai_file_upload(access_token, "gpt-4o", file_buffer, "application/pdf", "document.pdf")
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### 8. File Deletion (Untested)
|
|
101
|
+
```python
|
|
102
|
+
# Gemini files auto-delete after 48 hours, so there is no delete method.
|
|
103
|
+
# Delete an OpenAI file:
|
|
104
|
+
ai.openai_file_delete(access_token, "gpt-4o", openai_upload['fileReference'])
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### 9. AI Chat with File & Tools (Untested)
|
|
108
|
+
```python
|
|
109
|
+
payload = {
|
|
110
|
+
"contents": [
|
|
111
|
+
{
|
|
112
|
+
"role": "user",
|
|
113
|
+
"parts": [
|
|
114
|
+
{ "text": "Based on this document, what is my name? Also search the web for the current weather in London." },
|
|
115
|
+
{ "fileData": { "fileUri": gemini_upload['fileReference'], "mimeType": gemini_upload['mimeType'] } }
|
|
116
|
+
]
|
|
117
|
+
}
|
|
118
|
+
],
|
|
119
|
+
"tools": [
|
|
120
|
+
{ "googleSearch": {} } # Enable Google Search tool
|
|
121
|
+
]
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
response = ai.chat(payload, access_token, "gemini-2.5-flash-lite")
|
|
125
|
+
print(response)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## License
|
|
129
|
+
MIT
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rnet-oauth"
|
|
7
|
+
version = "1.0.1"
|
|
8
|
+
description = "RNet OAuth Python client library"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{name = "rNet Ai"}]
|
|
13
|
+
keywords = ["oauth2", "rnet", "authentication"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://rnetai.org"
|
|
17
|
+
Repository = "https://github.com/rNetAi/rnet-oauth-python"
|
|
18
|
+
|
|
19
|
+
[tool.setuptools]
|
|
20
|
+
packages = ["rnet_oauth"]
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import os
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import urllib.request
|
|
6
|
+
import urllib.error
|
|
7
|
+
from urllib.parse import urlencode
|
|
8
|
+
from typing import Optional, Dict, Any, Generator
|
|
9
|
+
|
|
10
|
+
ISSUER = "https://central-backend.rnetai.org"
|
|
11
|
+
AI_PROVIDER = "https://ai-provider.rnetai.org"
|
|
12
|
+
|
|
13
|
+
class RNetAuth:
|
|
14
|
+
"""
|
|
15
|
+
RNet OAuth Python Library
|
|
16
|
+
A backend library to verify and exchange OAuth2 tokens and interact with rNet Ai.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
__slots__ = ("client_id", "client_secret", "redirect_uri")
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
client_id: str,
|
|
24
|
+
client_secret: str,
|
|
25
|
+
redirect_uri: str
|
|
26
|
+
):
|
|
27
|
+
if not all([client_id, client_secret, redirect_uri]):
|
|
28
|
+
raise ValueError("client_id, client_secret, and redirect_uri are required")
|
|
29
|
+
|
|
30
|
+
self.client_id = client_id
|
|
31
|
+
self.client_secret = client_secret
|
|
32
|
+
self.redirect_uri = redirect_uri
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def issuer(self) -> str:
|
|
36
|
+
return ISSUER
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def ai_provider(self) -> str:
|
|
40
|
+
return AI_PROVIDER
|
|
41
|
+
|
|
42
|
+
def generate_pkce(self) -> Dict[str, str]:
|
|
43
|
+
"""Generates a PKCE code_verifier and code_challenge."""
|
|
44
|
+
verifier_bytes = os.urandom(32)
|
|
45
|
+
verifier = base64.urlsafe_b64encode(verifier_bytes).decode('utf-8').replace('=', '')
|
|
46
|
+
|
|
47
|
+
challenge_hash = hashlib.sha256(verifier.encode('utf-8')).digest()
|
|
48
|
+
challenge = base64.urlsafe_b64encode(challenge_hash).decode('utf-8').replace('=', '')
|
|
49
|
+
|
|
50
|
+
return {"verifier": verifier, "challenge": challenge}
|
|
51
|
+
|
|
52
|
+
def get_authorization_url(self, challenge: Optional[str] = None, state: Optional[str] = None) -> str:
|
|
53
|
+
"""Generates the authorization URL."""
|
|
54
|
+
params = {
|
|
55
|
+
"response_type": "code",
|
|
56
|
+
"client_id": self.client_id,
|
|
57
|
+
"redirect_uri": self.redirect_uri,
|
|
58
|
+
"scope": "openid profile email"
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if challenge:
|
|
62
|
+
params["code_challenge"] = challenge
|
|
63
|
+
params["code_challenge_method"] = "S256"
|
|
64
|
+
|
|
65
|
+
if state:
|
|
66
|
+
params["state"] = state
|
|
67
|
+
|
|
68
|
+
return f"{ISSUER}/oauth2/authorize?{urlencode(params)}"
|
|
69
|
+
|
|
70
|
+
def exchange_code_for_token(self, code: str, code_verifier: Optional[str] = None) -> Dict[str, Any]:
|
|
71
|
+
"""Exchanges an authorization code for tokens."""
|
|
72
|
+
payload = {
|
|
73
|
+
"grant_type": "authorization_code",
|
|
74
|
+
"code": code,
|
|
75
|
+
"redirect_uri": self.redirect_uri
|
|
76
|
+
}
|
|
77
|
+
if code_verifier:
|
|
78
|
+
payload["code_verifier"] = code_verifier
|
|
79
|
+
|
|
80
|
+
return self._post_token(payload)
|
|
81
|
+
|
|
82
|
+
def refresh_access_token(self, refresh_token: str) -> Dict[str, Any]:
|
|
83
|
+
"""Renews tokens using a refresh token."""
|
|
84
|
+
payload = {
|
|
85
|
+
"grant_type": "refresh_token",
|
|
86
|
+
"refresh_token": refresh_token
|
|
87
|
+
}
|
|
88
|
+
return self._post_token(payload)
|
|
89
|
+
|
|
90
|
+
def get_user_info(self, access_token: str) -> Dict[str, Any]:
|
|
91
|
+
"""Fetches the authenticated user's profile from the OAuth UserInfo endpoint."""
|
|
92
|
+
if not access_token:
|
|
93
|
+
raise ValueError("access_token is required")
|
|
94
|
+
|
|
95
|
+
req = urllib.request.Request(
|
|
96
|
+
f"{ISSUER}/userinfo",
|
|
97
|
+
headers={
|
|
98
|
+
'Accept': 'application/json',
|
|
99
|
+
'Authorization': f'Bearer {access_token}'
|
|
100
|
+
},
|
|
101
|
+
method='GET'
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
with urllib.request.urlopen(req) as response:
|
|
106
|
+
return json.loads(response.read().decode('utf-8'))
|
|
107
|
+
except urllib.error.HTTPError as e:
|
|
108
|
+
self._handle_error(e)
|
|
109
|
+
|
|
110
|
+
def _post_token(self, payload: Dict[str, str]) -> Dict[str, Any]:
|
|
111
|
+
url = f"{ISSUER}/oauth2/token"
|
|
112
|
+
data = urlencode(payload).encode('utf-8')
|
|
113
|
+
|
|
114
|
+
auth = base64.b64encode(f"{self.client_id}:{self.client_secret}".encode('utf-8')).decode('utf-8')
|
|
115
|
+
|
|
116
|
+
req = urllib.request.Request(
|
|
117
|
+
url,
|
|
118
|
+
data=data,
|
|
119
|
+
headers={
|
|
120
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
121
|
+
'Authorization': f'Basic {auth}'
|
|
122
|
+
},
|
|
123
|
+
method='POST'
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
with urllib.request.urlopen(req) as response:
|
|
128
|
+
return json.loads(response.read().decode('utf-8'))
|
|
129
|
+
except urllib.error.HTTPError as e:
|
|
130
|
+
self._handle_error(e)
|
|
131
|
+
|
|
132
|
+
def _handle_error(self, e: urllib.error.HTTPError):
|
|
133
|
+
try:
|
|
134
|
+
error_data = json.loads(e.read().decode('utf-8'))
|
|
135
|
+
msg = error_data.get("error", str(e))
|
|
136
|
+
except:
|
|
137
|
+
msg = str(e)
|
|
138
|
+
raise RuntimeError(f"Request failed: {e.code} - {msg}")
|
|
139
|
+
|
|
140
|
+
class RNetAi:
|
|
141
|
+
"""
|
|
142
|
+
rNet Ai Python Library
|
|
143
|
+
Interaction with rNet Ai services.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
__slots__ = ()
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def ai_provider(self) -> str:
|
|
150
|
+
return AI_PROVIDER
|
|
151
|
+
|
|
152
|
+
def chat(self, body: Dict[str, Any], access_token: str, model: str) -> Dict[str, Any]:
|
|
153
|
+
"""Calls the rNet Ai Provider API."""
|
|
154
|
+
if not access_token: raise ValueError("access_token is required")
|
|
155
|
+
if not model: raise ValueError("model is required")
|
|
156
|
+
|
|
157
|
+
query = urlencode({"access_token": access_token, "model": model})
|
|
158
|
+
url = f"{AI_PROVIDER}/ai?{query}"
|
|
159
|
+
|
|
160
|
+
req = urllib.request.Request(
|
|
161
|
+
url,
|
|
162
|
+
data=json.dumps(body).encode('utf-8'),
|
|
163
|
+
headers={'Content-Type': 'application/json'},
|
|
164
|
+
method='POST'
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
try:
|
|
168
|
+
with urllib.request.urlopen(req) as response:
|
|
169
|
+
return json.loads(response.read().decode('utf-8'))
|
|
170
|
+
except urllib.error.HTTPError as e:
|
|
171
|
+
self._handle_error(e)
|
|
172
|
+
|
|
173
|
+
def chat_stream(self, body: Dict[str, Any], access_token: str, model: str) -> Generator[str, None, None]:
|
|
174
|
+
"""Calls the rNet Ai Provider API and returns a generator for the response stream."""
|
|
175
|
+
if not access_token: raise ValueError("access_token is required")
|
|
176
|
+
if not model: raise ValueError("model is required")
|
|
177
|
+
|
|
178
|
+
query = urlencode({"access_token": access_token, "model": model})
|
|
179
|
+
url = f"{AI_PROVIDER}/ai/stream?{query}"
|
|
180
|
+
|
|
181
|
+
req = urllib.request.Request(
|
|
182
|
+
url,
|
|
183
|
+
data=json.dumps(body).encode('utf-8'),
|
|
184
|
+
headers={'Content-Type': 'application/json'},
|
|
185
|
+
method='POST'
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
response = urllib.request.urlopen(req)
|
|
190
|
+
for line in response:
|
|
191
|
+
yield line.decode('utf-8')
|
|
192
|
+
except urllib.error.HTTPError as e:
|
|
193
|
+
self._handle_error(e)
|
|
194
|
+
|
|
195
|
+
def gemini_file_upload(self, access_token: str, model: str, file_data: bytes, mime_type: str, display_name: str = "") -> Dict[str, Any]:
|
|
196
|
+
"""Uploads a file for use with Gemini models. (Untested)"""
|
|
197
|
+
return self._upload_file(access_token, model, file_data, mime_type, display_name)
|
|
198
|
+
|
|
199
|
+
def openai_file_upload(self, access_token: str, model: str, file_data: bytes, mime_type: str, display_name: str = "") -> Dict[str, Any]:
|
|
200
|
+
"""Uploads a file for use with OpenAI models. (Untested)"""
|
|
201
|
+
return self._upload_file(access_token, model, file_data, mime_type, display_name)
|
|
202
|
+
|
|
203
|
+
def claude_file_upload(self, access_token: str, model: str, file_data: bytes, mime_type: str, display_name: str = "") -> Dict[str, Any]:
|
|
204
|
+
"""Uploads a file for use with Claude models. (Untested)"""
|
|
205
|
+
return self._upload_file(access_token, model, file_data, mime_type, display_name)
|
|
206
|
+
|
|
207
|
+
def openai_file_delete(self, access_token: str, model: str, file_id: str) -> Dict[str, Any]:
|
|
208
|
+
"""Deletes a file previously uploaded for OpenAI models. (Untested)"""
|
|
209
|
+
return self._delete_file(access_token, model, file_id)
|
|
210
|
+
|
|
211
|
+
def claude_file_delete(self, access_token: str, model: str, file_id: str) -> Dict[str, Any]:
|
|
212
|
+
"""Deletes a file previously uploaded for Claude models. (Untested)"""
|
|
213
|
+
return self._delete_file(access_token, model, file_id)
|
|
214
|
+
|
|
215
|
+
def _upload_file(self, access_token: str, model: str, file_data: bytes, mime_type: str, display_name: str) -> Dict[str, Any]:
|
|
216
|
+
if not access_token: raise ValueError("access_token is required")
|
|
217
|
+
if not model: raise ValueError("model is required")
|
|
218
|
+
if not file_data: raise ValueError("file_data is required")
|
|
219
|
+
if not mime_type: raise ValueError("mime_type is required")
|
|
220
|
+
|
|
221
|
+
query = urlencode({"access_token": access_token, "model": model})
|
|
222
|
+
url = f"{AI_PROVIDER}/ai/upload?{query}"
|
|
223
|
+
|
|
224
|
+
import uuid
|
|
225
|
+
boundary = uuid.uuid4().hex
|
|
226
|
+
|
|
227
|
+
body = bytearray()
|
|
228
|
+
|
|
229
|
+
# Add file part
|
|
230
|
+
body.extend(f"--{boundary}\r\n".encode('utf-8'))
|
|
231
|
+
filename = display_name if display_name else "file"
|
|
232
|
+
body.extend(f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'.encode('utf-8'))
|
|
233
|
+
body.extend(f'Content-Type: {mime_type}\r\n\r\n'.encode('utf-8'))
|
|
234
|
+
body.extend(file_data)
|
|
235
|
+
body.extend(b'\r\n')
|
|
236
|
+
|
|
237
|
+
# Add mimeType part
|
|
238
|
+
body.extend(f"--{boundary}\r\n".encode('utf-8'))
|
|
239
|
+
body.extend(b'Content-Disposition: form-data; name="mimeType"\r\n\r\n')
|
|
240
|
+
body.extend(mime_type.encode('utf-8'))
|
|
241
|
+
body.extend(b'\r\n')
|
|
242
|
+
|
|
243
|
+
# Add displayName part
|
|
244
|
+
body.extend(f"--{boundary}\r\n".encode('utf-8'))
|
|
245
|
+
body.extend(b'Content-Disposition: form-data; name="displayName"\r\n\r\n')
|
|
246
|
+
body.extend(display_name.encode('utf-8'))
|
|
247
|
+
body.extend(b'\r\n')
|
|
248
|
+
|
|
249
|
+
body.extend(f"--{boundary}--\r\n".encode('utf-8'))
|
|
250
|
+
|
|
251
|
+
req = urllib.request.Request(
|
|
252
|
+
url,
|
|
253
|
+
data=bytes(body),
|
|
254
|
+
headers={'Content-Type': f'multipart/form-data; boundary={boundary}'},
|
|
255
|
+
method='POST'
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
try:
|
|
259
|
+
with urllib.request.urlopen(req) as response:
|
|
260
|
+
return json.loads(response.read().decode('utf-8'))
|
|
261
|
+
except urllib.error.HTTPError as e:
|
|
262
|
+
self._handle_error(e)
|
|
263
|
+
|
|
264
|
+
def _delete_file(self, access_token: str, model: str, file_id: str) -> Dict[str, Any]:
|
|
265
|
+
if not access_token: raise ValueError("access_token is required")
|
|
266
|
+
if not model: raise ValueError("model is required")
|
|
267
|
+
if not file_id: raise ValueError("file_id is required")
|
|
268
|
+
|
|
269
|
+
query = urlencode({"access_token": access_token, "model": model, "fileId": file_id})
|
|
270
|
+
url = f"{AI_PROVIDER}/ai/upload?{query}"
|
|
271
|
+
|
|
272
|
+
req = urllib.request.Request(url, method='DELETE')
|
|
273
|
+
|
|
274
|
+
try:
|
|
275
|
+
with urllib.request.urlopen(req) as response:
|
|
276
|
+
return json.loads(response.read().decode('utf-8'))
|
|
277
|
+
except urllib.error.HTTPError as e:
|
|
278
|
+
self._handle_error(e)
|
|
279
|
+
|
|
280
|
+
def _handle_error(self, e: urllib.error.HTTPError):
|
|
281
|
+
try:
|
|
282
|
+
error_data = json.loads(e.read().decode('utf-8'))
|
|
283
|
+
msg = error_data.get("error", str(e))
|
|
284
|
+
except:
|
|
285
|
+
msg = str(e)
|
|
286
|
+
raise RuntimeError(f"Request failed: {e.code} - {msg}")
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rnet-oauth
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: RNet OAuth Python client library
|
|
5
|
+
Author: rNet Ai
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://rnetai.org
|
|
8
|
+
Project-URL: Repository, https://github.com/rNetAi/rnet-oauth-python
|
|
9
|
+
Keywords: oauth2,rnet,authentication
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# RNet OAuth Python Library
|
|
16
|
+
|
|
17
|
+
A Python backend library for integrating **RNet OAuth** and **AI Provider** services. This library allows users to authenticate via RNet and pay for AI model token costs directly using their RNet account.
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- **OAuth2 PKCE Support**: Secure authorization code flow with automatic code verifier and challenge generation.
|
|
22
|
+
- **Token Management**: Exchange authorization codes for tokens and refresh expired tokens.
|
|
23
|
+
- **UserInfo Endpoint**: Fetch the authenticated user's RNet profile with an access token.
|
|
24
|
+
- **AI Integration**: Easy methods to chat with AI models using standard or streaming responses.
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install rnet-oauth
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick Start
|
|
33
|
+
|
|
34
|
+
### 1. Initialize the Clients
|
|
35
|
+
```python
|
|
36
|
+
from rnet_oauth import RNetAuth, RNetAi
|
|
37
|
+
|
|
38
|
+
auth = RNetAuth(
|
|
39
|
+
client_id='client-id',
|
|
40
|
+
client_secret='client-secret',
|
|
41
|
+
redirect_uri='redirect-uri'
|
|
42
|
+
)
|
|
43
|
+
ai = RNetAi()
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### 2. Generate Authorization URL (OAuth2 PKCE)
|
|
47
|
+
```python
|
|
48
|
+
# 1. Generate PKCE
|
|
49
|
+
pkce = auth.generate_pkce()
|
|
50
|
+
verifier = pkce['verifier']
|
|
51
|
+
challenge = pkce['challenge']
|
|
52
|
+
|
|
53
|
+
# 2. Get Authorization URL
|
|
54
|
+
# challenge: PKCE code challenge (optional)
|
|
55
|
+
# state: An optional string to maintain state between the request and callback (recommended for security)
|
|
56
|
+
auth_url = auth.get_authorization_url(challenge, state='optional-state')
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### 3. Exchange Code for Tokens
|
|
60
|
+
```python
|
|
61
|
+
# 3. Exchange code for tokens
|
|
62
|
+
tokens = auth.exchange_code_for_token(code, verifier)
|
|
63
|
+
access_token = tokens['access_token']
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 4. Get User Info
|
|
67
|
+
```python
|
|
68
|
+
user_info = auth.get_user_info(access_token)
|
|
69
|
+
print(user_info['email'])
|
|
70
|
+
print(user_info['name'])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The UserInfo response comes from RNet's `/userinfo` endpoint and may include:
|
|
74
|
+
`sub`, `email`, `email_verified`, `name`, `preferred_username`, `user_id`, `role`, and `status`.
|
|
75
|
+
|
|
76
|
+
### 5. Chat with AI
|
|
77
|
+
```python
|
|
78
|
+
response = ai.chat({
|
|
79
|
+
"contents": [
|
|
80
|
+
{
|
|
81
|
+
"role": "user",
|
|
82
|
+
"parts": [{"text": "Hello!"}]
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
}, access_token, "gemini-2.5-flash-lite")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### 6. Streaming AI Response (Untested)
|
|
89
|
+
```python
|
|
90
|
+
for chunk in ai.chat_stream({
|
|
91
|
+
"contents": [
|
|
92
|
+
{
|
|
93
|
+
"role": "user",
|
|
94
|
+
"parts": [{"text": "Hello!"}]
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
}, access_token, "gemini-2.5-flash-lite"):
|
|
98
|
+
print(chunk)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### 7. File Upload (Untested)
|
|
102
|
+
```python
|
|
103
|
+
with open("document.pdf", "rb") as f:
|
|
104
|
+
file_buffer = f.read()
|
|
105
|
+
|
|
106
|
+
# Upload to Gemini
|
|
107
|
+
gemini_upload = ai.gemini_file_upload(access_token, "gemini-2.5-flash-lite", file_buffer, "application/pdf", "document.pdf")
|
|
108
|
+
print(gemini_upload['fileReference']) # Use this in chat payload
|
|
109
|
+
|
|
110
|
+
# Upload to OpenAI
|
|
111
|
+
openai_upload = ai.openai_file_upload(access_token, "gpt-4o", file_buffer, "application/pdf", "document.pdf")
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 8. File Deletion (Untested)
|
|
115
|
+
```python
|
|
116
|
+
# Gemini files auto-delete after 48 hours, so there is no delete method.
|
|
117
|
+
# Delete an OpenAI file:
|
|
118
|
+
ai.openai_file_delete(access_token, "gpt-4o", openai_upload['fileReference'])
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 9. AI Chat with File & Tools (Untested)
|
|
122
|
+
```python
|
|
123
|
+
payload = {
|
|
124
|
+
"contents": [
|
|
125
|
+
{
|
|
126
|
+
"role": "user",
|
|
127
|
+
"parts": [
|
|
128
|
+
{ "text": "Based on this document, what is my name? Also search the web for the current weather in London." },
|
|
129
|
+
{ "fileData": { "fileUri": gemini_upload['fileReference'], "mimeType": gemini_upload['mimeType'] } }
|
|
130
|
+
]
|
|
131
|
+
}
|
|
132
|
+
],
|
|
133
|
+
"tools": [
|
|
134
|
+
{ "googleSearch": {} } # Enable Google Search tool
|
|
135
|
+
]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
response = ai.chat(payload, access_token, "gemini-2.5-flash-lite")
|
|
139
|
+
print(response)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
MIT
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
rnet_oauth
|