metergraphrelay 0.1.0__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.
- metergraphrelay-0.1.0/LICENSE +21 -0
- metergraphrelay-0.1.0/PKG-INFO +144 -0
- metergraphrelay-0.1.0/README.md +121 -0
- metergraphrelay-0.1.0/pyproject.toml +40 -0
- metergraphrelay-0.1.0/setup.cfg +4 -0
- metergraphrelay-0.1.0/src/metergraphrelay/__init__.py +1 -0
- metergraphrelay-0.1.0/src/metergraphrelay/cli.py +141 -0
- metergraphrelay-0.1.0/src/metergraphrelay/config.py +37 -0
- metergraphrelay-0.1.0/src/metergraphrelay/demo.py +22 -0
- metergraphrelay-0.1.0/src/metergraphrelay/providers/__init__.py +0 -0
- metergraphrelay-0.1.0/src/metergraphrelay/providers/openai.py +101 -0
- metergraphrelay-0.1.0/src/metergraphrelay/push.py +60 -0
- metergraphrelay-0.1.0/src/metergraphrelay/py.typed +0 -0
- metergraphrelay-0.1.0/src/metergraphrelay.egg-info/PKG-INFO +144 -0
- metergraphrelay-0.1.0/src/metergraphrelay.egg-info/SOURCES.txt +21 -0
- metergraphrelay-0.1.0/src/metergraphrelay.egg-info/dependency_links.txt +1 -0
- metergraphrelay-0.1.0/src/metergraphrelay.egg-info/entry_points.txt +2 -0
- metergraphrelay-0.1.0/src/metergraphrelay.egg-info/requires.txt +5 -0
- metergraphrelay-0.1.0/src/metergraphrelay.egg-info/top_level.txt +1 -0
- metergraphrelay-0.1.0/tests/test_cli.py +236 -0
- metergraphrelay-0.1.0/tests/test_config.py +77 -0
- metergraphrelay-0.1.0/tests/test_demo.py +45 -0
- metergraphrelay-0.1.0/tests/test_push.py +108 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vasiliy Radostev
|
|
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,144 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: metergraphrelay
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Move LLM trace data between systems: pull from providers, push to metergraph.
|
|
5
|
+
Author: Vasiliy Radostev
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/VasiliyRad/metergraphrelay
|
|
8
|
+
Project-URL: Repository, https://github.com/VasiliyRad/metergraphrelay
|
|
9
|
+
Project-URL: Issues, https://github.com/VasiliyRad/metergraphrelay/issues
|
|
10
|
+
Keywords: llm,openai,observability,cost-tracking,cli,metergraph
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: openai>=1.63.0
|
|
19
|
+
Requires-Dist: python-dotenv>=1.0
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# metergraphrelay
|
|
25
|
+
|
|
26
|
+
Export OpenAI stored chat completions as trace records, and optionally
|
|
27
|
+
generate demo conversations to try it out.
|
|
28
|
+
|
|
29
|
+
## Purpose
|
|
30
|
+
|
|
31
|
+
Download the chat completions already stored in *your own* OpenAI
|
|
32
|
+
account (completions created with `store=True`) as local JSONL trace
|
|
33
|
+
records — useful for auditing, backups, or feeding into other tooling.
|
|
34
|
+
This tool only reads what's associated with the API key you provide; it
|
|
35
|
+
can't see or export anyone else's data.
|
|
36
|
+
|
|
37
|
+
Built on OpenAI's [List Chat Completions API](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/list),
|
|
38
|
+
which returns completions that were created with `store: true`. See the
|
|
39
|
+
[official OpenAI API reference](https://developers.openai.com/api/reference/chat-completions/overview)
|
|
40
|
+
for the underlying data model.
|
|
41
|
+
|
|
42
|
+
## Setup
|
|
43
|
+
|
|
44
|
+
pip install -e ".[dev]"
|
|
45
|
+
cp .env.example .env
|
|
46
|
+
# edit .env and set OPENAI_API_KEY
|
|
47
|
+
|
|
48
|
+
## Usage
|
|
49
|
+
|
|
50
|
+
Generate 1-2 demo conversations (stored with `store=True`) so there's
|
|
51
|
+
data to pull:
|
|
52
|
+
|
|
53
|
+
metergraphrelay demo openai
|
|
54
|
+
|
|
55
|
+
Pull the 10 most recent stored chat completions into `traces.jsonl`,
|
|
56
|
+
already shaped as metergraph trace records:
|
|
57
|
+
|
|
58
|
+
metergraphrelay pull openai
|
|
59
|
+
|
|
60
|
+
Options:
|
|
61
|
+
|
|
62
|
+
metergraphrelay pull openai -n 25 --output my-traces.jsonl --stdout --include-content --route my-app/support-bot
|
|
63
|
+
metergraphrelay demo openai --model gpt-4o-mini
|
|
64
|
+
|
|
65
|
+
Push a local JSONL file of traces to metergraph:
|
|
66
|
+
|
|
67
|
+
metergraphrelay push traces.jsonl
|
|
68
|
+
|
|
69
|
+
`pull anthropic` and `pull langfuse` accept the same shape but are not
|
|
70
|
+
yet implemented in this version — they check for `ANTHROPIC_API_KEY` /
|
|
71
|
+
`LANGFUSE_PUBLIC_KEY`+`LANGFUSE_SECRET_KEY` and report accordingly.
|
|
72
|
+
|
|
73
|
+
All subcommands accept `--env-file PATH` to point at a config file
|
|
74
|
+
other than `./.env`.
|
|
75
|
+
|
|
76
|
+
## Using it against your real system (not just the demo)
|
|
77
|
+
|
|
78
|
+
`metergraphrelay pull openai` only finds completions that were created
|
|
79
|
+
with `store=True`. The `demo openai` subcommand sets that flag for you,
|
|
80
|
+
but for your own application to show up in a pull, its own OpenAI calls
|
|
81
|
+
need the same flag. The only change required is adding `store=True`
|
|
82
|
+
(and, optionally, `metadata` to help you tell requests apart later) to
|
|
83
|
+
calls you're already making:
|
|
84
|
+
|
|
85
|
+
from openai import OpenAI
|
|
86
|
+
|
|
87
|
+
client = OpenAI()
|
|
88
|
+
|
|
89
|
+
response = client.chat.completions.create(
|
|
90
|
+
model="gpt-4o-mini",
|
|
91
|
+
messages=[{"role": "user", "content": "..."}],
|
|
92
|
+
store=True, # <-- persists this completion for later pulling
|
|
93
|
+
metadata={"source": "my-app"}, # optional: filter/identify later via the API
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
No other code changes are needed — the request and response are handled
|
|
97
|
+
exactly as before. Once your app is sending `store=True`, its completions
|
|
98
|
+
become visible to `metergraphrelay pull openai` (or to the
|
|
99
|
+
[List Chat Completions API](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/list)
|
|
100
|
+
directly) using the same API key.
|
|
101
|
+
|
|
102
|
+
Two things worth knowing before flipping this on in production:
|
|
103
|
+
- Stored completions include full request/response content by default,
|
|
104
|
+
so treat them as you would any other place your data is retained.
|
|
105
|
+
- Storage has no automatic expiry from this tool's side — deletion is a
|
|
106
|
+
separate API call ([Delete chat completion](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/delete)),
|
|
107
|
+
not something `metergraphrelay` currently does.
|
|
108
|
+
|
|
109
|
+
## Trace record shape
|
|
110
|
+
|
|
111
|
+
Each line of `pull openai`'s output is a JSON object already shaped for
|
|
112
|
+
metergraph's ingest API:
|
|
113
|
+
|
|
114
|
+
{
|
|
115
|
+
"ts": "2026-07-30T12:00:00+00:00",
|
|
116
|
+
"provider": "openai",
|
|
117
|
+
"model": "gpt-4o-mini",
|
|
118
|
+
"status": "success",
|
|
119
|
+
"endpoint": "chat.completions",
|
|
120
|
+
"input_tokens": 12,
|
|
121
|
+
"output_tokens": 34,
|
|
122
|
+
"error": false,
|
|
123
|
+
"error_type": null,
|
|
124
|
+
"request_id": "chatcmpl-...",
|
|
125
|
+
"tags": {},
|
|
126
|
+
"route": "openai/backfill",
|
|
127
|
+
"content_opted_in": false,
|
|
128
|
+
"request_json": null,
|
|
129
|
+
"response_text": null,
|
|
130
|
+
"sdk": "metergraphrelay",
|
|
131
|
+
"sdk_version": "0.1.0"
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
`request_json`/`response_text` are populated only when `--include-content`
|
|
135
|
+
is passed.
|
|
136
|
+
|
|
137
|
+
Every completion returned by the stored-completions list already succeeded, so
|
|
138
|
+
`status` is always `"success"`. `error`/`error_type` flag a *partial* record:
|
|
139
|
+
`--include-content` was requested but the follow-up message fetch failed, so
|
|
140
|
+
token counts are still real while the content is missing.
|
|
141
|
+
|
|
142
|
+
## Running tests
|
|
143
|
+
|
|
144
|
+
pytest
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# metergraphrelay
|
|
2
|
+
|
|
3
|
+
Export OpenAI stored chat completions as trace records, and optionally
|
|
4
|
+
generate demo conversations to try it out.
|
|
5
|
+
|
|
6
|
+
## Purpose
|
|
7
|
+
|
|
8
|
+
Download the chat completions already stored in *your own* OpenAI
|
|
9
|
+
account (completions created with `store=True`) as local JSONL trace
|
|
10
|
+
records — useful for auditing, backups, or feeding into other tooling.
|
|
11
|
+
This tool only reads what's associated with the API key you provide; it
|
|
12
|
+
can't see or export anyone else's data.
|
|
13
|
+
|
|
14
|
+
Built on OpenAI's [List Chat Completions API](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/list),
|
|
15
|
+
which returns completions that were created with `store: true`. See the
|
|
16
|
+
[official OpenAI API reference](https://developers.openai.com/api/reference/chat-completions/overview)
|
|
17
|
+
for the underlying data model.
|
|
18
|
+
|
|
19
|
+
## Setup
|
|
20
|
+
|
|
21
|
+
pip install -e ".[dev]"
|
|
22
|
+
cp .env.example .env
|
|
23
|
+
# edit .env and set OPENAI_API_KEY
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
Generate 1-2 demo conversations (stored with `store=True`) so there's
|
|
28
|
+
data to pull:
|
|
29
|
+
|
|
30
|
+
metergraphrelay demo openai
|
|
31
|
+
|
|
32
|
+
Pull the 10 most recent stored chat completions into `traces.jsonl`,
|
|
33
|
+
already shaped as metergraph trace records:
|
|
34
|
+
|
|
35
|
+
metergraphrelay pull openai
|
|
36
|
+
|
|
37
|
+
Options:
|
|
38
|
+
|
|
39
|
+
metergraphrelay pull openai -n 25 --output my-traces.jsonl --stdout --include-content --route my-app/support-bot
|
|
40
|
+
metergraphrelay demo openai --model gpt-4o-mini
|
|
41
|
+
|
|
42
|
+
Push a local JSONL file of traces to metergraph:
|
|
43
|
+
|
|
44
|
+
metergraphrelay push traces.jsonl
|
|
45
|
+
|
|
46
|
+
`pull anthropic` and `pull langfuse` accept the same shape but are not
|
|
47
|
+
yet implemented in this version — they check for `ANTHROPIC_API_KEY` /
|
|
48
|
+
`LANGFUSE_PUBLIC_KEY`+`LANGFUSE_SECRET_KEY` and report accordingly.
|
|
49
|
+
|
|
50
|
+
All subcommands accept `--env-file PATH` to point at a config file
|
|
51
|
+
other than `./.env`.
|
|
52
|
+
|
|
53
|
+
## Using it against your real system (not just the demo)
|
|
54
|
+
|
|
55
|
+
`metergraphrelay pull openai` only finds completions that were created
|
|
56
|
+
with `store=True`. The `demo openai` subcommand sets that flag for you,
|
|
57
|
+
but for your own application to show up in a pull, its own OpenAI calls
|
|
58
|
+
need the same flag. The only change required is adding `store=True`
|
|
59
|
+
(and, optionally, `metadata` to help you tell requests apart later) to
|
|
60
|
+
calls you're already making:
|
|
61
|
+
|
|
62
|
+
from openai import OpenAI
|
|
63
|
+
|
|
64
|
+
client = OpenAI()
|
|
65
|
+
|
|
66
|
+
response = client.chat.completions.create(
|
|
67
|
+
model="gpt-4o-mini",
|
|
68
|
+
messages=[{"role": "user", "content": "..."}],
|
|
69
|
+
store=True, # <-- persists this completion for later pulling
|
|
70
|
+
metadata={"source": "my-app"}, # optional: filter/identify later via the API
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
No other code changes are needed — the request and response are handled
|
|
74
|
+
exactly as before. Once your app is sending `store=True`, its completions
|
|
75
|
+
become visible to `metergraphrelay pull openai` (or to the
|
|
76
|
+
[List Chat Completions API](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/list)
|
|
77
|
+
directly) using the same API key.
|
|
78
|
+
|
|
79
|
+
Two things worth knowing before flipping this on in production:
|
|
80
|
+
- Stored completions include full request/response content by default,
|
|
81
|
+
so treat them as you would any other place your data is retained.
|
|
82
|
+
- Storage has no automatic expiry from this tool's side — deletion is a
|
|
83
|
+
separate API call ([Delete chat completion](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/delete)),
|
|
84
|
+
not something `metergraphrelay` currently does.
|
|
85
|
+
|
|
86
|
+
## Trace record shape
|
|
87
|
+
|
|
88
|
+
Each line of `pull openai`'s output is a JSON object already shaped for
|
|
89
|
+
metergraph's ingest API:
|
|
90
|
+
|
|
91
|
+
{
|
|
92
|
+
"ts": "2026-07-30T12:00:00+00:00",
|
|
93
|
+
"provider": "openai",
|
|
94
|
+
"model": "gpt-4o-mini",
|
|
95
|
+
"status": "success",
|
|
96
|
+
"endpoint": "chat.completions",
|
|
97
|
+
"input_tokens": 12,
|
|
98
|
+
"output_tokens": 34,
|
|
99
|
+
"error": false,
|
|
100
|
+
"error_type": null,
|
|
101
|
+
"request_id": "chatcmpl-...",
|
|
102
|
+
"tags": {},
|
|
103
|
+
"route": "openai/backfill",
|
|
104
|
+
"content_opted_in": false,
|
|
105
|
+
"request_json": null,
|
|
106
|
+
"response_text": null,
|
|
107
|
+
"sdk": "metergraphrelay",
|
|
108
|
+
"sdk_version": "0.1.0"
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
`request_json`/`response_text` are populated only when `--include-content`
|
|
112
|
+
is passed.
|
|
113
|
+
|
|
114
|
+
Every completion returned by the stored-completions list already succeeded, so
|
|
115
|
+
`status` is always `"success"`. `error`/`error_type` flag a *partial* record:
|
|
116
|
+
`--include-content` was requested but the follow-up message fetch failed, so
|
|
117
|
+
token counts are still real while the content is missing.
|
|
118
|
+
|
|
119
|
+
## Running tests
|
|
120
|
+
|
|
121
|
+
pytest
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "metergraphrelay"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Move LLM trace data between systems: pull from providers, push to metergraph."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Vasiliy Radostev" }]
|
|
13
|
+
keywords = ["llm", "openai", "observability", "cost-tracking", "cli", "metergraph"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"openai>=1.63.0",
|
|
22
|
+
"python-dotenv>=1.0",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/VasiliyRad/metergraphrelay"
|
|
27
|
+
Repository = "https://github.com/VasiliyRad/metergraphrelay"
|
|
28
|
+
Issues = "https://github.com/VasiliyRad/metergraphrelay/issues"
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
dev = ["pytest>=8.0"]
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
metergraphrelay = "metergraphrelay.cli:main"
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.packages.find]
|
|
37
|
+
where = ["src"]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from openai import OpenAI
|
|
8
|
+
|
|
9
|
+
from .config import ConfigError, require_credentials
|
|
10
|
+
from .demo import run_demo
|
|
11
|
+
from .providers.openai import pull_openai
|
|
12
|
+
from .push import push_file
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
parser = argparse.ArgumentParser(prog="metergraphrelay")
|
|
17
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
18
|
+
|
|
19
|
+
pull_parser = subparsers.add_parser(
|
|
20
|
+
"pull", help="Pull trace data from a provider into a local JSONL file"
|
|
21
|
+
)
|
|
22
|
+
pull_subparsers = pull_parser.add_subparsers(dest="provider", required=True)
|
|
23
|
+
|
|
24
|
+
pull_openai_parser = pull_subparsers.add_parser("openai")
|
|
25
|
+
pull_openai_parser.add_argument("-n", "--count", type=int, default=10)
|
|
26
|
+
pull_openai_parser.add_argument("--output", default="traces.jsonl")
|
|
27
|
+
pull_openai_parser.add_argument("--stdout", action="store_true")
|
|
28
|
+
pull_openai_parser.add_argument("--route", default="openai/backfill")
|
|
29
|
+
pull_openai_parser.add_argument("--include-content", action="store_true")
|
|
30
|
+
pull_openai_parser.add_argument("--env-file", default=".env")
|
|
31
|
+
|
|
32
|
+
pull_anthropic_parser = pull_subparsers.add_parser("anthropic")
|
|
33
|
+
pull_anthropic_parser.add_argument("-n", "--count", type=int, default=10)
|
|
34
|
+
pull_anthropic_parser.add_argument("--output", default="traces.jsonl")
|
|
35
|
+
pull_anthropic_parser.add_argument("--env-file", default=".env")
|
|
36
|
+
|
|
37
|
+
pull_langfuse_parser = pull_subparsers.add_parser("langfuse")
|
|
38
|
+
pull_langfuse_parser.add_argument("--output", default="traces.jsonl")
|
|
39
|
+
pull_langfuse_parser.add_argument("--env-file", default=".env")
|
|
40
|
+
|
|
41
|
+
demo_parser = subparsers.add_parser(
|
|
42
|
+
"demo", help="Run 1-2 demo conversations with store=True"
|
|
43
|
+
)
|
|
44
|
+
demo_subparsers = demo_parser.add_subparsers(dest="provider", required=True)
|
|
45
|
+
demo_openai_parser = demo_subparsers.add_parser("openai")
|
|
46
|
+
demo_openai_parser.add_argument("--model", default="gpt-4o-mini")
|
|
47
|
+
demo_openai_parser.add_argument("--env-file", default=".env")
|
|
48
|
+
|
|
49
|
+
push_parser = subparsers.add_parser(
|
|
50
|
+
"push", help="Push a local JSONL file of traces to metergraph"
|
|
51
|
+
)
|
|
52
|
+
push_parser.add_argument("file")
|
|
53
|
+
push_parser.add_argument("--env-file", default=".env")
|
|
54
|
+
|
|
55
|
+
return parser
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _config_error(exc: ConfigError) -> int:
|
|
59
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
60
|
+
return 1
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _os_error(exc: OSError) -> int:
|
|
64
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
65
|
+
return 1
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _not_implemented(provider: str) -> int:
|
|
69
|
+
print(
|
|
70
|
+
f"Error: pulling from {provider} is not implemented in this version.",
|
|
71
|
+
file=sys.stderr,
|
|
72
|
+
)
|
|
73
|
+
return 1
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def main(argv: list[str] | None = None) -> int:
|
|
77
|
+
parser = build_parser()
|
|
78
|
+
args = parser.parse_args(argv)
|
|
79
|
+
|
|
80
|
+
if args.command == "pull" and args.provider in {"anthropic", "langfuse"}:
|
|
81
|
+
try:
|
|
82
|
+
require_credentials(args.provider, args.env_file)
|
|
83
|
+
except ConfigError as exc:
|
|
84
|
+
return _config_error(exc)
|
|
85
|
+
return _not_implemented(args.provider)
|
|
86
|
+
|
|
87
|
+
if args.command == "pull" and args.provider == "openai":
|
|
88
|
+
try:
|
|
89
|
+
creds = require_credentials("openai", args.env_file)
|
|
90
|
+
except ConfigError as exc:
|
|
91
|
+
return _config_error(exc)
|
|
92
|
+
client = OpenAI(api_key=creds["OPENAI_API_KEY"])
|
|
93
|
+
try:
|
|
94
|
+
written = pull_openai(
|
|
95
|
+
client,
|
|
96
|
+
args.count,
|
|
97
|
+
args.output,
|
|
98
|
+
route=args.route,
|
|
99
|
+
include_content=args.include_content,
|
|
100
|
+
echo_stdout=args.stdout,
|
|
101
|
+
)
|
|
102
|
+
except OSError as exc:
|
|
103
|
+
return _os_error(exc)
|
|
104
|
+
if written == 0:
|
|
105
|
+
print("No stored completions found. Try `metergraphrelay demo openai` first.")
|
|
106
|
+
else:
|
|
107
|
+
print(f"Wrote {written} trace(s) to {args.output}")
|
|
108
|
+
return 0
|
|
109
|
+
|
|
110
|
+
if args.command == "demo" and args.provider == "openai":
|
|
111
|
+
try:
|
|
112
|
+
creds = require_credentials("openai", args.env_file)
|
|
113
|
+
except ConfigError as exc:
|
|
114
|
+
return _config_error(exc)
|
|
115
|
+
client = OpenAI(api_key=creds["OPENAI_API_KEY"])
|
|
116
|
+
run_demo(client, model=args.model)
|
|
117
|
+
return 0
|
|
118
|
+
|
|
119
|
+
if args.command == "push":
|
|
120
|
+
try:
|
|
121
|
+
creds = require_credentials("push", args.env_file)
|
|
122
|
+
except ConfigError as exc:
|
|
123
|
+
return _config_error(exc)
|
|
124
|
+
base_url = os.environ.get("METERGRAPH_INGEST_URL")
|
|
125
|
+
try:
|
|
126
|
+
succeeded, failed = push_file(
|
|
127
|
+
args.file, creds["METERGRAPH_APP_TOKEN"], base_url=base_url
|
|
128
|
+
)
|
|
129
|
+
except OSError as exc:
|
|
130
|
+
return _os_error(exc)
|
|
131
|
+
if failed:
|
|
132
|
+
print(f"Pushed {succeeded} row(s), {failed} failed.", file=sys.stderr)
|
|
133
|
+
return 1
|
|
134
|
+
print(f"Pushed {succeeded} row(s) to metergraph.")
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
return 1
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
if __name__ == "__main__":
|
|
141
|
+
sys.exit(main())
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from dotenv import load_dotenv
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ConfigError(Exception):
|
|
9
|
+
"""Raised when required configuration is missing or invalid."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
CREDENTIAL_SPECS: dict[str, list[str]] = {
|
|
13
|
+
"openai": ["OPENAI_API_KEY"],
|
|
14
|
+
"anthropic": ["ANTHROPIC_API_KEY"],
|
|
15
|
+
"langfuse": ["LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY"],
|
|
16
|
+
"push": ["METERGRAPH_APP_TOKEN"],
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def require_credentials(target: str, env_file: str = ".env") -> dict[str, str]:
|
|
21
|
+
load_dotenv(env_file, override=True)
|
|
22
|
+
var_names = CREDENTIAL_SPECS[target]
|
|
23
|
+
values: dict[str, str] = {}
|
|
24
|
+
missing: list[str] = []
|
|
25
|
+
for name in var_names:
|
|
26
|
+
value = os.environ.get(name, "").strip()
|
|
27
|
+
if value:
|
|
28
|
+
values[name] = value
|
|
29
|
+
else:
|
|
30
|
+
missing.append(name)
|
|
31
|
+
if missing:
|
|
32
|
+
joined = ", ".join(missing)
|
|
33
|
+
raise ConfigError(
|
|
34
|
+
f"{joined} not set. Add {'it' if len(missing) == 1 else 'them'} to "
|
|
35
|
+
f"{env_file} (see .env.example) or export in your shell."
|
|
36
|
+
)
|
|
37
|
+
return values
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
DEMO_PROMPTS = [
|
|
6
|
+
"Say hello in one sentence.",
|
|
7
|
+
"What's 2+2?",
|
|
8
|
+
]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def run_demo(client: Any, *, model: str = "gpt-4o-mini") -> list[dict]:
|
|
12
|
+
results = []
|
|
13
|
+
for prompt in DEMO_PROMPTS:
|
|
14
|
+
completion = client.chat.completions.create(
|
|
15
|
+
model=model,
|
|
16
|
+
store=True,
|
|
17
|
+
messages=[{"role": "user", "content": prompt}],
|
|
18
|
+
)
|
|
19
|
+
reply = completion.choices[0].message.content
|
|
20
|
+
print(f"> {prompt}\n{reply}\n")
|
|
21
|
+
results.append({"prompt": prompt, "reply": reply})
|
|
22
|
+
return results
|
|
File without changes
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from itertools import islice
|
|
7
|
+
from typing import Any, Iterable
|
|
8
|
+
|
|
9
|
+
from .. import __version__
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def normalize_completion(
|
|
13
|
+
completion: Any,
|
|
14
|
+
messages: Iterable[Any],
|
|
15
|
+
*,
|
|
16
|
+
route: str,
|
|
17
|
+
include_content: bool,
|
|
18
|
+
content_fetch_error: Exception | None = None,
|
|
19
|
+
) -> dict:
|
|
20
|
+
usage = getattr(completion, "usage", None)
|
|
21
|
+
tags = getattr(completion, "metadata", None) or {}
|
|
22
|
+
ts = datetime.fromtimestamp(completion.created, tz=timezone.utc).isoformat()
|
|
23
|
+
message_list = list(messages)
|
|
24
|
+
|
|
25
|
+
content_opted_in = include_content and content_fetch_error is None
|
|
26
|
+
request_json: str | None = None
|
|
27
|
+
response_text: str | None = None
|
|
28
|
+
if content_opted_in:
|
|
29
|
+
if message_list and message_list[-1].role == "assistant":
|
|
30
|
+
response_text = message_list[-1].content
|
|
31
|
+
request_messages = message_list[:-1]
|
|
32
|
+
else:
|
|
33
|
+
request_messages = message_list
|
|
34
|
+
request_json = json.dumps(
|
|
35
|
+
[{"role": m.role, "content": m.content} for m in request_messages]
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
"ts": ts,
|
|
40
|
+
"provider": "openai",
|
|
41
|
+
"model": completion.model,
|
|
42
|
+
"status": "success",
|
|
43
|
+
"endpoint": "chat.completions",
|
|
44
|
+
"input_tokens": getattr(usage, "prompt_tokens", None) if usage else None,
|
|
45
|
+
"output_tokens": getattr(usage, "completion_tokens", None) if usage else None,
|
|
46
|
+
"error": content_fetch_error is not None,
|
|
47
|
+
"error_type": (
|
|
48
|
+
type(content_fetch_error).__name__ if content_fetch_error else None
|
|
49
|
+
),
|
|
50
|
+
"request_id": completion.id,
|
|
51
|
+
"tags": tags,
|
|
52
|
+
"route": route,
|
|
53
|
+
"content_opted_in": content_opted_in,
|
|
54
|
+
"request_json": request_json,
|
|
55
|
+
"response_text": response_text,
|
|
56
|
+
"sdk": "metergraphrelay",
|
|
57
|
+
"sdk_version": __version__,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def pull_openai(
|
|
62
|
+
client: Any,
|
|
63
|
+
count: int,
|
|
64
|
+
output_path: str,
|
|
65
|
+
*,
|
|
66
|
+
route: str,
|
|
67
|
+
include_content: bool,
|
|
68
|
+
echo_stdout: bool = False,
|
|
69
|
+
) -> int:
|
|
70
|
+
page = client.chat.completions.list(order="desc", limit=count)
|
|
71
|
+
completions = list(islice(iter(page), count))
|
|
72
|
+
written = 0
|
|
73
|
+
with open(output_path, "w") as f:
|
|
74
|
+
for completion in completions:
|
|
75
|
+
if not include_content:
|
|
76
|
+
row = normalize_completion(
|
|
77
|
+
completion, [], route=route, include_content=include_content
|
|
78
|
+
)
|
|
79
|
+
else:
|
|
80
|
+
try:
|
|
81
|
+
messages = client.chat.completions.messages.list(completion.id)
|
|
82
|
+
except Exception as exc:
|
|
83
|
+
print(
|
|
84
|
+
f"Warning: could not fetch messages for {completion.id}: {exc}",
|
|
85
|
+
file=sys.stderr,
|
|
86
|
+
)
|
|
87
|
+
row = normalize_completion(
|
|
88
|
+
completion, [], route=route, include_content=include_content,
|
|
89
|
+
content_fetch_error=exc,
|
|
90
|
+
)
|
|
91
|
+
else:
|
|
92
|
+
row = normalize_completion(
|
|
93
|
+
completion, messages, route=route,
|
|
94
|
+
include_content=include_content,
|
|
95
|
+
)
|
|
96
|
+
line = json.dumps(row)
|
|
97
|
+
f.write(line + "\n")
|
|
98
|
+
if echo_stdout:
|
|
99
|
+
print(line)
|
|
100
|
+
written += 1
|
|
101
|
+
return written
|