python-fastllm 0.0.49__tar.gz → 0.0.51__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.
Files changed (22) hide show
  1. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/PKG-INFO +18 -73
  2. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/README.md +16 -71
  3. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/__init__.py +1 -1
  4. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/_modidx.py +19 -6
  5. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/anthropic.py +59 -44
  6. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/gemini.py +37 -19
  7. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/openai_chat.py +31 -18
  8. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/openai_responses.py +23 -24
  9. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/responses.py +21 -2
  10. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/streaming.py +3 -8
  11. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/types.py +12 -10
  12. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/pyproject.toml +1 -1
  13. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/python_fastllm.egg-info/PKG-INFO +18 -73
  14. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/python_fastllm.egg-info/requires.txt +1 -1
  15. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/acomplete.py +0 -0
  16. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/chat.py +0 -0
  17. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/fastllm/codex.py +0 -0
  18. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/python_fastllm.egg-info/SOURCES.txt +0 -0
  19. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/python_fastllm.egg-info/dependency_links.txt +0 -0
  20. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/python_fastllm.egg-info/entry_points.txt +0 -0
  21. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/python_fastllm.egg-info/top_level.txt +0 -0
  22. {python_fastllm-0.0.49 → python_fastllm-0.0.51}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-fastllm
3
- Version: 0.0.49
3
+ Version: 0.0.51
4
4
  Author-email: Kerem Turgutlu <keremturgutlu@gmail.com>
5
5
  License: Apache-2.0
6
6
  Project-URL: Repository, https://github.com/AnswerDotAI/fastllm
@@ -10,7 +10,7 @@ Classifier: Programming Language :: Python :: 3 :: Only
10
10
  Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
12
  Requires-Dist: fastcore>=2.1.18
13
- Requires-Dist: aidialog>=0.0.10
13
+ Requires-Dist: aidialog>=0.0.25
14
14
  Requires-Dist: fasttransport>=0.0.2
15
15
  Requires-Dist: pillow
16
16
 
@@ -21,13 +21,14 @@ Requires-Dist: pillow
21
21
 
22
22
  ## Install
23
23
 
24
- Clone and install locally into your `aai-ws` env
24
+ Run `pip install python-fastllm` or clone from github and install locally.
25
25
 
26
26
  ## Setup
27
27
 
28
28
  ``` python
29
29
  from aidialog.msg_parts import Msg, Part, Text, Thinking, ToolUse, InputImage, mk_tool_res_msg, Completion
30
30
  from fastllm.acomplete import acomplete
31
+ from fastllm.types import sample_img_url, sample_doms
31
32
  import asyncio, json
32
33
 
33
34
  # Helpers
@@ -56,7 +57,7 @@ The same `acomplete` call works with Claude, GPT, Gemini, and Kimi. Just change
56
57
 
57
58
  ``` python
