Clients¶
Client for Interactions with LLMs (Language Models) This module provides a client interface for interacting with various LLMs. It includes functionality for sending requests, receiving responses, and handling errors.
AbstractClient ¶
AbstractClient(conversation_memory: Optional[ConversationMemory] = None, preset: Optional[str] = None, tools: Optional[List[Union[str, AbstractTool]]] = None, use_tools: bool = False, debug: bool = True, tool_manager: Optional[ToolManager] = None, **kwargs)
Bases: EventEmitterMixin, ABC
Abstract base Class for LLM models.
Source code in packages/ai-parrot/src/parrot/clients/base.py
client
property
writable
¶
Return the SDK client bound to the current event loop, or None.
The cache key is id(asyncio.get_running_loop()). Returns None
when called outside a running loop (e.g. in __init__ or sync code).
| RETURNS | DESCRIPTION |
|---|---|
Optional[Any]
|
The loop-local SDK client instance, or |
Optional[Any]
|
been created yet for the current loop. |
get_client
abstractmethod
async
¶
complete
async
¶
complete(prompt: str, *, model: Optional[str] = None, system_prompt: Optional[str] = None, max_tokens: Optional[int] = None, temperature: Optional[float] = None) -> str
Send a prompt, return the model's textual reply as a plain string.
Thin convenience wrapper around ask() for single-shot,
tool-less text generation. Use cases:
- Interop with components that expect
async complete(prompt) -> str(e.g.parrot_tools.scraping.PlanGenerator). - Quick prompts where you don't need the full
AIMessage.
Handles two things ask() does NOT:
- Auto-enters the async context manager if the client isn't
already initialized, so callers don't need
async with client:before callingcomplete(). If the client was already entered (e.g. inside a surroundingasync with), we reuse it and don't tear it down. - Extracts plain text from the response —
ask()returns anAIMessagepydantic model (provider-specific clients) or aMessageResponseTypedDict with a content-block list. Both shapes collapse to a single string here.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
User prompt.
TYPE:
|
model
|
Override the instance default model.
TYPE:
|
system_prompt
|
Optional system prompt.
TYPE:
|
max_tokens
|
Override default max tokens.
TYPE:
|
temperature
|
Override default sampling temperature.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The model's textual response. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the response has no extractable text. |
Source code in packages/ai-parrot/src/parrot/clients/base.py
close
async
¶
Close all per-loop SDK clients.
Delegates to close_all(). Both close and close_all exist
so callers can be explicit about intent (spec §8 Q1).
Source code in packages/ai-parrot/src/parrot/clients/base.py
close_all
async
¶
Tear down every per-loop SDK client entry.
Safely handles dead / foreign loops: entries whose loop has been
garbage-collected or belongs to a different running context are dropped
without awaiting their close() coroutine.
After this call, _clients_by_loop and _locks_by_loop are empty.
Source code in packages/ai-parrot/src/parrot/clients/base.py
set_program ¶
start_conversation
async
¶
start_conversation(user_id: str, session_id: str, metadata: Optional[Dict[str, Any]] = None, chatbot_id: Optional[str] = None) -> ConversationHistory
Start a new conversation session.
Source code in packages/ai-parrot/src/parrot/clients/base.py
get_conversation
async
¶
get_conversation(user_id: str, session_id: str, chatbot_id: Optional[str] = None) -> Optional[ConversationHistory]
Get an existing conversation session.
Source code in packages/ai-parrot/src/parrot/clients/base.py
clear_conversation
async
¶
Clear conversation history for a session.
Source code in packages/ai-parrot/src/parrot/clients/base.py
delete_conversation
async
¶
Delete conversation history entirely.
Source code in packages/ai-parrot/src/parrot/clients/base.py
list_user_conversations
async
¶
List all conversation sessions for a user.
Source code in packages/ai-parrot/src/parrot/clients/base.py
set_tools ¶
Set complete list of tools, replacing existing.
get_tool ¶
Get a tool by name from ToolManager or legacy tools.
Source code in packages/ai-parrot/src/parrot/clients/base.py
register_tool ¶
register_tool(tool: Union[ToolDefinition, AbstractTool] = None, name: str = None, description: str = None, input_schema: Dict[str, Any] = None, function: Callable = None) -> None
Register a Python function as a tool for LLM to call.
Source code in packages/ai-parrot/src/parrot/clients/base.py
register_tools ¶
Register multiple tools at once.
register_python_tool ¶
register_python_tool(report_dir: Optional[Path] = None, plt_style: str = 'seaborn-v0_8-whitegrid', palette: str = 'Set2') -> PythonREPLTool
Register Python REPL tool with a ClaudeAPIClient.
| PARAMETER | DESCRIPTION |
|---|---|
client
|
The ClaudeAPIClient instance
|
report_dir
|
Directory for saving reports
TYPE:
|
plt_style
|
Matplotlib style
TYPE:
|
palette
|
Seaborn color palette
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PythonREPLTool
|
The PythonREPLTool instance |
Source code in packages/ai-parrot/src/parrot/clients/base.py
list_tools ¶
Get a list of all registered tool names.
Source code in packages/ai-parrot/src/parrot/clients/base.py
remove_tool ¶
Remove a tool by name.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Tool name to remove
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if tool was removed, False if not found |
Source code in packages/ai-parrot/src/parrot/clients/base.py
clear_tools ¶
ask
abstractmethod
async
¶
ask(prompt: str, model: str, max_tokens: int = 4096, temperature: float = 0.7, files: Optional[List[Union[str, Path]]] = None, system_prompt: Optional[str] = None, structured_output: Union[type, StructuredOutputConfig, None] = None, user_id: Optional[str] = None, session_id: Optional[str] = None, tools: Optional[List[Dict[str, Any]]] = None, use_tools: Optional[bool] = None, deep_research: bool = False, background: bool = False, lazy_loading: bool = False) -> MessageResponse
Send a prompt to the model and return the response.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
The input prompt for the model
TYPE:
|
model
|
The model to use
TYPE:
|
max_tokens
|
Maximum number of tokens in the response
TYPE:
|
temperature
|
Sampling temperature for response generation
TYPE:
|
files
|
Optional files to include in the request
TYPE:
|
system_prompt
|
Optional system prompt to guide the model
TYPE:
|
structured_output
|
Optional structured output configuration
TYPE:
|
user_id
|
Optional user identifier for tracking
TYPE:
|
session_id
|
Optional session identifier for tracking
TYPE:
|
tools
|
Optional tools to register for this call
TYPE:
|
use_tools
|
Whether to use tools
TYPE:
|
deep_research
|
If True, use deep research mode (provider-specific)
TYPE:
|
background
|
If True, execute research in background (async mode)
TYPE:
|
lazy_loading
|
If True, enabled dynamic tool searching
TYPE:
|
Source code in packages/ai-parrot/src/parrot/clients/base.py
ask_stream
abstractmethod
async
¶
ask_stream(prompt: str, model: str = None, max_tokens: int = 4096, temperature: float = 0.7, files: Optional[List[Union[str, Path]]] = None, system_prompt: Optional[str] = None, user_id: Optional[str] = None, session_id: Optional[str] = None, tools: Optional[List[Dict[str, Any]]] = None, deep_research: bool = False, agent_config: Optional[Dict[str, Any]] = None, lazy_loading: bool = False) -> AsyncIterator[Union[str, AIMessage]]
Stream the model's response.
Yields successive string chunks of the model response followed by a
single final :class:~parrot.models.responses.AIMessage carrying full
response metadata (token usage, stop reason, model, provider, turn_id,
etc.).
Implementors MUST yield at least one str chunk before the final
AIMessage. Consumers can detect the end-of-stream sentinel via
isinstance(chunk, AIMessage).
Source code in packages/ai-parrot/src/parrot/clients/base.py
resume
abstractmethod
async
¶
Resume a suspended model execution.
| PARAMETER | DESCRIPTION |
|---|---|
session_id
|
The session ID
TYPE:
|
user_input
|
The user's input to inject as tool result
TYPE:
|
state
|
The suspended state containing messages and tool_call_id
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MessageResponse
|
The response from the LLM
TYPE:
|
Source code in packages/ai-parrot/src/parrot/clients/base.py
batch_ask
async
¶
invoke
abstractmethod
async
¶
invoke(prompt: str, *, output_type: Optional[type] = None, structured_output: Optional[StructuredOutputConfig] = None, model: Optional[str] = None, system_prompt: Optional[str] = None, max_tokens: int = 4096, temperature: float = 0.0, use_tools: bool = False, tools: Optional[list] = None) -> InvokeResult
Lightweight stateless invocation — no retry, no history, no prompt builder.
Each concrete client implements this method using provider-native structured
output. Use this instead of ask() when you need fast, stateless structured
extraction without conversation history overhead.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
The user prompt to send.
TYPE:
|
output_type
|
A Pydantic model or dataclass class to parse the response into.
Mutually exclusive with
TYPE:
|
structured_output
|
Full :class:
TYPE:
|
model
|
Override the model for this call. Falls back to
TYPE:
|
system_prompt
|
Override the system prompt. Falls back to
TYPE:
|
max_tokens
|
Maximum completion tokens (default 4096).
TYPE:
|
temperature
|
Sampling temperature (default 0.0 for deterministic output).
TYPE:
|
use_tools
|
If
TYPE:
|
tools
|
Additional tool definitions to pass directly to the provider.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
InvokeResult
|
class: |
InvokeResult
|
and optional |
| RAISES | DESCRIPTION |
|---|---|
|
class: |
Source code in packages/ai-parrot/src/parrot/clients/base.py
create_conversation_memory
staticmethod
¶
Factory method to create a conversation memory instance.
Source code in packages/ai-parrot/src/parrot/clients/base.py
StreamingRetryConfig ¶
StreamingRetryConfig(max_retries: int = 3, base_delay: float = 1.0, max_delay: float = 60.0, backoff_factor: float = 2.0, jitter: bool = True, auto_retry_on_max_tokens: bool = True, token_increase_factor: float = 1.5, retry_on_rate_limit: bool = True, retry_on_server_error: bool = True)
Configuration for streaming retry behavior.
Source code in packages/ai-parrot/src/parrot/clients/base.py
ZaiClient ¶
ZaiClient(api_key: Optional[str] = None, base_url: str = 'https://api.z.ai/api/paas/v4/', timeout: Optional[float] = None, max_retries: Optional[int] = None, **kwargs: Any)
Bases: AbstractClient
Client for Z.ai chat completions using the official zai-sdk package.
Source code in packages/ai-parrot/src/parrot/clients/zai.py
get_client
async
¶
Create the official Z.ai SDK client for the current event loop.
Source code in packages/ai-parrot/src/parrot/clients/zai.py
ask
async
¶
ask(prompt: str, model: Union[str, ZaiModel, None] = None, max_tokens: int = 4096, temperature: float = 0.7, top_p: float = 0.9, files: Optional[List[Union[str, Path]]] = None, system_prompt: Optional[Union[str, list]] = None, structured_output: Union[type, StructuredOutputConfig, None] = None, user_id: Optional[str] = None, session_id: Optional[str] = None, tools: Optional[List[Dict[str, Any]]] = None, use_tools: Optional[bool] = None, thinking: Optional[Union[bool, str, Dict[str, Any]]] = None, deep_thinking: bool = False, **_: Any) -> AIMessage
Send a non-streaming chat request to Z.ai.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
The user input text.
TYPE:
|
model
|
Z.ai model identifier; defaults to :attr:
TYPE:
|
max_tokens
|
Maximum completion tokens.
TYPE:
|
temperature
|
Sampling temperature.
TYPE:
|
top_p
|
Top-p nucleus sampling parameter.
TYPE:
|
files
|
Optional file paths to include in the request.
TYPE:
|
system_prompt
|
Optional system prompt string or list of CacheableSegments.
TYPE:
|
structured_output
|
Pydantic model or :class:
TYPE:
|
user_id
|
Optional user identifier for conversation memory.
TYPE:
|
session_id
|
Optional session identifier for conversation memory.
TYPE:
|
tools
|
Additional tool definitions to register for this call.
TYPE:
|
use_tools
|
Override the instance-level
TYPE:
|
thinking
|
Enable chain-of-thought for thinking-capable models.
TYPE:
|
deep_thinking
|
Shorthand to enable thinking on capable models.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AIMessage
|
class: |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
Propagates provider errors after emitting a
|
Source code in packages/ai-parrot/src/parrot/clients/zai.py
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 424 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 | |
ask_stream
async
¶
ask_stream(prompt: str, model: Union[str, ZaiModel, None] = None, max_tokens: int = 4096, temperature: float = 0.7, top_p: float = 0.9, files: Optional[List[Union[str, Path]]] = None, system_prompt: Optional[Union[str, list]] = None, user_id: Optional[str] = None, session_id: Optional[str] = None, tools: Optional[List[Dict[str, Any]]] = None, use_tools: Optional[bool] = None, thinking: Optional[Union[bool, str, Dict[str, Any]]] = None, deep_thinking: bool = False, stream_reasoning: bool = False, **_: Any) -> AsyncIterator[Union[str, AIMessage]]
Stream a Z.ai response, yielding text chunks followed by an
:class:AIMessage sentinel.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
The user input text.
TYPE:
|
model
|
Z.ai model identifier; defaults to :attr:
TYPE:
|
max_tokens
|
Maximum completion tokens.
TYPE:
|
temperature
|
Sampling temperature.
TYPE:
|
top_p
|
Top-p nucleus sampling parameter.
TYPE:
|
files
|
Optional file paths to include in the request.
TYPE:
|
system_prompt
|
Optional system prompt string or list of CacheableSegments.
TYPE:
|
user_id
|
Optional user identifier for conversation memory.
TYPE:
|
session_id
|
Optional session identifier for conversation memory.
TYPE:
|
tools
|
Additional tool definitions to register for this call.
TYPE:
|
use_tools
|
Override the instance-level
TYPE:
|
thinking
|
Enable chain-of-thought for thinking-capable models.
TYPE:
|
deep_thinking
|
Shorthand to enable thinking on capable models.
TYPE:
|
stream_reasoning
|
When
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
AsyncIterator[Union[str, AIMessage]]
|
|
single
|
class:
TYPE::
|
| RAISES | DESCRIPTION |
|---|---|
Exception
|
Propagates provider errors after emitting a
|
Source code in packages/ai-parrot/src/parrot/clients/zai.py
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 686 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 | |
resume
async
¶
Resume a suspended ZaiClient execution after a HandoffTool / HITL pause.
Injects user_input into the suspended message history (as a tool
role message when state["tool_call_id"] is present, otherwise as a
user message) and continues the tool-call loop until a final
response is produced.
| PARAMETER | DESCRIPTION |
|---|---|
session_id
|
Session identifier propagated to any
:class:
TYPE:
|
user_input
|
User reply to inject as the resumption value.
TYPE:
|
state
|
Suspended execution state. Expected keys:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AIMessage
|
class: |
AIMessage
|
calls executed during resumption. |
| RAISES | DESCRIPTION |
|---|---|
|
class: |
Source code in packages/ai-parrot/src/parrot/clients/zai.py
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 876 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 | |
invoke
async
¶
invoke(prompt: str, *, output_type: Optional[type] = None, structured_output: Optional[StructuredOutputConfig] = None, model: Optional[str] = None, system_prompt: Optional[str] = None, max_tokens: int = 4096, temperature: float = 0.0, use_tools: bool = False, tools: Optional[list] = None) -> InvokeResult
Lightweight stateless invocation for ZaiClient.
Makes a single chat.completions.create call without conversation
history, retries, or the full prompt-builder overhead. Uses Z.ai's
native json_schema response format for structured output.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
User prompt.
TYPE:
|
output_type
|
Pydantic model or dataclass to parse the response into. Mutually exclusive with structured_output (the latter wins).
TYPE:
|
structured_output
|
Full :class:
TYPE:
|
model
|
Model override. Falls back to :attr:
TYPE:
|
system_prompt
|
System prompt override. Falls back to the default
:attr:
TYPE:
|
max_tokens
|
Maximum completion tokens (default
TYPE:
|
temperature
|
Sampling temperature (default
TYPE:
|
use_tools
|
If
TYPE:
|
tools
|
Additional tool definitions to register for this call.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
InvokeResult
|
class: |
InvokeResult
|
|
| RAISES | DESCRIPTION |
|---|---|
|
class: |
Source code in packages/ai-parrot/src/parrot/clients/zai.py
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 | |
embed
async
¶
Embeddings are not implemented by this chat client yet.