Skip to content

Commit 0dd41f0

Browse files
authored
fix(api): preserve legacy score create alias (#1786)
1 parent a8e3efa commit 0dd41f0

2 files changed

Lines changed: 418 additions & 0 deletions

File tree

Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
#!/usr/bin/env python3
2+
"""Preserve the legacy score-create API after Fern moves it to ``scores``.
3+
4+
Fern owns ``langfuse/api`` and regenerates it from the main Langfuse repository.
5+
This postprocessor is intentionally narrow and fail-closed: it only patches the
6+
known generated shape where ``scores.create`` exists and
7+
``legacy.score_v1.create`` no longer does.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import argparse
13+
from pathlib import Path
14+
15+
CLIENT_IMPORTS = """\
16+
from ...commons.types.create_score_value import CreateScoreValue
17+
from ...commons.types.score_data_type import ScoreDataType
18+
from ...scores.client import (
19+
AsyncScoresClient as CanonicalAsyncScoresClient,
20+
ScoresClient as CanonicalScoresClient,
21+
OMIT,
22+
)
23+
from ...scores.types.create_score_response import CreateScoreResponse
24+
from ...scores.types.create_score_source import CreateScoreSource
25+
"""
26+
27+
SYNC_CREATE_METHOD = '''\
28+
def create(
29+
self,
30+
*,
31+
name: str,
32+
value: CreateScoreValue,
33+
id: typing.Optional[str] = OMIT,
34+
trace_id: typing.Optional[str] = OMIT,
35+
session_id: typing.Optional[str] = OMIT,
36+
observation_id: typing.Optional[str] = OMIT,
37+
dataset_run_id: typing.Optional[str] = OMIT,
38+
comment: typing.Optional[str] = OMIT,
39+
metadata: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
40+
environment: typing.Optional[str] = OMIT,
41+
queue_id: typing.Optional[str] = OMIT,
42+
data_type: typing.Optional[ScoreDataType] = OMIT,
43+
config_id: typing.Optional[str] = OMIT,
44+
source: typing.Optional[CreateScoreSource] = OMIT,
45+
request_options: typing.Optional[RequestOptions] = None,
46+
) -> CreateScoreResponse:
47+
"""**Deprecated compatibility alias.** Use ``client.scores.create``."""
48+
return CanonicalScoresClient(
49+
client_wrapper=self._raw_client._client_wrapper
50+
).create(
51+
name=name,
52+
value=value,
53+
id=id,
54+
trace_id=trace_id,
55+
session_id=session_id,
56+
observation_id=observation_id,
57+
dataset_run_id=dataset_run_id,
58+
comment=comment,
59+
metadata=metadata,
60+
environment=environment,
61+
queue_id=queue_id,
62+
data_type=data_type,
63+
config_id=config_id,
64+
source=source,
65+
request_options=request_options,
66+
)
67+
68+
'''
69+
70+
ASYNC_CREATE_METHOD = '''\
71+
async def create(
72+
self,
73+
*,
74+
name: str,
75+
value: CreateScoreValue,
76+
id: typing.Optional[str] = OMIT,
77+
trace_id: typing.Optional[str] = OMIT,
78+
session_id: typing.Optional[str] = OMIT,
79+
observation_id: typing.Optional[str] = OMIT,
80+
dataset_run_id: typing.Optional[str] = OMIT,
81+
comment: typing.Optional[str] = OMIT,
82+
metadata: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
83+
environment: typing.Optional[str] = OMIT,
84+
queue_id: typing.Optional[str] = OMIT,
85+
data_type: typing.Optional[ScoreDataType] = OMIT,
86+
config_id: typing.Optional[str] = OMIT,
87+
source: typing.Optional[CreateScoreSource] = OMIT,
88+
request_options: typing.Optional[RequestOptions] = None,
89+
) -> CreateScoreResponse:
90+
"""**Deprecated compatibility alias.** Use ``client.scores.create``."""
91+
return await CanonicalAsyncScoresClient(
92+
client_wrapper=self._raw_client._client_wrapper
93+
).create(
94+
name=name,
95+
value=value,
96+
id=id,
97+
trace_id=trace_id,
98+
session_id=session_id,
99+
observation_id=observation_id,
100+
dataset_run_id=dataset_run_id,
101+
comment=comment,
102+
metadata=metadata,
103+
environment=environment,
104+
queue_id=queue_id,
105+
data_type=data_type,
106+
config_id=config_id,
107+
source=source,
108+
request_options=request_options,
109+
)
110+
111+
'''
112+
113+
TYPE_NAMES = (
114+
"CreateScoreRequest",
115+
"CreateScoreResponse",
116+
"CreateScoreSource",
117+
)
118+
LEGACY_ALIAS_MARKER = (
119+
"**Deprecated compatibility alias.** Use ``client.scores.create``."
120+
)
121+
122+
123+
def _replace_once(contents: str, marker: str, replacement: str, *, path: Path) -> str:
124+
count = contents.count(marker)
125+
if count != 1:
126+
raise RuntimeError(
127+
f"Expected exactly one compatibility marker in {path}: {marker!r}; "
128+
f"found {count}"
129+
)
130+
return contents.replace(marker, replacement, 1)
131+
132+
133+
def _append_type_exports(path: Path, imports_by_type: dict[str, str]) -> None:
134+
exports_marker = "# Score-create compatibility aliases (LFE-10397)."
135+
contents = path.read_text()
136+
if exports_marker in contents:
137+
return
138+
139+
imports = "\n".join(
140+
f"from {module_name} import {type_name}"
141+
for type_name, module_name in imports_by_type.items()
142+
)
143+
names = ", ".join(repr(type_name) for type_name in TYPE_NAMES)
144+
path.write_text(
145+
f"{contents.rstrip()}\n\n{exports_marker}\n{imports}\n"
146+
f"__all__ = [*__all__, {names}]\n"
147+
)
148+
149+
150+
def _create_type_aliases(types_dir: Path) -> None:
151+
types_dir.mkdir(parents=True, exist_ok=True)
152+
for type_name in TYPE_NAMES:
153+
module_name = "".join(
154+
f"_{character.lower()}" if character.isupper() else character
155+
for character in type_name
156+
).lstrip("_")
157+
alias_path = types_dir / f"{module_name}.py"
158+
alias_path.write_text(
159+
"# This compatibility alias is applied after Fern generation.\n\n"
160+
f"from ....scores.types.{module_name} import {type_name}\n\n"
161+
f'__all__ = ["{type_name}"]\n'
162+
)
163+
164+
165+
def patch_generated_api(api_root: Path) -> bool:
166+
canonical_client_path = api_root / "scores" / "client.py"
167+
legacy_client_path = api_root / "legacy" / "score_v1" / "client.py"
168+
169+
canonical_client = canonical_client_path.read_text()
170+
legacy_client = legacy_client_path.read_text()
171+
172+
canonical_has_create = (
173+
"\n def create(" in canonical_client
174+
and "\n async def create(" in canonical_client
175+
)
176+
legacy_has_create = (
177+
"\n def create(" in legacy_client
178+
and "\n async def create(" in legacy_client
179+
)
180+
181+
if legacy_has_create:
182+
if LEGACY_ALIAS_MARKER in legacy_client and canonical_has_create:
183+
return False
184+
if canonical_has_create:
185+
raise RuntimeError(
186+
"Both canonical and legacy generated score clients define create; "
187+
"refusing to introduce a third compatibility surface"
188+
)
189+
return False
190+
191+
if not canonical_has_create:
192+
raise RuntimeError(
193+
"Neither generated score client defines both sync and async create methods"
194+
)
195+
196+
legacy_client = _replace_once(
197+
legacy_client,
198+
"from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper\n",
199+
"from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper\n"
200+
f"{CLIENT_IMPORTS}",
201+
path=legacy_client_path,
202+
)
203+
legacy_client = _replace_once(
204+
legacy_client,
205+
"\n def delete(",
206+
f"\n{SYNC_CREATE_METHOD} def delete(",
207+
path=legacy_client_path,
208+
)
209+
legacy_client = _replace_once(
210+
legacy_client,
211+
"\n async def delete(",
212+
f"\n{ASYNC_CREATE_METHOD} async def delete(",
213+
path=legacy_client_path,
214+
)
215+
legacy_client_path.write_text(legacy_client)
216+
217+
legacy_package_path = api_root / "legacy" / "score_v1" / "__init__.py"
218+
legacy_parent_package_path = api_root / "legacy" / "__init__.py"
219+
legacy_types_path = api_root / "legacy" / "score_v1" / "types" / "__init__.py"
220+
_create_type_aliases(legacy_types_path.parent)
221+
222+
if not legacy_types_path.exists():
223+
legacy_types_path.write_text(
224+
"# This package is generated by Fern and extended for compatibility.\n\n"
225+
"__all__: list[str] = []\n"
226+
)
227+
228+
_append_type_exports(
229+
legacy_types_path,
230+
{
231+
"CreateScoreRequest": ".create_score_request",
232+
"CreateScoreResponse": ".create_score_response",
233+
"CreateScoreSource": ".create_score_source",
234+
},
235+
)
236+
_append_type_exports(
237+
legacy_package_path, {type_name: ".types" for type_name in TYPE_NAMES}
238+
)
239+
_append_type_exports(
240+
legacy_parent_package_path,
241+
{type_name: ".score_v1" for type_name in TYPE_NAMES},
242+
)
243+
return True
244+
245+
246+
def main() -> None:
247+
parser = argparse.ArgumentParser()
248+
parser.add_argument(
249+
"--api-root",
250+
type=Path,
251+
default=Path("langfuse/api"),
252+
help="Path to the freshly generated Fern Python package",
253+
)
254+
args = parser.parse_args()
255+
changed = patch_generated_api(args.api_root)
256+
print(
257+
"Patched legacy score create compatibility alias."
258+
if changed
259+
else "No patch needed."
260+
)
261+
262+
263+
if __name__ == "__main__":
264+
main()

0 commit comments

Comments
 (0)