Asynchronous Client¶
bookwyrm.AsyncBookWyrmClient ¶
AsyncBookWyrmClient(
base_url: str = "https://api.bookwyrm.ai:443",
api_key: Optional[str] = None,
timeout: Optional[float] = None,
)
Asynchronous client for BookWyrm API.
The asynchronous client provides full async/await support for all BookWyrm API endpoints
using the httpx library. It supports concurrent operations, streaming responses,
and automatic session management with proper cleanup.
Examples:
Basic async client usage:
import asyncio
from bookwyrm import AsyncBookWyrmClient
async def main():
# Using environment variable for API key
client = AsyncBookWyrmClient()
# Explicit API key
client = AsyncBookWyrmClient(api_key="your-api-key")
# Custom base URL
client = AsyncBookWyrmClient(
base_url="https://custom-api.example.com",
api_key="your-api-key"
)
asyncio.run(main())
Async context manager for automatic cleanup:
async def example():
async with AsyncBookWyrmClient() as client:
response = await client.get_citations(request)
# Client is automatically closed when exiting the context
Concurrent operations:
async def concurrent_operations():
async with AsyncBookWyrmClient() as client:
# Run multiple operations concurrently
tasks = [
client.get_citations(request1),
client.get_citations(request2),
client.summarize(summarize_request)
]
results = await asyncio.gather(*tasks)
return results
Initialize the async BookWyrm client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Base URL of the BookWyrm API. Defaults to "https://api.bookwyrm.ai:443" |
'https://api.bookwyrm.ai:443'
|
api_key
|
Optional[str]
|
API key for authentication. If not provided, will attempt to read from BOOKWYRM_API_KEY environment variable |
None
|
timeout
|
Optional[float]
|
Request timeout in seconds. Defaults to None (no timeout). Set to a float for specific timeout. |
None
|
Examples:
# Basic initialization
client = AsyncBookWyrmClient()
# With explicit API key
client = AsyncBookWyrmClient(api_key="your-api-key")
# With custom endpoint and timeout
client = AsyncBookWyrmClient(
base_url="https://localhost:8000",
api_key="dev-key",
timeout=60.0
)
# With infinite timeout (default)
client = AsyncBookWyrmClient()
Source code in bookwyrm/async_client.py
get_citations
async
¶
get_citations(
*,
chunks: Optional[List[TextSpan]] = None,
jsonl_content: Optional[str] = None,
jsonl_url: Optional[str] = None,
question: str,
start: Optional[int] = 0,
limit: Optional[int] = None,
max_tokens_per_chunk: Optional[int] = 1000,
model_strength: ModelStrength = ModelStrength.SWIFT
) -> CitationResponse
Get citations for a question from text chunks asynchronously.
This async method finds relevant citations that answer a specific question by analyzing the provided text chunks. Each citation includes a quality score (0-4) and reasoning for why it's relevant to the question.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Optional[List[TextSpan]]
|
List of text chunks to search |
None
|
jsonl_content
|
Optional[str]
|
Raw JSONL content as string |
None
|
jsonl_url
|
Optional[str]
|
URL to fetch JSONL content from |
None
|
question
|
str
|
The question to find citations for |
required |
start
|
Optional[int]
|
Starting chunk index (0-based) |
0
|
limit
|
Optional[int]
|
Maximum number of chunks to process |
None
|
max_tokens_per_chunk
|
Optional[int]
|
Maximum tokens per chunk |
1000
|
Returns:
| Type | Description |
|---|---|
CitationResponse
|
Citation response with found citations, total count, and usage information |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async citation finding:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import TextSpan
async def find_citations():
# Create some example chunks
chunks = [
TextSpan(text="The sky is blue due to Rayleigh scattering.", start_char=0, end_char=42),
TextSpan(text="Water molecules are polar.", start_char=43, end_char=69),
TextSpan(text="Plants appear green due to chlorophyll.", start_char=70, end_char=109)
]
async with AsyncBookWyrmClient(api_key="your-api-key") as client:
response = await client.get_citations(
chunks=chunks,
question="Why is the sky blue?"
)
print(f"Found {response.total_citations} citations")
for citation in response.citations:
print(f"Quality: {citation.quality}/4")
print(f"Text: {citation.text}")
asyncio.run(find_citations())
Concurrent citation requests:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import TextSpan
async def concurrent_citations():
# Create example chunks for different topics
chunks1 = [TextSpan(text="The sky is blue due to Rayleigh scattering.", start_char=0, end_char=42)]
chunks2 = [TextSpan(text="Water boils at 100°C at sea level.", start_char=0, end_char=34)]
chunks3 = [TextSpan(text="Photosynthesis converts CO2 to oxygen.", start_char=0, end_char=38)]
async with AsyncBookWyrmClient(api_key="your-api-key") as client:
# Process all requests concurrently
responses = await asyncio.gather(
client.get_citations(chunks=chunks1, question="Why is the sky blue?"),
client.get_citations(chunks=chunks2, question="At what temperature does water boil?"),
client.get_citations(chunks=chunks3, question="What does photosynthesis produce?")
)
for i, response in enumerate(responses):
print(f"Request {i+1}: {response.total_citations} citations")
asyncio.run(concurrent_citations())
Source code in bookwyrm/async_client.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
classify
async
¶
classify(
*,
content: Optional[str] = None,
content_bytes: Optional[bytes] = None,
filename: Optional[str] = None,
content_encoding: str = "raw"
) -> ClassifyResponse
Classify file content to determine file type and format asynchronously.
This async method analyzes file content to determine format type, content type, MIME type, and other classification details. It supports both binary and text files, providing confidence scores and additional metadata about the detected format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
Optional[str]
|
File content as string (raw text or base64-encoded) |
None
|
content_bytes
|
Optional[bytes]
|
Raw file bytes |
None
|
filename
|
Optional[str]
|
Optional filename hint for classification |
None
|
content_encoding
|
str
|
Content encoding format ("raw" for plain text, "base64" for encoded) |
'raw'
|
Returns:
| Type | Description |
|---|---|
ClassifyResponse
|
Classification response with detected file type, confidence score, and additional details |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async file classification:
async def classify_file():
# Read file as binary
with open("document.pdf", "rb") as f:
file_bytes = f.read()
async with AsyncBookWyrmClient() as client:
response = await client.classify(
content_bytes=file_bytes,
filename="document.pdf"
)
print(f"File type: {response.classification.format_type}")
print(f"Confidence: {response.classification.confidence:.2%}")
asyncio.run(classify_file())
Classify multiple files concurrently:
async def classify_multiple_files():
files = ["doc1.pdf", "script.py", "data.json", "image.jpg"]
async def classify_single(filename):
file_path = Path(filename)
return filename, await client.classify(
content_bytes=file_path.read_bytes(),
filename=file_path.name
)
async with AsyncBookWyrmClient() as client:
results = await asyncio.gather(*[
classify_single(f) for f in files
])
for filename, response in results:
print(f"{filename}: {response.classification.content_type} ({response.classification.confidence:.1%})")
Source code in bookwyrm/async_client.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | |
query_character_range
async
¶
query_character_range(
*,
mapping: Optional[PDFTextMapping] = None,
mapping_file: Optional[Path] = None,
start_char: int,
end_char: int,
output_file: Optional[Path] = None
) -> Dict[str, Any]
Query character positions to get bounding boxes from mapping object or file asynchronously.
This async method queries a character range to get the corresponding bounding boxes, pages, and sample text. It can work with either an in-memory PDFTextMapping object or load from a mapping file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Optional[PDFTextMapping]
|
In-memory PDFTextMapping object |
None
|
mapping_file
|
Optional[Path]
|
Path to character mapping JSON file |
None
|
start_char
|
int
|
Starting character index (inclusive) |
required |
end_char
|
int
|
Ending character index (exclusive) |
required |
output_file
|
Optional[Path]
|
Optional path to save query results |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing query results with bounding boxes, pages, and sample text |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither mapping nor mapping_file is provided, or if character range is invalid |
FileNotFoundError
|
If mapping_file doesn't exist |
Examples:
Query from in-memory mapping:
# After creating mapping from pages
mapping = create_pdf_text_mapping_from_pages(pages)
result = await client.query_character_range(
mapping=mapping,
start_char=100,
end_char=200
)
print(f"Found bounding boxes on {len(result['pages'])} pages")
Query from mapping file:
result = await client.query_character_range(
mapping_file=Path("data/mapping.json"),
start_char=100,
end_char=200,
output_file=Path("data/query_results.json")
)
Source code in bookwyrm/async_client.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 | |
stream_classify
async
¶
stream_classify(
*,
content: Optional[str] = None,
content_bytes: Optional[bytes] = None,
filename: Optional[str] = None,
content_encoding: str = "raw"
) -> AsyncIterator[StreamingClassifyResponse]
Stream file classification with real-time progress updates asynchronously.
This async method provides real-time streaming of file classification progress, allowing you to process classification results as they become available. Useful for large files or when you want to show progress to users during classification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
Optional[str]
|
File content as string (raw text or base64-encoded) |
None
|
content_bytes
|
Optional[bytes]
|
Raw file bytes |
None
|
filename
|
Optional[str]
|
Optional filename hint for classification |
None
|
content_encoding
|
str
|
Content encoding format ("raw" for plain text, "base64" for encoded) |
'raw'
|
Yields:
| Name | Type | Description |
|---|---|---|
StreamingClassifyResponse |
AsyncIterator[StreamingClassifyResponse]
|
Union of progress updates, classification results, or error messages |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async streaming classification:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import ClassifyProgressUpdate, ClassifyStreamResponse, ClassifyErrorResponse
async def classify_file_stream():
# Read file as binary
with open("document.pdf", "rb") as f:
file_bytes = f.read()
async with AsyncBookWyrmClient(api_key="your-api-key") as client:
classification_result = None
async for response in client.stream_classify(
content_bytes=file_bytes,
filename="document.pdf"
):
if isinstance(response, ClassifyProgressUpdate): # Progress update
print(f"Progress: {response.message}")
elif isinstance(response, ClassifyStreamResponse): # Classification result
classification_result = response
print(f"Format: {response.classification.format_type}")
print(f"Confidence: {response.classification.confidence:.2%}")
elif isinstance(response, ClassifyErrorResponse): # Error
print(f"Error: {response.message}")
asyncio.run(classify_file_stream())
Concurrent classification of multiple files:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import ClassifyStreamResponse
async def classify_multiple_files():
files = ["doc1.pdf", "script.py", "data.json"]
async def classify_single(filename):
file_path = Path(filename)
results = []
async with AsyncBookWyrmClient() as client:
async for response in client.stream_classify(
content_bytes=file_path.read_bytes(),
filename=file_path.name
):
if isinstance(response, ClassifyStreamResponse):
results.append((filename, response))
return results
all_results = await asyncio.gather(*[
classify_single(f) for f in files
])
for file_results in all_results:
for filename, response in file_results:
print(f"{filename}: {response.classification.content_type}")
asyncio.run(classify_multiple_files())
Source code in bookwyrm/async_client.py
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 | |
stream_process_text
async
¶
stream_process_text(
*,
text: Optional[str] = None,
text_url: Optional[str] = None,
chunk_size: Optional[int] = None,
response_format: Union[
ResponseFormat,
Literal[
"with_offsets", "offsets", "text_only", "text"
],
] = ResponseFormat.WITH_OFFSETS,
offsets: Optional[bool] = None,
text_only: Optional[bool] = None
) -> AsyncIterator[StreamingPhrasalResponse]
Stream text processing using phrasal analysis with async real-time results.
This async method breaks down text into meaningful phrases or chunks using NLP, supporting both direct text input and URLs. It can create fixed-size chunks or extract individual phrases with optional position information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
Optional[str]
|
Text content to process |
None
|
text_url
|
Optional[str]
|
URL to fetch text from |
None
|
chunk_size
|
Optional[int]
|
Optional chunk size for fixed-size chunking |
None
|
response_format
|
Union[ResponseFormat, Literal['with_offsets', 'offsets', 'text_only', 'text']]
|
Response format - use ResponseFormat enum, "with_offsets"/"offsets", or "text_only"/"text" |
WITH_OFFSETS
|
offsets
|
Optional[bool]
|
Set to True for WITH_OFFSETS format (boolean flag) |
None
|
text_only
|
Optional[bool]
|
Set to True for TEXT_ONLY format (boolean flag) |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
StreamingPhrasalResponse |
AsyncIterator[StreamingPhrasalResponse]
|
Union of progress updates and phrase/chunk results |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async phrasal processing:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import ResponseFormat, TextResult, TextSpanResult, PhraseProgressUpdate
async def process_text_example():
text = "Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence."
phrases = []
async with AsyncBookWyrmClient(api_key="your-api-key") as client:
async for response in client.stream_process_text(
text=text,
offsets=True # or response_format="with_offsets" or ResponseFormat.WITH_OFFSETS
):
if isinstance(response, (TextResult, TextSpanResult)): # Phrase result
phrases.append(response)
elif isinstance(response, PhraseProgressUpdate): # Progress
print(f"Progress: {response.message}")
print(f"Extracted {len(phrases)} phrases")
asyncio.run(process_text_example())
Process multiple texts concurrently:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import TextResult, TextSpanResult
async def process_multiple_texts():
async def process_single(text, name):
phrases = []
async with AsyncBookWyrmClient(api_key="your-api-key") as client:
async for response in client.stream_process_text(
text=text,
chunk_size=500
):
if isinstance(response, (TextResult, TextSpanResult)):
phrases.append(response)
return name, phrases
results = await asyncio.gather(
process_single(text1, "Text1"),
process_single(text2, "Text2"),
)
for name, phrases in results:
print(f"{name}: {len(phrases)} phrases")
asyncio.run(process_multiple_texts())
Process text from URL:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import TextResult, TextSpanResult
async def process_from_url():
async with AsyncBookWyrmClient(api_key="your-api-key") as client:
phrases: List[Union[TextResult, TextSpanResult]] = []
async for response in client.stream_process_text(
text_url="https://www.gutenberg.org/files/11/11-0.txt",
chunk_size=2000,
text_only=True
):
if isinstance(response, (TextResult, TextSpanResult)):
phrases.append(response)
print(f"Processed {len(phrases)} phrases from URL")
asyncio.run(process_from_url())
Source code in bookwyrm/async_client.py
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 | |
stream_citations
async
¶
stream_citations(
*,
chunks: Optional[List[TextSpan]] = None,
jsonl_content: Optional[str] = None,
jsonl_url: Optional[str] = None,
question: str,
start: Optional[int] = 0,
limit: Optional[int] = None,
max_tokens_per_chunk: Optional[int] = 1000,
model_strength: ModelStrength = ModelStrength.SWIFT
) -> AsyncIterator[StreamingCitationResponse]
Stream citations as they are found with real-time progress updates.
This async method provides real-time streaming of citation results, allowing you to process citations as they're found rather than waiting for all results. Useful for large datasets or when you want to show progress to users.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Optional[List[TextSpan]]
|
List of text chunks to search |
None
|
jsonl_content
|
Optional[str]
|
Raw JSONL content as string |
None
|
jsonl_url
|
Optional[str]
|
URL to fetch JSONL content from |
None
|
question
|
str
|
The question to find citations for |
required |
start
|
Optional[int]
|
Starting chunk index (0-based) |
0
|
limit
|
Optional[int]
|
Maximum number of chunks to process |
None
|
max_tokens_per_chunk
|
Optional[int]
|
Maximum tokens per chunk |
1000
|
Yields:
| Name | Type | Description |
|---|---|---|
StreamingCitationResponse |
AsyncIterator[StreamingCitationResponse]
|
Union of progress updates, individual citations, |
AsyncIterator[StreamingCitationResponse]
|
final summary, or error messages |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async streaming with function arguments:
import asyncio
from bookwyrm import AsyncBookWyrmClient
from bookwyrm.models import TextSpan, CitationProgressUpdate, CitationStreamResponse, CitationSummaryResponse
async def stream_citations_example():
# Create some example chunks
chunks = [
TextSpan(text="The sky is blue due to Rayleigh scattering.", start_char=0, end_char=42),
TextSpan(text="Water molecules are polar.", start_char=43, end_char=69),
TextSpan(text="Plants appear green due to chlorophyll.", start_char=70, end_char=109)
]
async with AsyncBookWyrmClient(api_key="your-api-key") as client:
citations = []
async for response in client.stream_citations(
chunks=chunks,
question="Why is the sky blue?"
):
if isinstance(response, CitationProgressUpdate): # Progress update
print(f"Progress: {response.message}")
elif isinstance(response, CitationStreamResponse): # Citation found
citations.append(response.citation)
print(f"Found: {response.citation.text[:50]}...")
elif isinstance(response, CitationSummaryResponse): # Summary
print(f"Complete: {response.total_citations} citations found")
asyncio.run(stream_citations_example())
Legacy request object usage (still supported):
from bookwyrm.models import CitationRequest
request = CitationRequest(
chunks=chunks,
question="Why is the sky blue?"
)
async for response in client.stream_citations(request):
# Process responses...
Source code in bookwyrm/async_client.py
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 | |
extract_pdf_simple
async
¶
extract_pdf_simple(
*,
pdf_url: Optional[str] = None,
pdf_content: Optional[str] = None,
pdf_bytes: Optional[bytes] = None,
filename: Optional[str] = None,
start_page: Optional[int] = None,
num_pages: Optional[int] = None,
lang: str = "en",
enable_layout_detection: bool = False,
force_ocr: bool = False
) -> AsyncIterator[StreamingPDFResponse]
Stream PDF extraction with simplified feature flags (async version).
Uses the new simplified PDF endpoint contract with essential parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdf_url
|
Optional[str]
|
URL to PDF file |
None
|
pdf_content
|
Optional[str]
|
Base64 encoded PDF content |
None
|
pdf_bytes
|
Optional[bytes]
|
Raw PDF bytes |
None
|
filename
|
Optional[str]
|
Optional filename hint |
None
|
start_page
|
Optional[int]
|
1-based page number to start from |
None
|
num_pages
|
Optional[int]
|
Number of pages to process from start_page |
None
|
lang
|
str
|
Language code for OCR processing (default: "en") |
'en'
|
enable_layout_detection
|
bool
|
Enable advanced layout detection |
False
|
force_ocr
|
bool
|
Force OCR even for native text PDFs (auto-enabled with layout detection) |
False
|
Source code in bookwyrm/async_client.py
stream_extract_pdf
async
¶
stream_extract_pdf(
*,
pdf_url: Optional[str] = None,
pdf_content: Optional[str] = None,
pdf_bytes: Optional[bytes] = None,
filename: Optional[str] = None,
start_page: Optional[int] = None,
num_pages: Optional[int] = None,
lang: str = "en",
enable_layout_detection: bool = False,
force_ocr: bool = False
) -> AsyncIterator[StreamingPDFResponse]
Stream PDF extraction with real-time progress updates asynchronously.
This async method provides real-time streaming of PDF extraction progress, yielding metadata, individual page results, and completion status. Useful for large PDFs where you want to show progress or process pages as they become available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdf_url
|
Optional[str]
|
URL to PDF file |
None
|
pdf_content
|
Optional[str]
|
Base64 encoded PDF content |
None
|
pdf_bytes
|
Optional[bytes]
|
Raw PDF bytes (will be encoded to base64) |
None
|
filename
|
Optional[str]
|
Optional filename hint |
None
|
start_page
|
Optional[int]
|
1-based page number to start from |
None
|
num_pages
|
Optional[int]
|
Number of pages to process from start_page |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
StreamingPDFResponse |
AsyncIterator[StreamingPDFResponse]
|
Union of metadata, page responses, page errors, completion, or general errors |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async streaming PDF extraction with function arguments:
async def stream_extract_pdf_example():
pages = []
async with AsyncBookWyrmClient() as client:
async for response in client.stream_extract_pdf(
pdf_bytes=pdf_bytes,
filename="document.pdf"
):
if isinstance(response, PDFStreamPageResponse): # Page extracted
pages.append(response.page_data)
print(f"Page {response.document_page}: {len(response.page_data.text_blocks)} elements")
elif isinstance(response, PDFStreamMetadata): # Metadata
print(f"Processing {response.total_pages} pages")
elif isinstance(response, PDFStreamPageError):
print(f"Error on page {response.document_page}: {response.error}")
print(f"Extracted {len(pages)} pages total")
asyncio.run(stream_extract_pdf_example())
Legacy request object usage (still supported):
from bookwyrm.models import PDFExtractRequest
request = PDFExtractRequest(
pdf_bytes=pdf_bytes,
filename="document.pdf"
)
async for response in client.stream_extract_pdf(request):
# Process responses...
Source code in bookwyrm/async_client.py
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 | |
close
async
¶
summarize
async
¶
summarize(
*,
content: Optional[str] = None,
url: Optional[str] = None,
phrases: Optional[List[TextSpan]] = None,
max_tokens: int = 10000,
model_strength: str = "swift",
debug: bool = False,
model_name: Optional[str] = None,
model_schema_json: Optional[str] = None,
summary_class: Optional[Type[BaseModel]] = None,
chunk_prompt: Optional[str] = None,
summary_of_summaries_prompt: Optional[str] = None
) -> SummaryResponse
Get a summary of the provided content using hierarchical summarization.
This async method performs intelligent summarization of text content, supporting both plain text summaries and structured output using Pydantic models. It can handle large documents through hierarchical chunking and summarization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
Optional[str]
|
Text content to summarize |
None
|
url
|
Optional[str]
|
URL to fetch content from |
None
|
phrases
|
Optional[List[TextSpan]]
|
List of text phrases to summarize |
None
|
max_tokens
|
int
|
Maximum tokens for chunking (default: 10000) |
10000
|
debug
|
bool
|
Include intermediate summaries in response |
False
|
Returns:
| Type | Description |
|---|---|
SummaryResponse
|
Summary response containing the generated summary, metadata, and optional debug information |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async summarization with function arguments:
async def summarize_text():
with open("book_phrases.jsonl", "r") as f:
content = f.read()
async with AsyncBookWyrmClient() as client:
response = await client.summarize(
content=content,
max_tokens=10000,
debug=True
)
print(response.summary)
print(f"Used {response.levels_used} levels")
asyncio.run(summarize_text())
Concurrent summarization of multiple documents:
async def summarize_multiple():
async with AsyncBookWyrmClient() as client:
summaries = await asyncio.gather(
client.summarize(content=content1, max_tokens=5000),
client.summarize(content=content2, max_tokens=5000),
client.summarize(content=content3, max_tokens=5000)
)
for i, summary in enumerate(summaries):
print(f"Document {i+1} summary: {summary.summary[:100]}...")
Legacy request object usage (still supported):
from bookwyrm.models import SummarizeRequest
request = SummarizeRequest(
content=content,
max_tokens=10000,
debug=True
)
response = await client.summarize(request)
Source code in bookwyrm/async_client.py
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 | |
stream_summarize
async
¶
stream_summarize(
*,
content: Optional[str] = None,
url: Optional[str] = None,
phrases: Optional[List[TextSpan]] = None,
max_tokens: int = 10000,
model_strength: str = "swift",
debug: bool = False,
model_name: Optional[str] = None,
model_schema_json: Optional[str] = None,
summary_class: Optional[Type[BaseModel]] = None,
chunk_prompt: Optional[str] = None,
summary_of_summaries_prompt: Optional[str] = None
) -> AsyncIterator[StreamingSummarizeResponse]
Stream summarization progress and results with real-time updates.
This async method provides real-time streaming of summarization progress, including hierarchical processing updates, retry attempts, and final results. Useful for long-running summarization tasks where you want to show progress to users.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
Optional[str]
|
Text content to summarize |
None
|
url
|
Optional[str]
|
URL to fetch content from |
None
|
phrases
|
Optional[List[TextSpan]]
|
List of text phrases to summarize |
None
|
max_tokens
|
int
|
Maximum tokens for chunking (default: 10000) |
10000
|
debug
|
bool
|
Include intermediate summaries in response |
False
|
Yields:
| Name | Type | Description |
|---|---|---|
StreamingSummarizeResponse |
AsyncIterator[StreamingSummarizeResponse]
|
Union of progress updates, final summary, rate limit messages, |
AsyncIterator[StreamingSummarizeResponse]
|
structural error messages, or general errors |
Raises:
| Type | Description |
|---|---|
BookWyrmAPIError
|
If the API request fails (network, authentication, server errors) |
Examples:
Basic async streaming summarization with function arguments:
async def stream_summarize_example():
async with AsyncBookWyrmClient() as client:
final_result = None
async for response in client.stream_summarize(
content=content,
max_tokens=5000,
debug=True
):
if isinstance(response, SummarizeProgressUpdate): # Progress update
print(f"Progress: {response.message}")
elif isinstance(response, SummaryResponse): # Final summary
final_result = response
print("Summary complete!")
if final_result:
print(final_result.summary)
asyncio.run(stream_summarize_example())
Legacy request object usage (still supported):
from bookwyrm.models import SummarizeRequest
request = SummarizeRequest(
content=content,
max_tokens=5000,
debug=True
)
async for response in client.stream_summarize(request):
# Process responses...
Source code in bookwyrm/async_client.py
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 | |
options: members: - init - stream_citations - stream_summarize - stream_process_text - classify - stream_extract_pdf - close - aenter - aexit show_root_heading: true show_source: true