Graph of Thoughts Framework¶
An implementation of the Graph of Thoughts (GoT) reasoning framework from this paper.
The implementation represents the reasoning process as a graph where nodes are thoughts and edges represent transformations. The flow of reasoning is controlled by a Graph of Operations (GoO).
Defining the Graph of Operations (GoO)¶
To use GraphOfThoughts
, you must provide a graph_of_operations
argument to the run_async
method.
This argument is a list of tuples, where each tuple defines an operation step:
graph_of_operations: List[Tuple[str, Dict]]
- The first element of the tuple is the name of the operation (e.g.,
'Generate'
,'Score'
,'KeepBest'
). - The second element is a dictionary containing the parameters specific to that operation.
Example GoO:
from cogitator import ThoughtExpansion
EXAMPLE_GOO = [
# Step 1: Generate 3 new thoughts from the initial question (in 'frontier' set)
# Store results in the 'generated_thoughts' set. Use the 'expand' prompt. Expect ThoughtExpansion schema.
('Generate', {'k': 3, 'target_set': 'frontier', 'output_set': 'generated_thoughts', 'prompt_key': 'expand', 'response_schema': ThoughtExpansion}),
# Step 2: Score the thoughts generated in the previous step. Use 'evaluate' prompt.
('Score', {'target_set': 'generated_thoughts', 'prompt_key': 'evaluate'}),
# Step 3: Keep only the single best-scoring thought from the previous step.
# Put the result back into the 'frontier' set for potential further steps or final answer generation.
('KeepBest', {'N': 1, 'target_set': 'generated_thoughts', 'output_set': 'frontier'})
]
Main Class (GraphOfThoughts
)¶
cogitator.strategies.graph_of_thoughts.GraphOfThoughts
¶
Implements the Graph of Thoughts (GoT) prompting framework.
GoT represents the reasoning process as a graph where nodes are partial solutions (thoughts) and edges represent dependencies or transformations between them. It allows for applying operations like generation, aggregation, scoring, and selection according to a defined Graph of Operations (GoO).
Reference
Besta et al. (v4; 2024) "Graph of Thoughts: Solving Elaborate Problems with Large Language Models". https://arxiv.org/abs/2308.09687
Source code in cogitator/strategies/graph_of_thoughts.py
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 |
|
__init__(llm, embedder=None, final_answer_format='text', prompts=None, max_tokens=None, seed=None)
¶
Initializes the GraphOfThoughts strategy handler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
llm
|
BaseLLM
|
The language model instance. |
required |
embedder
|
Optional[BaseEmbedder]
|
Optional embedding model instance for similarity checks. |
None
|
final_answer_format
|
Literal['text', 'json']
|
Whether to extract the final answer as raw text or JSON. |
'text'
|
prompts
|
Optional[Dict[str, str]]
|
A dictionary mapping operation types (e.g., 'expand', 'evaluate', 'aggregate', 'improve') to their prompt templates. |
None
|
max_tokens
|
Optional[int]
|
Default maximum tokens for LLM generation calls. |
None
|
seed
|
Optional[int]
|
Default random seed for LLM calls. |
None
|
Source code in cogitator/strategies/graph_of_thoughts.py
run_async(question, graph_of_operations, semaphore=None, **kwargs)
async
¶
Asynchronously executes the Graph of Thoughts reasoning process based on a GoO.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
question
|
str
|
The initial question or problem statement. |
required |
graph_of_operations
|
List[Tuple[str, Dict]]
|
A list defining the sequence of operations and their parameters. Example: [('Generate', {'k': 5, 'output_set': 'thoughts1'}), ('Score', {'target_set': 'thoughts1'}), ('KeepBest', {'N': 3, 'target_set': 'thoughts1', 'output_set': 'frontier'}), ('Aggregate', {'target_sets': ['frontier'], 'k': 1, 'output_set': 'aggregated'}), ...] |
required |
semaphore
|
Optional[Semaphore]
|
Optional asyncio.Semaphore to limit concurrent LLM calls. |
None
|
**kwargs
|
Any
|
Additional arguments passed to internal LLM calls (e.g., seed, max_tokens). |
{}
|
Returns:
Type | Description |
---|---|
str
|
The final answer string generated by the LLM based on the best reasoning path found. |
str
|
Returns an error message if no paths are generated or the final generation fails. |
Source code in cogitator/strategies/graph_of_thoughts.py
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 |
|
run(question, graph_of_operations, **kwargs)
¶
Synchronous execution is not supported for GraphOfThoughts.
Source code in cogitator/strategies/graph_of_thoughts.py
Available Operations¶
Here are the standard operations available.
You can create custom operations by subclassing GoTOperation
.
Base Operation Class¶
cogitator.strategies.graph_of_thoughts.GoTOperation
¶
Bases: ABC
Abstract base class for all Graph of Thoughts operations.
__init__(**params)
¶
Initializes the operation with specific parameters.
execute(grs, llm, prompts, embedder=None, **global_kwargs)
abstractmethod
¶
Executes the operation, modifying the GraphReasoningState.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
grs
|
GraphReasoningState
|
The current graph reasoning state. |
required |
llm
|
BaseLLM
|
The language model instance. |
required |
prompts
|
Dict[str, str]
|
A dictionary of available prompt templates. |
required |
embedder
|
Optional[BaseEmbedder]
|
Optional embedder for operations needing similarity. |
None
|
global_kwargs
|
Any
|
Global arguments like seed, max_tokens passed to LLM calls. |
{}
|
execute_async(grs, llm, prompts, embedder=None, semaphore=None, **global_kwargs)
abstractmethod
async
¶
Asynchronously executes the operation.
Generate Operation¶
cogitator.strategies.graph_of_thoughts.GenerateOp
¶
Bases: GoTOperation
Generates new thoughts based on parent nodes.
execute_async(grs, llm, prompts, embedder, semaphore, **global_kwargs)
async
¶
Generates new thoughts asynchronously.
Score Operation¶
cogitator.strategies.graph_of_thoughts.ScoreOp
¶
Bases: GoTOperation
Scores thoughts using the LLM.
execute_async(grs, llm, prompts, embedder, semaphore, **global_kwargs)
async
¶
Scores nodes asynchronously.
KeepBest Operation¶
cogitator.strategies.graph_of_thoughts.KeepBestOp
¶
Bases: GoTOperation
Selects the top N nodes based on score.
Aggregate Operation¶
cogitator.strategies.graph_of_thoughts.AggregateOp
¶
Bases: GoTOperation
Aggregates multiple thoughts into new ones.
execute_async(grs, llm, prompts, embedder, semaphore, **global_kwargs)
async
¶
Aggregates thoughts asynchronously.
Internal State (Advanced)¶
These classes manage the internal graph structure.
GoTNode¶
cogitator.strategies.graph_of_thoughts.GoTNode
¶
Represents a node (thought) in the Graph of Thoughts.
__init__(steps, embedder=None, parents=None, data=None, text_content=None)
¶
Initializes a GoT node.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
steps
|
List[str]
|
The sequence of reasoning steps/operations leading to this node. |
required |
embedder
|
Optional[BaseEmbedder]
|
The embedding model used for calculating node similarity. Can be None. |
None
|
parents
|
Optional[List[GoTNode]]
|
A list of parent nodes. |
None
|
data
|
Optional[Any]
|
Optional arbitrary data associated with the node. |
None
|
text_content
|
Optional[str]
|
Optional string representing the actual thought content. |
None
|
GraphReasoningState¶
cogitator.strategies.graph_of_thoughts.GraphReasoningState
¶
Maintains the dynamic state of the GoT reasoning process.
__init__(root_node)
¶
Initializes the Graph Reasoning State.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
root_node
|
GoTNode
|
The initial node containing the problem input. |
required |
add_node(node)
¶
Adds a new node to the state.
get_active_set(set_name)
¶
Gets the list of nodes in a named active set.
get_nodes(node_ids)
¶
Retrieves nodes by their IDs.
set_active_set(set_name, nodes)
¶
Sets or replaces a named active set.
update_node(node)
¶
Updates an existing node in the state (e.g., score, validity).