language_models
langroid/language_models/init.py
LLMConfig
¶
Bases: BaseSettings
Common configuration for all language models.
LLMMessage
¶
Bases: BaseModel
Class representing an entry in the msg-history sent to the LLM API. It could be one of these: - a user message - an LLM ("Assistant") response - a fn-call or tool-call-list from an OpenAI-compatible LLM API response - a result or results from executing a fn or tool-call(s)
api_dict(model, has_system_role=True)
¶
Convert to dictionary for API request, keeping ONLY the fields that are expected in an API call! E.g., DROP the tool_id, since it is only for use in the Assistant API, not the completion API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
has_system_role
|
bool
|
whether the message has a system role (if not, set to "user" role) |
True
|
Returns: dict: dictionary representation of LLM message
Source code in langroid/language_models/base.py
LLMFunctionCall
¶
Bases: BaseModel
Structure of LLM response indicating it "wants" to call a function.
Modeled after OpenAI spec for function_call field in ChatCompletion API.
from_dict(message)
staticmethod
¶
Initialize from dictionary. Args: d: dictionary containing fields to initialize
Source code in langroid/language_models/base.py
LLMFunctionSpec
¶
Bases: BaseModel
Description of a function available for the LLM to use.
To be used when calling the LLM chat() method with the functions parameter.
Modeled after OpenAI spec for functions fields in ChatCompletion API.
Role
¶
Bases: str, Enum
Possible roles for a message in a chat.
LLMTokenUsage
¶
Bases: BaseModel
Usage of tokens by an LLM.
LLMResponse
¶
Bases: BaseModel
Class representing response from LLM.
to_LLMMessage()
¶
Convert LLM response to an LLMMessage, to be included in the message-list sent to the API. This is currently NOT used in any significant way in the library, and is only provided as a utility to construct a message list for the API when directly working with an LLM object.
In a ChatAgent, an LLM response is first converted to a ChatDocument,
which is in turn converted to an LLMMessage via ChatDocument.to_LLMMessage()
See ChatAgent._prep_llm_messages() and ChatAgent.llm_response_messages
Source code in langroid/language_models/base.py
get_recipient_and_message(recognize_recipient_in_content=True)
¶
If message or function_call of an LLM response contains an explicit
recipient name, return this recipient name and message stripped
of the recipient name if specified.
Two cases:
(a) message contains addressing string TO[<name>]:<content>, or
(b) message is empty and function_call/tool_call with explicit recipient
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recognize_recipient_in_content
|
bool
|
When True (default), parses
message text for |
True
|
Returns:
| Type | Description |
|---|---|
str
|
name of recipient, which may be empty string if no recipient |
str
|
content of message |
Source code in langroid/language_models/base.py
OpenAICompletionModel
¶
Bases: str, Enum
Enum for OpenAI Completion models
OpenAIGPTConfig(**kwargs)
¶
Bases: LLMConfig
Class for any LLM with an OpenAI-like API: besides the OpenAI models this includes: (a) locally-served models behind an OpenAI-compatible API (b) non-local models, using a proxy adaptor lib like litellm that provides an OpenAI-compatible API. (We could rename this class to OpenAILikeConfig, but we keep it as-is for now)
Important Note:
Due to the env_prefix = "OPENAI_" defined below,
all of the fields below can be set AND OVERRIDDEN via env vars,
by upper-casing the name and prefixing with OPENAI_, e.g.¶
OPENAI_MAX_OUTPUT_TOKENS=1000.¶
If any of these is defined in this way in the environment¶
(either via explicit setenv or export or via .env file + load_dotenv()),¶
the environment variable takes precedence over the value in the config.¶
Source code in langroid/language_models/openai_gpt.py
model_copy(*, update=None, deep=False)
¶
Copy config while preserving nested model instances and subclasses.
Important: Avoid reconstructing via model_dump as that coerces nested
models to their annotated base types (dropping subclass-only fields).
Instead, defer to Pydantic's native model_copy, which keeps nested
BaseModel instances (and their concrete subclasses) intact.
Source code in langroid/language_models/openai_gpt.py
create(prefix)
classmethod
¶
Create a config class whose params can be set via a desired prefix from the .env file or env vars. E.g., using
you can have a group of params prefixed by "OLLAMA_", to be used with models served viaollama.
This way, you can maintain several setting-groups in your .env file,
one per model type.
Source code in langroid/language_models/openai_gpt.py
OpenAIGPT(config=OpenAIGPTConfig())
¶
Bases: LanguageModel
Class for OpenAI LLMs
Source code in langroid/language_models/openai_gpt.py
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 504 505 506 507 508 509 510 511 512 513 514 515 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 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 | |
is_gemini_model()
¶
unsupported_params()
¶
List of params that are not supported by the current model
rename_params()
¶
Map of param name -> new name for specific models. Currently main troublemaker is o1* series.
chat_context_length()
¶
Context-length for chat-completion models/endpoints. Get it from the config if explicitly given, otherwise use model_info based on model name, and fall back to generic model_info if there's no match.
Source code in langroid/language_models/openai_gpt.py
completion_context_length()
¶
Context-length for completion models/endpoints. Get it from the config if explicitly given, otherwise use model_info based on model name, and fall back to generic model_info if there's no match.
Source code in langroid/language_models/openai_gpt.py
chat_cost()
¶
(Prompt, Cached, Generation) cost per 1000 tokens, for chat-completion models/endpoints. Get it from the dict, otherwise fail-over to general method
Source code in langroid/language_models/openai_gpt.py
set_stream(stream)
¶
Enable or disable streaming output from API. Args: stream: enable streaming output from API Returns: previous value of stream
Source code in langroid/language_models/openai_gpt.py
get_stream()
¶
tool_deltas_to_tools(tools)
staticmethod
¶
Convert accumulated tool-call deltas to OpenAIToolCall objects. Adapted from this excellent code: https://community.openai.com/t/help-for-function-calls-with-streaming/627170/2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
List[Dict[str, Any]]
|
list of tool deltas received from streaming API |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
plain text corresponding to tool calls that failed to parse |
List[OpenAIToolCall]
|
List[OpenAIToolCall]: list of OpenAIToolCall objects |
|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: list of tool dicts (to reconstruct OpenAI API response, so it can be cached) |
Source code in langroid/language_models/openai_gpt.py
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 | |
OpenAICallParams
¶
Bases: BaseModel
Various params that can be sent to an OpenAI API chat-completion call. When specified, any param here overrides the one with same name in the OpenAIGPTConfig. See OpenAI API Reference for details on the params: https://platform.openai.com/docs/api-reference/chat
MockLM(config=MockLMConfig())
¶
Bases: LanguageModel
Source code in langroid/language_models/mock_lm.py
chat(messages, max_tokens=200, tools=None, tool_choice='auto', functions=None, function_call='auto', response_format=None)
¶
Mock chat function for testing
Source code in langroid/language_models/mock_lm.py
achat(messages, max_tokens=200, tools=None, tool_choice='auto', functions=None, function_call='auto', response_format=None)
async
¶
Mock chat function for testing
Source code in langroid/language_models/mock_lm.py
generate(prompt, max_tokens=200)
¶
agenerate(prompt, max_tokens=200)
async
¶
MockLMConfig
¶
Bases: LLMConfig
Mock Language Model Configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
response_dict |
Dict[str, str]
|
A "response rule-book", in the form of a dictionary; if last msg in dialog is x,then respond with response_dict[x] |
AzureConfig(**kwargs)
¶
Bases: OpenAIGPTConfig
Configuration for Azure OpenAI GPT.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
str
|
should be |
api_version |
str
|
can be set in the |
deployment_name |
str | None
|
can be optionally set in the |
model_name |
str
|
[DEPRECATED] can be set in the |
chat_model |
str
|
the chat model name to use. Can be set via
the env variable |
Source code in langroid/language_models/azure_openai.py
AzureGPT(config)
¶
Bases: OpenAIGPT
Class to access OpenAI LLMs via Azure. These env variables can be obtained from the
file .azure_env. Azure OpenAI doesn't support completion