58
59
  models = [
59
- ('claude-sonnet-4-20250514', {}),
60
+ ('claude-sonnet-5', {}),
60
61
  ('gpt-4o-mini', {}),
61
62
  ('models/gemini-3-flash-preview', {}),
62
63
  ('accounts/fireworks/models/kimi-k2p5', dict(vendor_name='fireworks_ai'))
@@ -80,46 +81,6 @@ for name, kw in models:
80
81
 
81
82
  The response should be simple and direct.
82
83
 
83
- ## Multi-Turn — Swap Providers Mid-Conversation
84
-
85
- Build a conversation with one provider, then seamlessly continue it with another. `fastllm` translates between every provider’s native format automatically:
86
-
87
- ``` python
88
- # Turn 1: Claude starts the conversation
89
- msgs = [user("Name the 3 largest planets in our solar system. One sentence.")]
90
- print("Claude: ", end='')
91
- r1 = await stream(msgs, model='claude-sonnet-4-20250514', max_tokens=mtok)
92
- ```
93
-
94
- Claude: The three largest planets in our solar system are Jupiter, Saturn, and Neptune.
95
-
96
- ``` python
97
- # Turn 2: Switch to GPT — just change the model string
98
- msgs += [r1.message, user("Which one has the most moons?")]
99
- print("GPT: ", end='')
100
- r2 = await stream(msgs, model='gpt-4o-mini', max_tokens=mtok)
101
- ```
102
-
103
- GPT: As of now, Saturn has the most moons, with over 80 confirmed moons.
104
-
105
- ``` python
106
- # Turn 3: Switch to Gemini — same msgs, different provider
107
- msgs += [r2.message, user("Summarize our conversation in one sentence.")]
108
- print("Gemini: ", end='')
109
- r3 = await stream(msgs, model='models/gemini-3-flash-preview', max_tokens=mtok)
110
- ```
111
-
112
- Gemini: The conversation identified the three largest planets in the solar system and noted that Saturn currently has the most moons.
113
-
114
- ``` python
115
- # Turn 4: Switch to Kimi — works the same way
116
- msgs += [r3.message, user("Thanks! What's one surprising fact about Saturn?")]
117
- print("Kimi: ", end='')
118
- r4 = await stream(msgs, model='accounts/fireworks/models/kimi-k2p5', vendor_name='fireworks_ai', max_tokens=mtok)
119
- ```
120
-
121
- Kimi: 🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠Saturn is less dense than water, meaning it would theoretically float if you could find a bathtub large enough to hold it.
122
-
123
84
  ## System Prompts
124
85
 
125
86
  Pass a system prompt to any provider — `fastllm` maps it to each API’s native mechanism (Anthropic `system`, OpenAI `instructions`, Gemini `system_instruction`):
@@ -128,7 +89,7 @@ Pass a system prompt to any provider — `fastllm` maps it to each API’s nativ
128
89
  sys = "You are a pirate chef. Always respond in pirate speak and mention food."
129
90
 
130
91
  print("Claude: ", end='')
131
- r = await stream([user("What should I do today?")], model='claude-sonnet-4-20250514', system=sys, max_tokens=mtok)
92
+ r = await stream([user("What should I do today?")], model='claude-sonnet-5', system=sys, max_tokens=mtok)
132
93
 
133
94
  print("Gemini: ", end='')
134
95
  r = await stream([user("What should I do today?")], model='models/gemini-3-flash-preview', system=sys, max_tokens=mtok)
@@ -161,7 +122,7 @@ r = await stream([user("What should I do today?")], model='models/gemini-3-flash
161
122
 
162
123
  ## Tool Calling — Define Once, Use Anywhere
163
124
 
164
- Define tools in a single canonical format. `fastllm` translates to each provider’s native tool schema automatically. Here we start a tool-use conversation with Claude, provide the result, then switch to GPT and Gemini to continue:
125
+ Define tools in a single canonical format. `fastllm` translates to each provider’s native tool schema automatically. Here Claude requests the tool, receives the result, and answers:
165
126
 
166
127
  ``` python
167
128
  tools = [{"type": "function", "function": {
@@ -172,7 +133,7 @@ tools = [{"type": "function", "function": {
172
133
 
173
134
  # Turn 1: Claude requests the tool
174
135
  msgs = [user("What's the weather in Paris?")]
175
- r1 = await stream(msgs, model='claude-sonnet-4-20250514', tools=tools, max_tokens=mtok)
136
+ r1 = await stream(msgs, model='claude-sonnet-5', tools=tools, max_tokens=mtok)
176
137
  print("Tool calls:", r1.tool_calls)
177
138
  ```
178
139
 
@@ -182,41 +143,26 @@ print("Tool calls:", r1.tool_calls)
182
143
  Tool calls: [ToolUse(raw={'caller': {'type': 'direct'}}, cache_control=None, id='toolu_01RMN1WM7vPBT3ovv5Ex6VzC', name='get_weather', arguments={'city': 'Paris'}, server=False, text=None)]
183
144
 
184
145
  ``` python
185
- # Provide the tool result
186
- msgs += [r1.message, mk_tool_res_msg(r1.tool_calls, ['22°C, sunny with light clouds'])]
187
-
188
- # Turn 2: Switch to GPT to interpret the result
189
- msgs.append(user("Should I bring a jacket?"))
190
- print("GPT: ", end='')
191
- r2 = await stream(msgs, model='gpt-4o-mini', tools=tools, max_tokens=mtok)
146
+ # Provide the tool result, then continue the same conversation
147
+ msgs += [r1.message, mk_tool_res_msg(r1.tool_calls, ['22°C, sunny with light clouds']), user("Should I bring a jacket?")]
148
+ print("Claude: ", end='')
149
+ r2 = await stream(msgs, model='claude-sonnet-5', tools=tools, max_tokens=mtok)
192
150
  ```
193
151
 
194
152
  GPT: With the temperature at 22°C and sunny with light clouds, a jacket isn't necessary for most people. However, if you tend to feel cold easily or if you plan to be out in the evening when it might cool down a bit, it could be a good idea to bring a light jacket.
195
153
 
196
- ``` python
197
- # Turn 3: Gemini sees the full cross-provider tool history
198
- msgs += [r2.message, user("How about tomorrow — will it rain?")]
199
- r3 = await stream(msgs, model='models/gemini-3-flash-preview', tools=tools, max_tokens=mtok, web_search_options={})
200
- ```
201
-
202
- Tomorrow in Paris (Saturday, June 13), the weather is expected to be mostly pleasant and sunny.
203
-
204
- While there is a small chance of light, passing showers (around a 20-25% chance), most forecasts indicate a dry day with mostly clear or scattered clouds. Temperatures will likely reach a comfortable high of around 22°C to 27°C (72°F to 80°F), making it a great day for being outdoors.
205
-
206
- So, while you might see a stray shower, you likely won't need to worry about heavy rain!
207
-
208
154
  ## Tool Choice
209
155
 
210
156
  Control whether the model must use tools, can’t use tools, or decides on its own:
211
157
 
212
158
  ``` python
213
159
  # Force the model to call a tool (even for a greeting)
214
- r = await stream([user("Hello there!")], model='claude-sonnet-4-20250514', tools=tools, tool_choice='required', max_tokens=mtok)
160
+ r = await stream([user("Hello there!")], model='claude-sonnet-5', tools=tools, tool_choice='required', max_tokens=mtok)
215
161
  print("Forced:", r.tool_calls)
216
162
 
217
163
  # Prevent tool use (model must answer directly)
218
164
  print("\nNo tools: ", end='')
219
- r = await stream([user("What's the weather?")], model='claude-sonnet-4-20250514', tools=tools, tool_choice='none', max_tokens=mtok)
165
+ r = await stream([user("What's the weather?")], model='claude-sonnet-5', tools=tools, tool_choice='none', max_tokens=mtok)
220
166
  ```
221
167
 
222
168
  - ⏳ `get_weather(city="<UNKNOWN>")` ⏳
@@ -327,11 +273,11 @@ long_ctx = "You are an expert on the solar system. " * 200
327
273
  system = Text(long_ctx, cache_control={'type': 'ephemeral'})
328
274
 
329
275
  print("Call 1: ", end='')
330
- r1 = await stream([user("What is Jupiter's mass?")], model='claude-sonnet-4-20250514', system=system, max_tokens=mtok)
276
+ r1 = await stream([user("What is Jupiter's mass?")], model='claude-sonnet-5', system=system, max_tokens=mtok)
331
277
  print(f"Usage: {r1.usage}")
332
278
 
333
279
  print("Call 2: ", end='')
334
- r2 = await stream([user("How about Saturn?")], model='claude-sonnet-4-20250514', system=system, max_tokens=mtok)
280
+ r2 = await stream([user("How about Saturn?")], model='claude-sonnet-5', system=system, max_tokens=mtok)
335
281
  print(f"Usage: {r2.usage}")
336
282
  ```
337
283
 
@@ -381,13 +327,12 @@ print(f"Usage: {r2.usage}")
381
327
  Send images to any provider that supports them. The canonical `input_image` part works everywhere:
382
328
 
383
329
  ``` python
384
- img_url = "https://img.freepik.com/free-photo/mountain-range-body-water_53876-139760.jpg?semt=ais_hybrid&w=740&q=80"
385
330
  img_msg = Msg(role='user', content=[
386
- InputImage(img_url),
331
+ InputImage(sample_img_url),
387
332
  Text("What do you see in this image?")
388
333
  ])
389
334
 
390
- for name, kw in [('claude-sonnet-4-20250514', {}), ('gpt-4o-mini', {}), ('models/gemini-3-flash-preview', {})]:
335
+ for name, kw in [('claude-sonnet-5', {}), ('gpt-4o-mini', {}), ('models/gemini-3-flash-preview', {})]:
391
336
  print(f"{name:>30s}: ", end='')
392
337
  r = await stream([img_msg], model=name, max_tokens=mtok, **kw)
393
338
  ```
@@ -5,13 +5,14 @@
5
5
 
6
6
  ## Install
7
7
 
8
- Clone and install locally into your `aai-ws` env
8
+ Run `pip install python-fastllm` or clone from github and install locally.
9
9
 
10
10
  ## Setup
11
11
 
12
12
  ``` python
13
13
  from aidialog.msg_parts import Msg, Part, Text, Thinking, ToolUse, InputImage, mk_tool_res_msg, Completion
14
14
  from fastllm.acomplete import acomplete
15
+ from fastllm.types import sample_img_url, sample_doms
15
16
  import asyncio, json
16
17
 
17
18
  # Helpers
@@ -40,7 +41,7 @@ The same `acomplete` call works with Claude, GPT, Gemini, and Kimi. Just change
40
41
 
41
42
  ``` python
42
43
  models = [
43
- ('claude-sonnet-4-20250514', {}),
44
+ ('claude-sonnet-5', {}),
44
45
  ('gpt-4o-mini', {}),
45
46
  ('models/gemini-3-flash-preview', {}),
46
47
  ('accounts/fireworks/models/kimi-k2p5', dict(vendor_name='fireworks_ai'))
@@ -64,46 +65,6 @@ for name, kw in models:
64
65
 
65
66
  The response should be simple and direct.
66
67
 
67
- ## Multi-Turn — Swap Providers Mid-Conversation
68
-
69
- Build a conversation with one provider, then seamlessly continue it with another. `fastllm` translates between every provider’s native format automatically:
70
-
71
- ``` python
72
- # Turn 1: Claude starts the conversation
73
- msgs = [user("Name the 3 largest planets in our solar system. One sentence.")]
74
- print("Claude: ", end='')
75
- r1 = await stream(msgs, model='claude-sonnet-4-20250514', max_tokens=mtok)
76
- ```
77
-
78
- Claude: The three largest planets in our solar system are Jupiter, Saturn, and Neptune.
79
-
80
- ``` python
81
- # Turn 2: Switch to GPT — just change the model string
82
- msgs += [r1.message, user("Which one has the most moons?")]
83
- print("GPT: ", end='')
84
- r2 = await stream(msgs, model='gpt-4o-mini', max_tokens=mtok)
85
- ```
86
-
87
- GPT: As of now, Saturn has the most moons, with over 80 confirmed moons.
88
-
89
- ``` python
90
- # Turn 3: Switch to Gemini — same msgs, different provider
91
- msgs += [r2.message, user("Summarize our conversation in one sentence.")]
92
- print("Gemini: ", end='')
93
- r3 = await stream(msgs, model='models/gemini-3-flash-preview', max_tokens=mtok)
94
- ```
95
-
96
- Gemini: The conversation identified the three largest planets in the solar system and noted that Saturn currently has the most moons.
97
-
98
- ``` python
99
- # Turn 4: Switch to Kimi — works the same way
100
- msgs += [r3.message, user("Thanks! What's one surprising fact about Saturn?")]
101
- print("Kimi: ", end='')
102
- r4 = await stream(msgs, model='accounts/fireworks/models/kimi-k2p5', vendor_name='fireworks_ai', max_tokens=mtok)
103
- ```
104
-
105
- Kimi: 🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠Saturn is less dense than water, meaning it would theoretically float if you could find a bathtub large enough to hold it.
106
-
107
68
  ## System Prompts
108
69
 
109
70
  Pass a system prompt to any provider — `fastllm` maps it to each API’s native mechanism (Anthropic `system`, OpenAI `instructions`, Gemini `system_instruction`):
@@ -112,7 +73,7 @@ Pass a system prompt to any provider — `fastllm` maps it to each API’s nativ
112
73
  sys = "You are a pirate chef. Always respond in pirate speak and mention food."
113
74
 
114
75
  print("Claude: ", end='')
115
- r = await stream([user("What should I do today?")], model='claude-sonnet-4-20250514', system=sys, max_tokens=mtok)
76
+ r = await stream([user("What should I do today?")], model='claude-sonnet-5', system=sys, max_tokens=mtok)
116
77
 
117
78
  print("Gemini: ", end='')
118
79
  r = await stream([user("What should I do today?")], model='models/gemini-3-flash-preview', system=sys, max_tokens=mtok)
@@ -145,7 +106,7 @@ r = await stream([user("What should I do today?")], model='models/gemini-3-flash
145
106
 
146
107
  ## Tool Calling — Define Once, Use Anywhere
147
108
 
148
- Define tools in a single canonical format. `fastllm` translates to each provider’s native tool schema automatically. Here we start a tool-use conversation with Claude, provide the result, then switch to GPT and Gemini to continue:
109
+ Define tools in a single canonical format. `fastllm` translates to each provider’s native tool schema automatically. Here Claude requests the tool, receives the result, and answers:
149
110
 
150
111
  ``` python
151
112
  tools = [{"type": "function", "function": {
@@ -156,7 +117,7 @@ tools = [{"type": "function", "function": {
156
117
 
157
118
  # Turn 1: Claude requests the tool
158
119
  msgs = [user("What's the weather in Paris?")]
159
- r1 = await stream(msgs, model='claude-sonnet-4-20250514', tools=tools, max_tokens=mtok)
120
+ r1 = await stream(msgs, model='claude-sonnet-5', tools=tools, max_tokens=mtok)
160
121
  print("Tool calls:", r1.tool_calls)
161
122
  ```
162
123
 
@@ -166,41 +127,26 @@ print("Tool calls:", r1.tool_calls)
166
127
  Tool calls: [ToolUse(raw={'caller': {'type': 'direct'}}, cache_control=None, id='toolu_01RMN1WM7vPBT3ovv5Ex6VzC', name='get_weather', arguments={'city': 'Paris'}, server=False, text=None)]
167
128
 
168
129
  ``` python
169
- # Provide the tool result
170
- msgs += [r1.message, mk_tool_res_msg(r1.tool_calls, ['22°C, sunny with light clouds'])]
171
-
172
- # Turn 2: Switch to GPT to interpret the result
173
- msgs.append(user("Should I bring a jacket?"))
174
- print("GPT: ", end='')
175
- r2 = await stream(msgs, model='gpt-4o-mini', tools=tools, max_tokens=mtok)
130
+ # Provide the tool result, then continue the same conversation
131
+ msgs += [r1.message, mk_tool_res_msg(r1.tool_calls, ['22°C, sunny with light clouds']), user("Should I bring a jacket?")]
132
+ print("Claude: ", end='')
133
+ r2 = await stream(msgs, model='claude-sonnet-5', tools=tools, max_tokens=mtok)
176
134
  ```
177
135
 
178
136
  GPT: With the temperature at 22°C and sunny with light clouds, a jacket isn't necessary for most people. However, if you tend to feel cold easily or if you plan to be out in the evening when it might cool down a bit, it could be a good idea to bring a light jacket.
179
137
 
180
- ``` python
181
- # Turn 3: Gemini sees the full cross-provider tool history
182
- msgs += [r2.message, user("How about tomorrow — will it rain?")]
183
- r3 = await stream(msgs, model='models/gemini-3-flash-preview', tools=tools, max_tokens=mtok, web_search_options={})
184
- ```
185
-
186
- Tomorrow in Paris (Saturday, June 13), the weather is expected to be mostly pleasant and sunny.
187
-
188
- While there is a small chance of light, passing showers (around a 20-25% chance), most forecasts indicate a dry day with mostly clear or scattered clouds. Temperatures will likely reach a comfortable high of around 22°C to 27°C (72°F to 80°F), making it a great day for being outdoors.
189
-
190
- So, while you might see a stray shower, you likely won't need to worry about heavy rain!
191
-
192
138
  ## Tool Choice
193
139
 
194
140
  Control whether the model must use tools, can’t use tools, or decides on its own:
195
141
 
196
142
  ``` python
197
143
  # Force the model to call a tool (even for a greeting)
198
- r = await stream([user("Hello there!")], model='claude-sonnet-4-20250514', tools=tools, tool_choice='required', max_tokens=mtok)
144
+ r = await stream([user("Hello there!")], model='claude-sonnet-5', tools=tools, tool_choice='required', max_tokens=mtok)
199
145
  print("Forced:", r.tool_calls)
200
146
 
201
147
  # Prevent tool use (model must answer directly)
202
148
  print("\nNo tools: ", end='')
203
- r = await stream([user("What's the weather?")], model='claude-sonnet-4-20250514', tools=tools, tool_choice='none', max_tokens=mtok)
149
+ r = await stream([user("What's the weather?")], model='claude-sonnet-5', tools=tools, tool_choice='none', max_tokens=mtok)
204
150
  ```
205
151
 
206
152
  - ⏳ `get_weather(city="<UNKNOWN>")` ⏳
@@ -311,11 +257,11 @@ long_ctx = "You are an expert on the solar system. " * 200
311
257
  system = Text(long_ctx, cache_control={'type': 'ephemeral'})
312
258
 
313
259
  print("Call 1: ", end='')
314
- r1 = await stream([user("What is Jupiter's mass?")], model='claude-sonnet-4-20250514', system=system, max_tokens=mtok)
260
+ r1 = await stream([user("What is Jupiter's mass?")], model='claude-sonnet-5', system=system, max_tokens=mtok)
315
261
  print(f"Usage: {r1.usage}")
316
262
 
317
263
  print("Call 2: ", end='')
318
- r2 = await stream([user("How about Saturn?")], model='claude-sonnet-4-20250514', system=system, max_tokens=mtok)
264
+ r2 = await stream([user("How about Saturn?")], model='claude-sonnet-5', system=system, max_tokens=mtok)
319
265
  print(f"Usage: {r2.usage}")
320
266
  ```
321
267
 
@@ -365,13 +311,12 @@ print(f"Usage: {r2.usage}")
365
311
  Send images to any provider that supports them. The canonical `input_image` part works everywhere:
366
312
 
367
313
  ``` python
368
- img_url = "https://img.freepik.com/free-photo/mountain-range-body-water_53876-139760.jpg?semt=ais_hybrid&w=740&q=80"
369
314
  img_msg = Msg(role='user', content=[
370
- InputImage(img_url),
315
+ InputImage(sample_img_url),
371
316
  Text("What do you see in this image?")
372
317
  ])
373
318
 
374
- for name, kw in [('claude-sonnet-4-20250514', {}), ('gpt-4o-mini', {}), ('models/gemini-3-flash-preview', {})]:
319
+ for name, kw in [('claude-sonnet-5', {}), ('gpt-4o-mini', {}), ('models/gemini-3-flash-preview', {})]:
375
320
  print(f"{name:>30s}: ", end='')
376
321
  r = await stream([img_msg], model=name, max_tokens=mtok, **kw)
377
322
  ```
@@ -2,4 +2,4 @@
2
2
 
3
3
  - `fastllm.responses`: Provider-independent Responses resources and streaming over FastLLM"""
4
4
 
5
- __version__ = "0.0.49"
5
+ __version__ = "0.0.51"
@@ -25,6 +25,7 @@ d = { 'settings': { 'branch': 'main',
25
25
  'fastllm.anthropic._sanid': ('anthropic.html#_sanid', 'fastllm/anthropic.py'),
26
26
  'fastllm.anthropic.acollect_stream': ('anthropic.html#acollect_stream', 'fastllm/anthropic.py'),
27
27
  'fastllm.anthropic.apply_cache_idxs': ('anthropic.html#apply_cache_idxs', 'fastllm/anthropic.py'),
28
+ 'fastllm.anthropic.collate_raw': ('anthropic.html#collate_raw', 'fastllm/anthropic.py'),
28
29
  'fastllm.anthropic.cost': ('anthropic.html#cost', 'fastllm/anthropic.py'),
29
30
  'fastllm.anthropic.delta_index_fn': ('anthropic.html#delta_index_fn', 'fastllm/anthropic.py'),
30
31
  'fastllm.anthropic.denorm_assistant': ('anthropic.html#denorm_assistant', 'fastllm/anthropic.py'),
@@ -49,7 +50,9 @@ d = { 'settings': { 'branch': 'main',
49
50
  'fastllm.anthropic.norm_tool_call': ('anthropic.html#norm_tool_call', 'fastllm/anthropic.py'),
50
51
  'fastllm.anthropic.norm_tool_calls': ('anthropic.html#norm_tool_calls', 'fastllm/anthropic.py'),
51
52
  'fastllm.anthropic.norm_tr_parts': ('anthropic.html#norm_tr_parts', 'fastllm/anthropic.py'),
52
- 'fastllm.anthropic.norm_usage': ('anthropic.html#norm_usage', 'fastllm/anthropic.py')},
53
+ 'fastllm.anthropic.norm_usage': ('anthropic.html#norm_usage', 'fastllm/anthropic.py'),
54
+ 'fastllm.anthropic.raw_msg': ('anthropic.html#raw_msg', 'fastllm/anthropic.py'),
55
+ 'fastllm.anthropic.search_hits': ('anthropic.html#search_hits', 'fastllm/anthropic.py')},
53
56
  'fastllm.chat': { 'fastllm.chat.AsyncChat': ('chat.html#asyncchat', 'fastllm/chat.py'),
54
57
  'fastllm.chat.AsyncChat.__call__': ('chat.html#asyncchat.__call__', 'fastllm/chat.py'),
55
58
  'fastllm.chat.AsyncChat.__init__': ('chat.html#asyncchat.__init__', 'fastllm/chat.py'),
@@ -139,6 +142,7 @@ d = { 'settings': { 'branch': 'main',
139
142
  'fastllm.gemini': { 'fastllm.gemini._gem_filter_sch': ('gemini.html#_gem_filter_sch', 'fastllm/gemini.py'),
140
143
  'fastllm.gemini._gem_part_type': ('gemini.html#_gem_part_type', 'fastllm/gemini.py'),
141
144
  'fastllm.gemini.acollect_stream': ('gemini.html#acollect_stream', 'fastllm/gemini.py'),
145
+ 'fastllm.gemini.collate_raw': ('gemini.html#collate_raw', 'fastllm/gemini.py'),
142
146
  'fastllm.gemini.cost': ('gemini.html#cost', 'fastllm/gemini.py'),
143
147
  'fastllm.gemini.delta_index_fn': ('gemini.html#delta_index_fn', 'fastllm/gemini.py'),
144
148
  'fastllm.gemini.denorm_assistant': ('gemini.html#denorm_assistant', 'fastllm/gemini.py'),
@@ -163,8 +167,10 @@ d = { 'settings': { 'branch': 'main',
163
167
  'fastllm.gemini.norm_parts': ('gemini.html#norm_parts', 'fastllm/gemini.py'),
164
168
  'fastllm.gemini.norm_sse_event': ('gemini.html#norm_sse_event', 'fastllm/gemini.py'),
165
169
  'fastllm.gemini.norm_tool_calls': ('gemini.html#norm_tool_calls', 'fastllm/gemini.py'),
166
- 'fastllm.gemini.norm_usage': ('gemini.html#norm_usage', 'fastllm/gemini.py')},
170
+ 'fastllm.gemini.norm_usage': ('gemini.html#norm_usage', 'fastllm/gemini.py'),
171
+ 'fastllm.gemini.raw_msg': ('gemini.html#raw_msg', 'fastllm/gemini.py')},
167
172
  'fastllm.openai_chat': { 'fastllm.openai_chat.acollect_stream': ('oai_chat.html#acollect_stream', 'fastllm/openai_chat.py'),
173
+ 'fastllm.openai_chat.collate_raw': ('oai_chat.html#collate_raw', 'fastllm/openai_chat.py'),
168
174
  'fastllm.openai_chat.cost': ('oai_chat.html#cost', 'fastllm/openai_chat.py'),
169
175
  'fastllm.openai_chat.delta_index_fn': ('oai_chat.html#delta_index_fn', 'fastllm/openai_chat.py'),
170
176
  'fastllm.openai_chat.denorm_assistant': ('oai_chat.html#denorm_assistant', 'fastllm/openai_chat.py'),
@@ -189,14 +195,15 @@ d = { 'settings': { 'branch': 'main',
189
195
  'fastllm.openai_chat.norm_finish': ('oai_chat.html#norm_finish', 'fastllm/openai_chat.py'),
190
196
  'fastllm.openai_chat.norm_parts': ('oai_chat.html#norm_parts', 'fastllm/openai_chat.py'),
191
197
  'fastllm.openai_chat.norm_sse_event': ('oai_chat.html#norm_sse_event', 'fastllm/openai_chat.py'),
192
- 'fastllm.openai_chat.norm_tool_calls': ('oai_chat.html#norm_tool_calls', 'fastllm/openai_chat.py')},
198
+ 'fastllm.openai_chat.norm_tool_calls': ('oai_chat.html#norm_tool_calls', 'fastllm/openai_chat.py'),
199
+ 'fastllm.openai_chat.raw_msg': ('oai_chat.html#raw_msg', 'fastllm/openai_chat.py')},
193
200
  'fastllm.openai_responses': { 'fastllm.openai_responses.Completion.response_id': ( 'oai_responses.html#completion.response_id',
194
201
  'fastllm/openai_responses.py'),
195
- 'fastllm.openai_responses.Completion.response_id_reusable': ( 'oai_responses.html#completion.response_id_reusable',
196
- 'fastllm/openai_responses.py'),
197
202
  'fastllm.openai_responses._sanid': ('oai_responses.html#_sanid', 'fastllm/openai_responses.py'),
198
203
  'fastllm.openai_responses.acollect_stream': ( 'oai_responses.html#acollect_stream',
199
204
  'fastllm/openai_responses.py'),
205
+ 'fastllm.openai_responses.collate_raw': ( 'oai_responses.html#collate_raw',
206
+ 'fastllm/openai_responses.py'),
200
207
  'fastllm.openai_responses.cost': ('oai_responses.html#cost', 'fastllm/openai_responses.py'),
201
208
  'fastllm.openai_responses.delta_index_fn': ( 'oai_responses.html#delta_index_fn',
202
209
  'fastllm/openai_responses.py'),
@@ -245,13 +252,19 @@ d = { 'settings': { 'branch': 'main',
245
252
  'fastllm.openai_responses.norm_tool_calls': ( 'oai_responses.html#norm_tool_calls',
246
253
  'fastllm/openai_responses.py'),
247
254
  'fastllm.openai_responses.norm_usage': ( 'oai_responses.html#norm_usage',
248
- 'fastllm/openai_responses.py')},
255
+ 'fastllm/openai_responses.py'),
256
+ 'fastllm.openai_responses.raw_msg': ( 'oai_responses.html#raw_msg',
257
+ 'fastllm/openai_responses.py')},
249
258
  'fastllm.responses': { 'fastllm.responses.AsyncResponses': ('responses.html#asyncresponses', 'fastllm/responses.py'),
259
+ 'fastllm.responses.AsyncResponses.__init__': ( 'responses.html#asyncresponses.__init__',
260
+ 'fastllm/responses.py'),
250
261
  'fastllm.responses.AsyncResponses.call': ('responses.html#asyncresponses.call', 'fastllm/responses.py'),
251
262
  'fastllm.responses.AsyncResponses.events': ( 'responses.html#asyncresponses.events',
252
263
  'fastllm/responses.py'),
253
264
  'fastllm.responses.AsyncResponses.prepare': ( 'responses.html#asyncresponses.prepare',
254
265
  'fastllm/responses.py'),
266
+ 'fastllm.responses.AsyncResponses.serve': ( 'responses.html#asyncresponses.serve',
267
+ 'fastllm/responses.py'),
255
268
  'fastllm.responses.AsyncResponses.server_results': ( 'responses.html#asyncresponses.server_results',
256
269
  'fastllm/responses.py'),
257
270
  'fastllm.responses.AsyncResponses.server_turn': ( 'responses.html#asyncresponses.server_turn',
@@ -1,21 +1,21 @@
1
1
  # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_anthropic.ipynb.
2
2
 
3
3
  # %% auto #0
4
- __all__ = ['ant_tc_types', 'norm_tool_call', 'norm_tool_calls', 'norm_usage', 'finalize_usage', 'norm_finish', 'norm_parts',
5
- 'norm_tr_parts', 'norm_sse_event', 'delta_index_fn', 'acollect_stream', 'denorm_tool_use',
6
- 'denorm_assistant', 'denorm_tool', 'denorm_msgs', 'denorm_tool_schs', 'denorm_tool_choice',
7
- 'denorm_reasoning', 'denorm_web_search', 'denorm_system', 'denorm_user', 'denorm_image', 'denorm_file',
8
- 'denorm_tool_result', 'apply_cache_idxs', 'mk_payload', 'get_hdrs', 'cost']
4
+ __all__ = ['ant_tc_types', 'norm_tool_call', 'norm_tool_calls', 'norm_usage', 'finalize_usage', 'norm_finish', 'search_hits',
5
+ 'norm_parts', 'raw_msg', 'norm_tr_parts', 'norm_sse_event', 'delta_index_fn', 'collate_raw',
6
+ 'acollect_stream', 'denorm_tool_use', 'denorm_assistant', 'denorm_tool', 'denorm_msgs', 'denorm_tool_schs',
7
+ 'denorm_tool_choice', 'denorm_reasoning', 'denorm_web_search', 'denorm_system', 'denorm_user',
8
+ 'denorm_image', 'denorm_file', 'denorm_tool_result', 'apply_cache_idxs', 'mk_payload', 'get_hdrs', 'cost']
9
9
 
10
10
  # %% ../nbs/04_anthropic.ipynb #02afd3d7
11
- import json
11
+ import json, copy
12
12
  from collections import Counter
13
13
  from fastcore.utils import *
14
14
  from fastcore.meta import *
15
15
  from fasttransport.errors import api_error_from_event
16
16
 
17
17
  from .types import *
18
- from aidialog.msg_parts import (Part, PartType, mk_part, Msg, Text, Thinking, ToolUse, ToolResult, tool_text, ServerToolResult,
18
+ from aidialog.msg_parts import (Part, PartType, mk_part, Msg, Completion, Text, Thinking, ToolUse, ToolResult, tool_text,
19
19
  InputImage, InputAudio, InputVideo, InputFile, data_url)
20
20
  from .streaming import *
21
21
  from .streaming import mk_acollect_stream
@@ -47,11 +47,11 @@ def norm_usage(resp):
47
47
  cached_tokens=cached, cache_creation_tokens=cache_creation, reasoning_tokens=0, raw=usg)
48
48
 
49
49
  def finalize_usage(usg, parts):
50
- "Adjust usage using finalized Anthropic content parts."
50
+ "Split reasoning tokens out of `output_tokens`: the reported `thinking_tokens`, else an estimate from the thinking text."
51
51
  if not usg: return usg
52
52
  rc = '\n'.join(p.text or '' for p in parts if isinstance(p, Thinking))
53
53
  ct = int(usg.raw.get('output_tokens', usg.completion_tokens) or 0)
54
- rt = min(int(len(rc.split())*1.5), ct) if rc else 0
54
+ rt = int(nested_idx(usg.raw, 'output_tokens_details', 'thinking_tokens') or 0) or (min(int(len(rc.split())*1.5), ct) if rc else 0)
55
55
  return Usage(prompt_tokens=usg.prompt_tokens, completion_tokens=ct-rt, total_tokens=usg.prompt_tokens+ct,
56
56
  cached_tokens=usg.cached_tokens, cache_creation_tokens=usg.cache_creation_tokens, reasoning_tokens=rt, raw=usg.raw)
57
57
 
@@ -67,20 +67,31 @@ def norm_finish(resp, tcs=None):
67
67
  def _ant_part_type(typ):
68
68
  "Map Anthropic content block type to canonical PartType."
69
69
  ant_parts_mapping = dict(text=PartType.text, thinking=PartType.thinking, redacted_thinking=PartType.thinking, tool_use=PartType.tool_use, server_tool_use=PartType.tool_use, mcp_tool_use=PartType.tool_use)
70
- if typ in ant_parts_mapping: return ant_parts_mapping[typ]
71
- if typ.endswith('_tool_result'): return PartType.server_tool_result
72
- return typ
70
+ return ant_parts_mapping.get(typ, typ)
71
+
72
+ def search_hits(parts, blocks):
73
+ "Set each server call's `text` to the `title: url` lines of its result block, when the response has one"
74
+ calls = {p.id: p for p in parts if isinstance(p, ToolUse)}
75
+ for b in blocks:
76
+ if b.get('type', '').endswith('_tool_result') and (tc := calls.get(b.get('tool_use_id'))):
77
+ tc.text = '\n'.join(f"{r.get('title', '')}: {r.get('url', '')}" for r in b.get('content') or [] if isinstance(r, dict) and r.get('url'))
78
+ return parts
73
79
 
74
80
  def norm_parts(resp):
81
+ "Canonical parts of a response; a server tool's result block lives in the raw message, and as the call's `text`"
75
82
  parts = []
76
83
  for b in resp.get("content", []):
77
84
  typ = _ant_part_type(b.get("type", "text"))
78
85
  if typ == PartType.thinking: parts.append(Thinking(b.get("thinking", ""), raw=b))
79
86
  elif typ == PartType.tool_use:
80
87
  if tc := norm_tool_call(b): parts.append(tc)
81
- elif typ == PartType.server_tool_result: parts.append(ServerToolResult(b.get("text", ""), raw=b))
82
- else: parts.append(Text(b.get("text", ""), raw=b))
83
- return parts
88
+ elif typ == PartType.text: parts.append(Text(b.get("text", ""), raw=b))
89
+ return search_hits(parts, resp.get("content", []))
90
+
91
+ # %% ../nbs/04_anthropic.ipynb #f24e52db
92
+ def raw_msg(resp):
93
+ "The assistant message as the API sent it"
94
+ return dict(role='assistant', content=resp['content'])
84
95
 
85
96
  # %% ../nbs/04_anthropic.ipynb #5d1440b7
86
97
  def norm_tr_parts(content):
@@ -103,7 +114,6 @@ def norm_sse_event(ev, **kwargs):
103
114
  text, thinking, tcs, citations = None, None, [], None
104
115
  if typ == "content_block_start":
105
116
  cb = ev.get("content_block", {})
106
- if cb.get("type", "").endswith("_tool_result"): return Delta(server_tool_result=cb, raw=ev, **kwargs)
107
117
  if tc := norm_tool_call(cb):
108
118
  if not tc.arguments: tc.arguments = {'_delta': ''}
109
119
  tcs = [tc]
@@ -127,11 +137,30 @@ def delta_index_fn(d, typ, last_typ, last_idx):
127
137
  'Returns accumulation index for current delta and updated last idx'
128
138
  return nested_idx(d, 'raw', 'index'), None
129
139
 
140
+ # %% ../nbs/04_anthropic.ipynb #de900e34
141
+ def collate_raw(deltas):
142
+ "The assistant message rebuilt from a stream's events"
143
+ blocks = {}
144
+ for ev in L(deltas).attrgot('raw'):
145
+ typ,i = ev.get('type'),ev.get('index')
146
+ if typ == 'content_block_start': blocks[i] = copy.deepcopy(ev['content_block'])
147
+ elif typ == 'content_block_delta':
148
+ d,b = ev['delta'],blocks[i]
149
+ if d['type'] == 'text_delta': b['text'] += d['text']
150
+ elif d['type'] == 'thinking_delta': b['thinking'] += d['thinking']
151
+ elif d['type'] == 'signature_delta': b['signature'] = d['signature']
152
+ elif d['type'] == 'input_json_delta': b['_json'] = b.get('_json', '') + d['partial_json']
153
+ elif d['type'] == 'citations_delta': b['citations'] = (b.get('citations') or []) + [d['citation']]
154
+ elif typ == 'content_block_stop' and '_json' in blocks[i]: blocks[i]['input'] = json.loads(blocks[i].pop('_json') or '{}')
155
+ return dict(role='assistant', content=list(blocks.values()))
156
+
130
157
  # %% ../nbs/04_anthropic.ipynb #c994adb1
131
158
  @delegates(mk_acollect_stream, but=['index_fn', 'api_name'])
132
159
  async def acollect_stream(resp, **kwargs):
133
160
  res = mk_acollect_stream(norm_and_yield(resp, norm_sse_event), index_fn=delta_index_fn, api_name='anthropic', **kwargs)
134
- async for o in res: yield o
161
+ async for o in res:
162
+ if isinstance(o, Completion): search_hits(o.message.content, o.message.raw['content'])
163
+ yield o
135
164
 
136
165
  # %% ../nbs/04_anthropic.ipynb #bb11ab62
137
166
  def _ant_cc(block, p):
@@ -145,44 +174,29 @@ def _sanid(id_str): return re.sub(r'[^a-zA-Z0-9_-]', '_', id_str or '')
145
174
  # %% ../nbs/04_anthropic.ipynb #6ec772cb
146
175
  def denorm_tool_use(p:ToolUse):
147
176
  "Convert canonical tool_use Part to Anthropic tool_use content block."
148
- block = dict(type='tool_use', id=_sanid(p.id or ''), name=p.name or '', input=p.arguments or {})
149
- if caller := (p.raw or {}).get('caller'): block['caller'] = caller
150
- return _ant_cc(block, p)
177
+ return _ant_cc(dict(type='tool_use', id=_sanid(p.id or ''), name=p.name or '', input=p.arguments or {}), p)
151
178
 
152
179
  def denorm_assistant(m:Msg):
153
- "Convert canonical assistant Msg to Anthropic assistant message + synthetic tool results for non-Anthropic server tools."
154
- blocks, srv_results, srv_call_id = [], [], None
155
- for p in m.content:
156
- if isinstance(p, (Thinking, Text)):
157
- if srv_call_id:
158
- srv_results.append(dict(type='tool_result', tool_use_id=srv_call_id, content=p.text or ''))
159
- srv_call_id = None
160
- elif isinstance(p, Thinking) and (sig:=(p.raw or {}).get('signature','')):
161
- blocks.append(dict(type='thinking', thinking=p.text or '', signature=sig))
162
- else: blocks.append(_ant_cc(dict(type='text', text=p.text or ''), p))
163
- elif isinstance(p, ToolUse):
164
- if p.server and (p.id or '').startswith('srvtoolu_'):
165
- blocks.append(dict(type='server_tool_use', id=p.id, name=p.name or '', input=p.arguments or {}))
166
- else:
167
- blocks.append(denorm_tool_use(p))
168
- if p.server: srv_call_id = p.id or ''
169
- elif isinstance(p, ServerToolResult): blocks.append(p.raw or dict(type='server_tool_result'))
170
- res = [dict(role='assistant', content=blocks)]
171
- if srv_results: res.append(dict(role='user', content=srv_results))
172
- return res
180
+ "The message as the API sent it, else its text and tool calls; a cache mark on the last part is copied onto the last raw block"
181
+ if m.raw:
182
+ cc = [p.cache_control for p in m.content if p.cache_control]
183
+ if not cc: return m.raw
184
+ return m.raw | dict(content=m.raw['content'][:-1] + [m.raw['content'][-1] | dict(cache_control=cc[-1])])
185
+ blocks = [_ant_cc(dict(type='text', text=p.text or ''), p) if isinstance(p, Text) else denorm_tool_use(p) for p in m.content if isinstance(p, (Text, ToolUse))]
186
+ return dict(role='assistant', content=blocks)
173
187
 
174
188
  def denorm_tool(m:Msg):
175
189
  "Convert canonical tool Msg to Anthropic user message with tool_result blocks."
176
190
  blocks = [denorm_tool_result(p) for p in m.content if isinstance(p, ToolResult)]
177
- return [dict(role='user', content=blocks)]
191
+ return dict(role='user', content=blocks)
178
192
 
179
193
  def denorm_msgs(msgs:list[Msg]):
180
194
  "Convert list of canonical Msgs to Anthropic messages."
181
195
  res = []
182
196
  for m in msgs:
183
197
  if m.role == 'user': res.append(denorm_user(m))
184
- elif m.role == 'assistant': res.extend(denorm_assistant(m))
185
- elif m.role == 'tool': res.extend(denorm_tool(m))
198
+ elif m.role == 'assistant': res.append(denorm_assistant(m))
199
+ elif m.role == 'tool': res.append(denorm_tool(m))
186
200
  return res
187
201
 
188
202
  # %% ../nbs/04_anthropic.ipynb #f762a6f2
@@ -346,5 +360,6 @@ def cost(usage, m):
346
360
 
347
361
  # %% ../nbs/04_anthropic.ipynb #f7c0b989
348
362
  api_registry.register('anthropic', norm_tool_calls=norm_tool_calls, norm_parts=norm_parts, norm_finish=norm_finish, norm_usage=norm_usage,
349
- finalize_usage=finalize_usage, acollect_stream=acollect_stream, mk_payload=mk_payload, cost=cost, get_hdrs=get_hdrs,
363
+ finalize_usage=finalize_usage, raw_msg=raw_msg, collate_raw=collate_raw, acollect_stream=acollect_stream, mk_payload=mk_payload,
364
+ cost=cost, get_hdrs=get_hdrs,
350
365
  endpoint='/v1/messages')