fastdecisions 0.0.1__py3-none-any.whl
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.
- fastdecisions/__init__.py +11 -0
- fastdecisions/_modidx.py +142 -0
- fastdecisions/core.py +175 -0
- fastdecisions/gemini.py +125 -0
- fastdecisions/openai.py +233 -0
- fastdecisions/specs/gemini.json +84 -0
- fastdecisions/specs/jev.json +117 -0
- fastdecisions/specs/openai.json +42 -0
- fastdecisions/types.py +315 -0
- fastdecisions/typesafe.py +118 -0
- fastdecisions/utils.py +306 -0
- fastdecisions-0.0.1.dist-info/METADATA +179 -0
- fastdecisions-0.0.1.dist-info/RECORD +17 -0
- fastdecisions-0.0.1.dist-info/WHEEL +5 -0
- fastdecisions-0.0.1.dist-info/entry_points.txt +5 -0
- fastdecisions-0.0.1.dist-info/licenses/LICENSE +201 -0
- fastdecisions-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Unified async Python client for decision models (Jev, Gemini, OpenAI)
|
|
2
|
+
|
|
3
|
+
`fastdecisions` provides a single Jev-style async interface for decision models across TypeSafe Jev (`jev-1.14.0`), Google Gemini (`gemini-decision-1`), and OpenAI (`gpt-6-luna`). Pass shared evidence—text, JSON, `aidialog.msg_parts.Msg` chat histories, or media—alongside batched `noul` (yes/no probability), `choice` (classification), `score` (rubric rating), or `box` (bounding box) questions, and swap providers with a single `model=` argument. Each provider adapter runs on `fastspec.OpenAPIClient` with offline bundled specs."""
|
|
4
|
+
|
|
5
|
+
__version__ = "0.0.1"
|
|
6
|
+
|
|
7
|
+
from fasttransport.errors import APIError
|
|
8
|
+
from .core import adecide, decide, Decider
|
|
9
|
+
from .types import (noul, choice, score, box, jev, gem_dec, luna,
|
|
10
|
+
Decision, NoulAnswer, ChoiceAnswer, ScoreAnswer, BoxAnswer, RefusalAnswer)
|
|
11
|
+
from .utils import Usage, Provider, providers, register_provider, ContextWindowExceededError
|
fastdecisions/_modidx.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Autogenerated by nbdev
|
|
2
|
+
|
|
3
|
+
d = { 'syms': { 'fastdecisions.core': { 'fastdecisions.core.resolve_provider': ('adecide.html#resolve_provider', 'fastdecisions/core.py'),
|
|
4
|
+
'fastdecisions.core.mk_client': ('adecide.html#mk_client', 'fastdecisions/core.py'),
|
|
5
|
+
'fastdecisions.core._norm_questions': ('adecide.html#_norm_questions', 'fastdecisions/core.py'),
|
|
6
|
+
'fastdecisions.core._check_opts': ('adecide.html#_check_opts', 'fastdecisions/core.py'),
|
|
7
|
+
'fastdecisions.core.adecide': ('adecide.html#adecide', 'fastdecisions/core.py'),
|
|
8
|
+
'fastdecisions.core.decide': ('adecide.html#decide', 'fastdecisions/core.py'),
|
|
9
|
+
'fastdecisions.core.Decider': ('adecide.html#decider', 'fastdecisions/core.py'),
|
|
10
|
+
'fastdecisions.core.Decider.__init__': ('adecide.html#decider.__init__', 'fastdecisions/core.py'),
|
|
11
|
+
'fastdecisions.core.Decider.__repr__': ('adecide.html#decider.__repr__', 'fastdecisions/core.py'),
|
|
12
|
+
'fastdecisions.core.Decider.__call__': ('adecide.html#decider.__call__', 'fastdecisions/core.py'),
|
|
13
|
+
'fastdecisions.core.Decider.batch': ('adecide.html#decider.batch', 'fastdecisions/core.py')},
|
|
14
|
+
'fastdecisions.gemini': { 'fastdecisions.gemini._media_block': ('gemini.html#_media_block', 'fastdecisions/gemini.py'),
|
|
15
|
+
'fastdecisions.gemini.prep_gemini_input': ( 'gemini.html#prep_gemini_input',
|
|
16
|
+
'fastdecisions/gemini.py'),
|
|
17
|
+
'fastdecisions.gemini._as_str': ('gemini.html#_as_str', 'fastdecisions/gemini.py'),
|
|
18
|
+
'fastdecisions.gemini._gemini_question': ('gemini.html#_gemini_question', 'fastdecisions/gemini.py'),
|
|
19
|
+
'fastdecisions.gemini._mk_payload': ('gemini.html#_mk_payload', 'fastdecisions/gemini.py'),
|
|
20
|
+
'fastdecisions.gemini._norm_usage': ('gemini.html#_norm_usage', 'fastdecisions/gemini.py'),
|
|
21
|
+
'fastdecisions.gemini._norm_response': ('gemini.html#_norm_response', 'fastdecisions/gemini.py')},
|
|
22
|
+
'fastdecisions.openai': { 'fastdecisions.openai._sanid': ('openai.html#_sanid', 'fastdecisions/openai.py'),
|
|
23
|
+
'fastdecisions.openai._img_part': ('openai.html#_img_part', 'fastdecisions/openai.py'),
|
|
24
|
+
'fastdecisions.openai._lower_oai': ('openai.html#_lower_oai', 'fastdecisions/openai.py'),
|
|
25
|
+
'fastdecisions.openai._json_parts': ('openai.html#_json_parts', 'fastdecisions/openai.py'),
|
|
26
|
+
'fastdecisions.openai._user_parts': ('openai.html#_user_parts', 'fastdecisions/openai.py'),
|
|
27
|
+
'fastdecisions.openai._tool_result_item': ( 'openai.html#_tool_result_item',
|
|
28
|
+
'fastdecisions/openai.py'),
|
|
29
|
+
'fastdecisions.openai._assistant_items': ('openai.html#_assistant_items', 'fastdecisions/openai.py'),
|
|
30
|
+
'fastdecisions.openai._msgs_to_openai': ('openai.html#_msgs_to_openai', 'fastdecisions/openai.py'),
|
|
31
|
+
'fastdecisions.openai.prep_openai_input': ( 'openai.html#prep_openai_input',
|
|
32
|
+
'fastdecisions/openai.py'),
|
|
33
|
+
'fastdecisions.openai._str_val': ('openai.html#_str_val', 'fastdecisions/openai.py'),
|
|
34
|
+
'fastdecisions.openai._fold_noul_criteria': ( 'openai.html#_fold_noul_criteria',
|
|
35
|
+
'fastdecisions/openai.py'),
|
|
36
|
+
'fastdecisions.openai._openai_question': ('openai.html#_openai_question', 'fastdecisions/openai.py'),
|
|
37
|
+
'fastdecisions.openai._mk_payload': ('openai.html#_mk_payload', 'fastdecisions/openai.py'),
|
|
38
|
+
'fastdecisions.openai._norm_usage': ('openai.html#_norm_usage', 'fastdecisions/openai.py'),
|
|
39
|
+
'fastdecisions.openai._norm_openai_answer': ( 'openai.html#_norm_openai_answer',
|
|
40
|
+
'fastdecisions/openai.py'),
|
|
41
|
+
'fastdecisions.openai._norm_response': ('openai.html#_norm_response', 'fastdecisions/openai.py')},
|
|
42
|
+
'fastdecisions.types': { 'fastdecisions.types._check_noul_criteria': ( 'types.html#_check_noul_criteria',
|
|
43
|
+
'fastdecisions/types.py'),
|
|
44
|
+
'fastdecisions.types.noul': ('types.html#noul', 'fastdecisions/types.py'),
|
|
45
|
+
'fastdecisions.types.choice': ('types.html#choice', 'fastdecisions/types.py'),
|
|
46
|
+
'fastdecisions.types.score': ('types.html#score', 'fastdecisions/types.py'),
|
|
47
|
+
'fastdecisions.types.box': ('types.html#box', 'fastdecisions/types.py'),
|
|
48
|
+
'fastdecisions.types.score_criteria_list': ( 'types.html#score_criteria_list',
|
|
49
|
+
'fastdecisions/types.py'),
|
|
50
|
+
'fastdecisions.types.norm_question': ('types.html#norm_question', 'fastdecisions/types.py'),
|
|
51
|
+
'fastdecisions.types._Answer': ('types.html#_answer', 'fastdecisions/types.py'),
|
|
52
|
+
'fastdecisions.types._Answer.__init__': ('types.html#_answer.__init__', 'fastdecisions/types.py'),
|
|
53
|
+
'fastdecisions.types._Answer.__eq__': ('types.html#_answer.__eq__', 'fastdecisions/types.py'),
|
|
54
|
+
'fastdecisions.types.NoulAnswer': ('types.html#noulanswer', 'fastdecisions/types.py'),
|
|
55
|
+
'fastdecisions.types.ChoiceAnswer': ('types.html#choiceanswer', 'fastdecisions/types.py'),
|
|
56
|
+
'fastdecisions.types.ScoreAnswer': ('types.html#scoreanswer', 'fastdecisions/types.py'),
|
|
57
|
+
'fastdecisions.types.NoulAnswer.__init__': ( 'types.html#noulanswer.__init__',
|
|
58
|
+
'fastdecisions/types.py'),
|
|
59
|
+
'fastdecisions.types.NoulAnswer._repr_markdown_': ( 'types.html#noulanswer._repr_markdown_',
|
|
60
|
+
'fastdecisions/types.py'),
|
|
61
|
+
'fastdecisions.types.ChoiceAnswer.__init__': ( 'types.html#choiceanswer.__init__',
|
|
62
|
+
'fastdecisions/types.py'),
|
|
63
|
+
'fastdecisions.types.ChoiceAnswer._repr_markdown_': ( 'types.html#choiceanswer._repr_markdown_',
|
|
64
|
+
'fastdecisions/types.py'),
|
|
65
|
+
'fastdecisions.types.ScoreAnswer.__init__': ( 'types.html#scoreanswer.__init__',
|
|
66
|
+
'fastdecisions/types.py'),
|
|
67
|
+
'fastdecisions.types.ScoreAnswer._repr_markdown_': ( 'types.html#scoreanswer._repr_markdown_',
|
|
68
|
+
'fastdecisions/types.py'),
|
|
69
|
+
'fastdecisions.types.BoxCoordinates': ('types.html#boxcoordinates', 'fastdecisions/types.py'),
|
|
70
|
+
'fastdecisions.types.BoxAnswer': ('types.html#boxanswer', 'fastdecisions/types.py'),
|
|
71
|
+
'fastdecisions.types.RefusalAnswer': ('types.html#refusalanswer', 'fastdecisions/types.py'),
|
|
72
|
+
'fastdecisions.types.BoxCoordinates.__init__': ( 'types.html#boxcoordinates.__init__',
|
|
73
|
+
'fastdecisions/types.py'),
|
|
74
|
+
'fastdecisions.types.BoxAnswer.__init__': ('types.html#boxanswer.__init__', 'fastdecisions/types.py'),
|
|
75
|
+
'fastdecisions.types.BoxAnswer._repr_markdown_': ( 'types.html#boxanswer._repr_markdown_',
|
|
76
|
+
'fastdecisions/types.py'),
|
|
77
|
+
'fastdecisions.types.RefusalAnswer._repr_markdown_': ( 'types.html#refusalanswer._repr_markdown_',
|
|
78
|
+
'fastdecisions/types.py'),
|
|
79
|
+
'fastdecisions.types.norm_answer': ('types.html#norm_answer', 'fastdecisions/types.py'),
|
|
80
|
+
'fastdecisions.types.check_answers': ('types.html#check_answers', 'fastdecisions/types.py'),
|
|
81
|
+
'fastdecisions.types.Decision': ('types.html#decision', 'fastdecisions/types.py'),
|
|
82
|
+
'fastdecisions.types.Decision.__init__': ('types.html#decision.__init__', 'fastdecisions/types.py'),
|
|
83
|
+
'fastdecisions.types.Decision.__getitem__': ( 'types.html#decision.__getitem__',
|
|
84
|
+
'fastdecisions/types.py'),
|
|
85
|
+
'fastdecisions.types.Decision.__iter__': ('types.html#decision.__iter__', 'fastdecisions/types.py'),
|
|
86
|
+
'fastdecisions.types.Decision.__len__': ('types.html#decision.__len__', 'fastdecisions/types.py'),
|
|
87
|
+
'fastdecisions.types.Decision.__eq__': ('types.html#decision.__eq__', 'fastdecisions/types.py'),
|
|
88
|
+
'fastdecisions.types.Decision.__getattr__': ( 'types.html#decision.__getattr__',
|
|
89
|
+
'fastdecisions/types.py'),
|
|
90
|
+
'fastdecisions.types.Decision.__dir__': ('types.html#decision.__dir__', 'fastdecisions/types.py'),
|
|
91
|
+
'fastdecisions.types.Decision.cost': ('types.html#decision.cost', 'fastdecisions/types.py'),
|
|
92
|
+
'fastdecisions.types._ans_summary': ('types.html#_ans_summary', 'fastdecisions/types.py'),
|
|
93
|
+
'fastdecisions.types.Decision._repr_markdown_': ( 'types.html#decision._repr_markdown_',
|
|
94
|
+
'fastdecisions/types.py'),
|
|
95
|
+
'fastdecisions.types.lower_state': ('types.html#lower_state', 'fastdecisions/types.py')},
|
|
96
|
+
'fastdecisions.typesafe': { 'fastdecisions.typesafe._img_bytes_fmt': ('jev.html#_img_bytes_fmt', 'fastdecisions/typesafe.py'),
|
|
97
|
+
'fastdecisions.typesafe._register_img': ('jev.html#_register_img', 'fastdecisions/typesafe.py'),
|
|
98
|
+
'fastdecisions.typesafe.prep_jev_state': ('jev.html#prep_jev_state', 'fastdecisions/typesafe.py'),
|
|
99
|
+
'fastdecisions.typesafe._jev_question': ('jev.html#_jev_question', 'fastdecisions/typesafe.py'),
|
|
100
|
+
'fastdecisions.typesafe._mk_payload': ('jev.html#_mk_payload', 'fastdecisions/typesafe.py'),
|
|
101
|
+
'fastdecisions.typesafe._req_hdrs': ('jev.html#_req_hdrs', 'fastdecisions/typesafe.py'),
|
|
102
|
+
'fastdecisions.typesafe._norm_usage': ('jev.html#_norm_usage', 'fastdecisions/typesafe.py'),
|
|
103
|
+
'fastdecisions.typesafe._norm_response': ('jev.html#_norm_response', 'fastdecisions/typesafe.py')},
|
|
104
|
+
'fastdecisions.utils': { 'fastdecisions.utils.Usage': ('utils.html#usage', 'fastdecisions/utils.py'),
|
|
105
|
+
'fastdecisions.utils.Usage.__init__': ('utils.html#usage.__init__', 'fastdecisions/utils.py'),
|
|
106
|
+
'fastdecisions.utils.Usage.__eq__': ('utils.html#usage.__eq__', 'fastdecisions/utils.py'),
|
|
107
|
+
'fastdecisions.utils.Usage.__add__': ('utils.html#usage.__add__', 'fastdecisions/utils.py'),
|
|
108
|
+
'fastdecisions.utils.Usage._repr_markdown_': ( 'utils.html#usage._repr_markdown_',
|
|
109
|
+
'fastdecisions/utils.py'),
|
|
110
|
+
'fastdecisions.utils.Provider': ('utils.html#provider', 'fastdecisions/utils.py'),
|
|
111
|
+
'fastdecisions.utils.norm_provider_name': ('utils.html#norm_provider_name', 'fastdecisions/utils.py'),
|
|
112
|
+
'fastdecisions.utils.register_provider': ('utils.html#register_provider', 'fastdecisions/utils.py'),
|
|
113
|
+
'fastdecisions.utils.Provider.__init__': ('utils.html#provider.__init__', 'fastdecisions/utils.py'),
|
|
114
|
+
'fastdecisions.utils.Provider.op_fn': ('utils.html#provider.op_fn', 'fastdecisions/utils.py'),
|
|
115
|
+
'fastdecisions.utils._auth_hdrs': ('utils.html#_auth_hdrs', 'fastdecisions/utils.py'),
|
|
116
|
+
'fastdecisions.utils.mk_provider_client': ('utils.html#mk_provider_client', 'fastdecisions/utils.py'),
|
|
117
|
+
'fastdecisions.utils.get_api_key': ('utils.html#get_api_key', 'fastdecisions/utils.py'),
|
|
118
|
+
'fastdecisions.utils.split_vendor': ('utils.html#split_vendor', 'fastdecisions/utils.py'),
|
|
119
|
+
'fastdecisions.utils.resolve_model': ('utils.html#resolve_model', 'fastdecisions/utils.py'),
|
|
120
|
+
'fastdecisions.utils.resize_b64': ('utils.html#resize_b64', 'fastdecisions/utils.py'),
|
|
121
|
+
'fastdecisions.utils.infer_api_name': ('utils.html#infer_api_name', 'fastdecisions/utils.py'),
|
|
122
|
+
'fastdecisions.utils.register_model_info': ( 'utils.html#register_model_info',
|
|
123
|
+
'fastdecisions/utils.py'),
|
|
124
|
+
'fastdecisions.utils.get_model_info': ('utils.html#get_model_info', 'fastdecisions/utils.py'),
|
|
125
|
+
'fastdecisions.utils.price_tier': ('utils.html#price_tier', 'fastdecisions/utils.py'),
|
|
126
|
+
'fastdecisions.utils.tier_rate': ('utils.html#tier_rate', 'fastdecisions/utils.py'),
|
|
127
|
+
'fastdecisions.utils.calc_cost': ('utils.html#calc_cost', 'fastdecisions/utils.py'),
|
|
128
|
+
'fastdecisions.utils.ContextWindowExceededError': ( 'utils.html#contextwindowexceedederror',
|
|
129
|
+
'fastdecisions/utils.py'),
|
|
130
|
+
'fastdecisions.utils._is_ctx_exceeded': ('utils.html#_is_ctx_exceeded', 'fastdecisions/utils.py'),
|
|
131
|
+
'fastdecisions.utils._classify_error': ('utils.html#_classify_error', 'fastdecisions/utils.py'),
|
|
132
|
+
'fastdecisions.utils._retry_call': ('utils.html#_retry_call', 'fastdecisions/utils.py'),
|
|
133
|
+
'fastdecisions.utils._debug_print': ('utils.html#_debug_print', 'fastdecisions/utils.py'),
|
|
134
|
+
'fastdecisions.utils.load_spec': ('utils.html#load_spec', 'fastdecisions/utils.py'),
|
|
135
|
+
'fastdecisions.utils.load_bundled_spec': ('utils.html#load_bundled_spec', 'fastdecisions/utils.py'),
|
|
136
|
+
'fastdecisions.utils._spec_from_openapi': ( 'utils.html#_spec_from_openapi',
|
|
137
|
+
'fastdecisions/utils.py')}},
|
|
138
|
+
'settings': { 'branch': 'main',
|
|
139
|
+
'lib_path': 'fastdecisions',
|
|
140
|
+
'git_url': 'https://github.com/AnswerDotAI/fastdecisions',
|
|
141
|
+
'doc_host': 'https://AnswerDotAI.github.io',
|
|
142
|
+
'doc_baseurl': '/fastdecisions'}}
|
fastdecisions/core.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Async and sync decision evaluation across TypeSafe Jev, Google Gemini, and OpenAI with a shared Jev-style interface, retries, and reusable `Decider` objects.
|
|
2
|
+
|
|
3
|
+
Docs: https://AnswerDotAI.github.io/fastdecisions/adecide.html.md"""
|
|
4
|
+
|
|
5
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/05_adecide.ipynb.
|
|
6
|
+
|
|
7
|
+
# %% auto #0
|
|
8
|
+
__all__ = ['vendor_doms', 'resolve_provider', 'mk_client', 'adecide', 'decide', 'Decider']
|
|
9
|
+
|
|
10
|
+
# %% ../nbs/05_adecide.ipynb #d2bd1bef
|
|
11
|
+
import asyncio, httpx2
|
|
12
|
+
from fastcore.utils import *
|
|
13
|
+
from fastcore.meta import *
|
|
14
|
+
from aidialog.msg_parts import Msg, Part
|
|
15
|
+
from .utils import (Provider, providers, norm_provider_name, mk_provider_client, split_vendor,
|
|
16
|
+
resolve_model, infer_api_name, _classify_error, _retry_call, defaults, _debug_print, Usage)
|
|
17
|
+
from .types import Decision, noul, norm_question, jev, _QUESTION_TYPES
|
|
18
|
+
from .typesafe import jev_provider
|
|
19
|
+
from .gemini import gemini_provider
|
|
20
|
+
from .openai import openai_provider
|
|
21
|
+
|
|
22
|
+
# %% ../nbs/05_adecide.ipynb #2e7c36cc
|
|
23
|
+
_default_providers = (jev_provider, gemini_provider, openai_provider)
|
|
24
|
+
vendor_doms = tuple(dict.fromkeys(httpx2.URL(p.base_url).host for p in _default_providers if p.base_url))
|
|
25
|
+
|
|
26
|
+
# %% ../nbs/05_adecide.ipynb #bd9adb0a
|
|
27
|
+
def resolve_provider(
|
|
28
|
+
model:str=None, # Bare model id, short alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
|
|
29
|
+
api_name:str=None, # Explicit registered provider name (accepts aliases like `'typesafe'` -> `'jev'`)
|
|
30
|
+
default:str=None, # Fallback provider name when `model` cannot be auto-inferred
|
|
31
|
+
) -> tuple[Provider, str]:
|
|
32
|
+
"Resolve `(Provider, model_id)` from aliases, `'provider/'` prefixes, or explicit `api_name`."
|
|
33
|
+
explicit = norm_provider_name(api_name)
|
|
34
|
+
if explicit and explicit not in providers: raise ValueError(f"Unknown provider {explicit!r}; registered: {', '.join(providers)}")
|
|
35
|
+
if model is None:
|
|
36
|
+
if explicit:
|
|
37
|
+
p = providers[explicit]
|
|
38
|
+
if not p.default_model: raise ValueError(f"Provider {explicit!r} has no default model; pass `model`")
|
|
39
|
+
return p, p.default_model
|
|
40
|
+
model = jev
|
|
41
|
+
model = resolve_model(model)
|
|
42
|
+
v, m = split_vendor(model)
|
|
43
|
+
prefix = v if v in providers else None
|
|
44
|
+
if prefix: model = resolve_model(m)
|
|
45
|
+
name = explicit or prefix or infer_api_name(model) or default
|
|
46
|
+
if not name: raise ValueError(f"Model {model!r} cannot be auto-resolved; pass `api_name` ({', '.join(providers)}) or prefix with `'provider/'`")
|
|
47
|
+
if name not in providers: raise ValueError(f"Unknown provider {name!r}; registered: {', '.join(providers)}")
|
|
48
|
+
return providers[name], model
|
|
49
|
+
|
|
50
|
+
def mk_client(
|
|
51
|
+
model:str=None, # Model name, alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
|
|
52
|
+
api_name:str=None, # Explicit registered provider name (accepts aliases like `'typesafe'` -> `'jev'`)
|
|
53
|
+
api_key:str=None, # Explicit API key; reads `provider.env` only on the default `base_url`
|
|
54
|
+
oauth_token:str=None, # Optional OAuth bearer token (mutually exclusive with `api_key`)
|
|
55
|
+
base_url:str=None, # Optional endpoint base URL override (never sends env keys without explicit creds)
|
|
56
|
+
xtra_hdrs:dict=None, # Extra default headers merged onto every request
|
|
57
|
+
timeout:float=60.0, # Request timeout in seconds
|
|
58
|
+
) -> tuple:
|
|
59
|
+
"Build `(OpenAPIClient, Provider, model_id)` for `model` with `retries=0` and `follow_redirects=False`."
|
|
60
|
+
p, model = resolve_provider(model, api_name=api_name, default='jev' if base_url else None)
|
|
61
|
+
cli = mk_provider_client(p, api_key=api_key, oauth_token=oauth_token, base_url=base_url, xtra_hdrs=xtra_hdrs, timeout=timeout)
|
|
62
|
+
return cli, p, model
|
|
63
|
+
|
|
64
|
+
# %% ../nbs/05_adecide.ipynb #9ae9f174
|
|
65
|
+
def _norm_questions(questions) -> dict:
|
|
66
|
+
"Normalize a questions dict, single question dict, or bare string into `{name: question_dict}`."
|
|
67
|
+
if isinstance(questions, str): return dict(answer=noul(questions))
|
|
68
|
+
if not isinstance(questions, dict) or not questions:
|
|
69
|
+
raise ValueError('`questions` must be a non-empty dict, a question dict, or a string')
|
|
70
|
+
if isinstance(questions.get('type'), str) and questions['type'] in _QUESTION_TYPES: return dict(answer=norm_question(questions))
|
|
71
|
+
return {k: norm_question(v) for k, v in questions.items()}
|
|
72
|
+
|
|
73
|
+
# %% ../nbs/05_adecide.ipynb #0354b427
|
|
74
|
+
def _check_opts(kwargs:dict):
|
|
75
|
+
known = {k for p in providers.values() for k in p.opt_keys}
|
|
76
|
+
if bad := sorted(set(kwargs) - known): raise TypeError(f"Unexpected keyword argument(s): {', '.join(bad)}")
|
|
77
|
+
|
|
78
|
+
async def adecide(
|
|
79
|
+
state, # Text, JSON dict/list, `Msg`, `list[Msg]`, or `aidialog.msg_parts` media
|
|
80
|
+
questions, # `{name: question}` dict (strings = `noul`), or a single question/string (under `'answer'`)
|
|
81
|
+
model:str=None, # Model name, alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
|
|
82
|
+
api_name:str=None, # Explicit registered provider name overriding model inference (accepts `'typesafe'` -> `'jev'`)
|
|
83
|
+
api_key:str=None, # Explicit API key overriding environment variable
|
|
84
|
+
oauth_token:str=None, # Explicit OAuth bearer token (mutually exclusive with `api_key`)
|
|
85
|
+
base_url:str=None, # Override provider base URL (skips env keys unless credentials are passed)
|
|
86
|
+
xtra_body:dict=None, # Extra raw JSON fields merged into the request body
|
|
87
|
+
xtra_hdrs:dict=None, # Extra HTTP headers merged onto the request
|
|
88
|
+
retries:int=2, # Max retries on retryable `APIError`s
|
|
89
|
+
retry_delay:float=0.5, # Initial exponential backoff delay in seconds
|
|
90
|
+
timeout:float=60.0, # Request timeout in seconds
|
|
91
|
+
**kwargs, # Provider options (`long_context`, `resolution`, `detail`, `prompt_cache_key`, etc.)
|
|
92
|
+
) -> Decision:
|
|
93
|
+
"Evaluate canonical decision `questions` against `state` using Jev, Gemini, or OpenAI."
|
|
94
|
+
_check_opts(kwargs)
|
|
95
|
+
cli, p, model = mk_client(model=model, api_name=api_name,
|
|
96
|
+
api_key=api_key, oauth_token=oauth_token, base_url=base_url, timeout=timeout)
|
|
97
|
+
qs = _norm_questions(questions)
|
|
98
|
+
body = p.mk_payload(state, qs, model=model, **kwargs)
|
|
99
|
+
headers = p.req_hdrs(body, headers=xtra_hdrs, **kwargs) if p.req_hdrs else (dict(xtra_hdrs) if xtra_hdrs else {})
|
|
100
|
+
op = p.op_fn(cli)
|
|
101
|
+
if defaults.debug_mode: _debug_print(model, p.name, body, op.base_url)
|
|
102
|
+
resp = await _retry_call(lambda: op(**body, headers_=headers, body_=xtra_body or {}),
|
|
103
|
+
retries=retries, retry_delay=retry_delay, classify=_classify_error)
|
|
104
|
+
return p.norm_response(resp, model=model, questions=qs)
|
|
105
|
+
|
|
106
|
+
@delegates(adecide, keep=True)
|
|
107
|
+
def decide(
|
|
108
|
+
state, # Text, JSON dict/list, `Msg`, `list[Msg]`, or `aidialog.msg_parts` media
|
|
109
|
+
questions, # `{name: question}` dict (strings = `noul`), or a single question/string
|
|
110
|
+
model:str=None, # Model name, alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
|
|
111
|
+
**kwargs,
|
|
112
|
+
) -> Decision:
|
|
113
|
+
"Synchronous wrapper around `adecide` via `run_sync` (works in both scripts and notebooks)."
|
|
114
|
+
return run_sync(adecide(state, questions, model=model, **kwargs))
|
|
115
|
+
|
|
116
|
+
# %% ../nbs/05_adecide.ipynb #095a51d1
|
|
117
|
+
class Decider:
|
|
118
|
+
"Reusable decision evaluator bound to a fixed question set and model, tracking cumulative usage and cost."
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
questions, # `{name: question}` dict (strings = `noul`), or single question/string
|
|
122
|
+
model:str=None, # Model name, alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
|
|
123
|
+
**kwargs, # Default kwargs forwarded to `adecide` (e.g. `resolution`, `long_context`, `prompt_cache_key`)
|
|
124
|
+
):
|
|
125
|
+
self.questions = _norm_questions(questions)
|
|
126
|
+
self.model = model if model is not None or kwargs.get('api_name') else jev
|
|
127
|
+
self.kwargs = kwargs
|
|
128
|
+
self.usage,self.cost,self.last = Usage(),0.0,None
|
|
129
|
+
|
|
130
|
+
def __repr__(self):
|
|
131
|
+
qs = list(self.questions)
|
|
132
|
+
q_str = ', '.join(qs[:4]) + (f', ... (+{len(qs)-4})' if len(qs) > 4 else '')
|
|
133
|
+
api = norm_provider_name(self.kwargs.get('api_name'))
|
|
134
|
+
m = self.model or (providers[api].default_model if api in providers else api) or jev
|
|
135
|
+
return f"Decider(model={m!r}, questions=[{q_str}], cost=${self.cost:.6f})"
|
|
136
|
+
|
|
137
|
+
async def __call__(
|
|
138
|
+
self,
|
|
139
|
+
state, # Text, JSON dict/list, `Msg`, `list[Msg]`, or media
|
|
140
|
+
**kwargs, # Per-call overrides merged over `self.kwargs`
|
|
141
|
+
) -> Decision:
|
|
142
|
+
"Evaluate `self.questions` against `state`, updating cumulative `usage`, `cost`, and `last`."
|
|
143
|
+
dec = await adecide(state, self.questions, model=self.model, **(self.kwargs | kwargs))
|
|
144
|
+
self.last = dec
|
|
145
|
+
self.usage = self.usage + dec.usage
|
|
146
|
+
self.cost += dec.cost
|
|
147
|
+
return dec
|
|
148
|
+
|
|
149
|
+
async def batch(
|
|
150
|
+
self,
|
|
151
|
+
states, # Sequence of states (or a single state) to evaluate concurrently
|
|
152
|
+
max_concurrency:int=8, # Maximum in-flight requests (must be >= 1)
|
|
153
|
+
return_exceptions:bool=False, # Return exceptions inline instead of cancelling and raising?
|
|
154
|
+
**kwargs, # Per-batch overrides forwarded to `adecide`
|
|
155
|
+
) -> list:
|
|
156
|
+
"Evaluate `self.questions` across `states` concurrently, preserving input order."
|
|
157
|
+
if max_concurrency < 1: raise ValueError('`max_concurrency` must be >= 1')
|
|
158
|
+
items = [states] if isinstance(states, (str, bytes, dict, Msg, Part)) else listify(states)
|
|
159
|
+
sem, failed = asyncio.Semaphore(max_concurrency), False
|
|
160
|
+
async def _one(st):
|
|
161
|
+
nonlocal failed
|
|
162
|
+
async with sem:
|
|
163
|
+
if failed and not return_exceptions: raise asyncio.CancelledError
|
|
164
|
+
try: return await self(st, **kwargs)
|
|
165
|
+
except BaseException:
|
|
166
|
+
failed = True
|
|
167
|
+
raise
|
|
168
|
+
tasks = [asyncio.create_task(_one(st)) for st in items]
|
|
169
|
+
if return_exceptions: return await asyncio.gather(*tasks, return_exceptions=True)
|
|
170
|
+
try: return await asyncio.gather(*tasks)
|
|
171
|
+
except BaseException:
|
|
172
|
+
for t in tasks:
|
|
173
|
+
if not t.done(): t.cancel()
|
|
174
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
175
|
+
raise
|
fastdecisions/gemini.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Gemini Decisions API adapter built on `fastspec.OpenAPIClient`, translating Jev-canonical inputs to `POST /v1beta/decisions`.
|
|
2
|
+
|
|
3
|
+
Docs: https://AnswerDotAI.github.io/fastdecisions/gemini.html.md"""
|
|
4
|
+
|
|
5
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_gemini.ipynb.
|
|
6
|
+
|
|
7
|
+
# %% auto #0
|
|
8
|
+
__all__ = ['gemini_spec', 'gemini_provider', 'prep_gemini_input']
|
|
9
|
+
|
|
10
|
+
# %% ../nbs/03_gemini.ipynb #fcaac9eb
|
|
11
|
+
from fastcore.utils import *
|
|
12
|
+
from fasttransport.errors import APIError
|
|
13
|
+
from aidialog.msg_parts import Media, InputImage, InputAudio, InputVideo, InputFile, data_url, url_mime
|
|
14
|
+
from .utils import Provider, Usage, load_bundled_spec, model_aliases, register_provider
|
|
15
|
+
from .types import Decision, check_answers, gem_dec, lower_state, norm_answer, norm_question, score_criteria_list
|
|
16
|
+
|
|
17
|
+
# %% ../nbs/03_gemini.ipynb #51c40146
|
|
18
|
+
gemini_spec = load_bundled_spec('gemini')
|
|
19
|
+
model_aliases.update(dict(gemini=gem_dec, gem_dec=gem_dec))
|
|
20
|
+
|
|
21
|
+
# %% ../nbs/03_gemini.ipynb #132265c2
|
|
22
|
+
_MEDIA_TYPES = {InputImage: 'image', InputAudio: 'audio', InputVideo: 'video', InputFile: 'document'}
|
|
23
|
+
_RES_TYPES = {'image', 'video', 'document'}
|
|
24
|
+
|
|
25
|
+
def _media_block(
|
|
26
|
+
p:Media, # `InputImage`, `InputAudio`, `InputVideo`, or `InputFile`
|
|
27
|
+
resolution:str=None, # Optional Gemini `MediaResolution` ('low', 'medium', 'high', 'ultra_high')
|
|
28
|
+
) -> dict:
|
|
29
|
+
"Convert an `aidialog.msg_parts.Media` part into a Gemini Decisions content block."
|
|
30
|
+
mtype = _MEDIA_TYPES.get(type(p))
|
|
31
|
+
if not mtype: raise ValueError(f'Unsupported media type: {type(p).__name__}')
|
|
32
|
+
if not p.text: raise ValueError(f'{type(p).__name__} has empty `text`')
|
|
33
|
+
blk = dict(type=mtype)
|
|
34
|
+
if parsed := data_url(p.text):
|
|
35
|
+
mime, b64 = parsed
|
|
36
|
+
blk['data'],blk['mime_type'] = b64,(p.mime or mime)
|
|
37
|
+
elif p.text.startswith(('http://', 'https://')):
|
|
38
|
+
blk['uri'] = p.text
|
|
39
|
+
if mime := (p.mime or url_mime(p.text, default=None)): blk['mime_type'] = mime
|
|
40
|
+
else: raise ValueError(f'Unsupported {type(p).__name__} source (expected data URL or HTTP/HTTPS URI): {p.text[:60]!r}')
|
|
41
|
+
if resolution and mtype in _RES_TYPES: blk['resolution'] = resolution
|
|
42
|
+
if isinstance(p, InputVideo) and any(getattr(p, k, None) is not None for k in ('start', 'end', 'fps')):
|
|
43
|
+
proc = dict(type='static')
|
|
44
|
+
if p.start is not None: proc['start_offset'] = f'{p.start}s'
|
|
45
|
+
if p.end is not None: proc['end_offset'] = f'{p.end}s'
|
|
46
|
+
if p.fps is not None: proc['fps'] = p.fps
|
|
47
|
+
blk['processing'] = proc
|
|
48
|
+
return blk
|
|
49
|
+
|
|
50
|
+
# %% ../nbs/03_gemini.ipynb #5296084e
|
|
51
|
+
def prep_gemini_input(
|
|
52
|
+
state, # String, JSON dict/list (may contain nested `Msg`/`Part`), `Msg`, `list[Msg]`, `Media`, or mixed list
|
|
53
|
+
resolution:str=None, # Optional `MediaResolution` applied to visual/document blocks
|
|
54
|
+
):
|
|
55
|
+
"Convert Jev-canonical `state` into a Gemini Decisions `input` string or Interactions block list."
|
|
56
|
+
if isinstance(state, str):
|
|
57
|
+
if not state: raise ValueError('Gemini Decisions requires non-empty `state`')
|
|
58
|
+
return state
|
|
59
|
+
media_blocks = []
|
|
60
|
+
def _on_media(p:Media):
|
|
61
|
+
media_blocks.append(_media_block(p, resolution=resolution))
|
|
62
|
+
return UNSET
|
|
63
|
+
low = lower_state(state, on_media=_on_media)
|
|
64
|
+
empty = low is UNSET or (isinstance(low, (str, list, dict)) and not low)
|
|
65
|
+
txt = '' if empty else (low if isinstance(low, str) else dumps(low))
|
|
66
|
+
if not txt and not media_blocks: raise ValueError('Prepared Gemini input is empty (for example a thinking-only message)')
|
|
67
|
+
if not media_blocks: return txt
|
|
68
|
+
return ([dict(type='text', text=txt)] if txt else []) + media_blocks
|
|
69
|
+
|
|
70
|
+
# %% ../nbs/03_gemini.ipynb #0cbb4022
|
|
71
|
+
def _as_str(v) -> str: return v if isinstance(v, str) else dumps(v)
|
|
72
|
+
|
|
73
|
+
def _gemini_question(q:dict) -> dict:
|
|
74
|
+
q = norm_question(q)
|
|
75
|
+
t = q['type']
|
|
76
|
+
if t == 'box': raise NotImplementedError("Gemini Decisions does not support 'box' questions")
|
|
77
|
+
if q.get('instructions') is None: raise ValueError("Gemini Decisions requires 'instructions' on every question")
|
|
78
|
+
q['instructions'] = _as_str(q['instructions'])
|
|
79
|
+
if t == 'noul' and q.get('criteria'):
|
|
80
|
+
c, gc = q['criteria'], {}
|
|
81
|
+
if (tv := c.get('true')) is not None: gc['true_description'] = _as_str(tv)
|
|
82
|
+
if (fv := c.get('false')) is not None: gc['false_description'] = _as_str(fv)
|
|
83
|
+
if gc: q['criteria'] = gc
|
|
84
|
+
else: q.pop('criteria', None)
|
|
85
|
+
elif t == 'choice': q['criteria'] = {str(k): ('' if v is None else _as_str(v)) for k, v in q['criteria'].items()}
|
|
86
|
+
elif t == 'score': q['criteria'] = [_as_str(v) for v in score_criteria_list(q['criteria'])]
|
|
87
|
+
return q
|
|
88
|
+
|
|
89
|
+
def _mk_payload(
|
|
90
|
+
state, # String, JSON dict/list, `Msg`, `list[Msg]`, or `Media`
|
|
91
|
+
questions:dict, # `{name: question_dict}` mapping
|
|
92
|
+
model:str=gem_dec, # Gemini decision model name
|
|
93
|
+
resolution:str=None, # Optional `MediaResolution` for visual/document inputs
|
|
94
|
+
**kwargs, # Ignored options belonging to other providers
|
|
95
|
+
) -> dict:
|
|
96
|
+
"Build a Gemini `POST /v1beta/decisions` request payload from canonical inputs."
|
|
97
|
+
if not questions: raise ValueError('`questions` must be a non-empty mapping')
|
|
98
|
+
return dict(model=model, input=prep_gemini_input(state, resolution=resolution),
|
|
99
|
+
questions={k: _gemini_question(v) for k, v in questions.items()})
|
|
100
|
+
|
|
101
|
+
# %% ../nbs/03_gemini.ipynb #440b2711
|
|
102
|
+
def _norm_usage(resp:dict) -> Usage:
|
|
103
|
+
u = obj2dict(resp.get('usage') or {})
|
|
104
|
+
inp, out = int(u.get('total_input_tokens', 0) or 0), int(u.get('total_output_tokens', 0) or 0)
|
|
105
|
+
tot, cached, thought = int(u.get('total_tokens', inp + out) or (inp + out)), int(u.get('total_cached_tokens', 0) or 0), int(u.get('total_thought_tokens', 0) or 0)
|
|
106
|
+
return Usage(prompt_tokens=inp, completion_tokens=out, total_tokens=tot, cached_tokens=cached, reasoning_tokens=thought, raw=u)
|
|
107
|
+
|
|
108
|
+
# %% ../nbs/03_gemini.ipynb #8ba479c8
|
|
109
|
+
def _norm_response(
|
|
110
|
+
resp, # Raw response returned by `cli.decisions.evaluate`
|
|
111
|
+
model:str=None, # Model name used for the request (Gemini omits `model` in responses)
|
|
112
|
+
questions:dict=None, # Original canonical questions dict (verified for completeness and key order)
|
|
113
|
+
) -> Decision:
|
|
114
|
+
"Convert a raw Gemini Decisions response into a canonical `Decision`, raising `APIError` on `prompt_feedback` blocks."
|
|
115
|
+
d = obj2dict(resp)
|
|
116
|
+
pf = d.get('prompt_feedback') or {}
|
|
117
|
+
if reason := pf.get('block_reason'):
|
|
118
|
+
msg = pf.get('block_reason_message') or f'Gemini Decisions blocked the prompt: {reason}'
|
|
119
|
+
raise APIError(msg, provider='gemini', model=model or gem_dec, endpoint='/v1beta/decisions',
|
|
120
|
+
status_code=200, error_type='prompt_blocked', code=reason, retryable=False, raw=d)
|
|
121
|
+
ans = check_answers({k: norm_answer(v) for k, v in (d.get('answers') or {}).items()}, questions)
|
|
122
|
+
return Decision(model=d.get('model') or model or gem_dec, answers=ans, usage=_norm_usage(d), api_name='gemini', raw=d)
|
|
123
|
+
|
|
124
|
+
gemini_provider = register_provider(Provider('gemini', gemini_spec, 'GEMINI_API_KEY', 'x-goog-api-key',
|
|
125
|
+
'decisions.evaluate', _mk_payload, norm_response=_norm_response, default_model=gem_dec, opt_keys=('resolution',)))
|