-
Notifications
You must be signed in to change notification settings - Fork 849
add graph_structure #3508
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Avijeet-Mandal
wants to merge
1
commit into
traceloop:main
Choose a base branch
from
Avijeet-Mandal:feature/graph_structure
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
add graph_structure #3508
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
...try-instrumentation-langchain/opentelemetry/instrumentation/langchain/langgraph_helper.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import inspect | ||
| import json | ||
| from langgraph.graph.state import CompiledStateGraph | ||
|
|
||
|
|
||
| from typing import List, Dict, Union, Any | ||
|
|
||
|
|
||
| def is_langgraph_task(name: str) -> bool: | ||
| return name == "LangGraph" | ||
|
|
||
|
|
||
| def get_compiled_graph(): | ||
| """ Get the compiled graph from the call stack """ | ||
| graph = None | ||
| invocation_methods = ["Pregel.invoke", "Pregel.ainvoke", "Pregel.stream", "Pregel.astream"] | ||
| frames = inspect.stack() | ||
| for frame_info in frames[1:]: | ||
| if frame_info.frame.f_code.co_qualname in invocation_methods: | ||
| local_vars = frame_info.frame.f_locals | ||
| graph = local_vars.get("self", None) | ||
| graph = graph if isinstance(graph, CompiledStateGraph) else None | ||
| break | ||
| return graph | ||
|
|
||
|
|
||
| def _normalize_endpoint_names( | ||
| names: Union[str, List[str], tuple[str, ...]] | ||
| ) -> List[str]: | ||
| """Normalize edge endpoints to a list of node names.""" | ||
| if isinstance(names, str): | ||
| return [names] | ||
| if isinstance(names, (list, tuple)): | ||
| return list(names) | ||
| raise TypeError(f"Unsupported endpoint type: {type(names)!r}") | ||
|
|
||
|
|
||
| def build_node_graph(compiled_state_graph: CompiledStateGraph) -> Dict[str, Any]: | ||
| """ | ||
| Build a simple node/edge representation from CompiledStateGraph. | ||
|
|
||
| Returns a dict: | ||
| { | ||
| "nodes": [node_name, ...], # excluding "__start__", "__end__" | ||
| "edges": [ | ||
| [[source1, ...], [dest1, dest2, ...]], # each edge has list of sources and list of destinations | ||
| ... | ||
| ] | ||
| } | ||
| """ | ||
| builder = compiled_state_graph.builder | ||
|
|
||
| # Track *all* node names (including __start__/__end__) for edges, | ||
| # but only expose non-special nodes in the "nodes" list. | ||
| all_nodes_ordered = list(compiled_state_graph.nodes.keys()) | ||
| nodes: List[str] = [ | ||
| name for name in all_nodes_ordered if name not in ("__start__", "__end__") | ||
| ] | ||
|
|
||
| edges: List[List[List[str]]] = [] | ||
|
|
||
| # Regular edges | ||
| for src, dst in builder.edges: | ||
| src_names = _normalize_endpoint_names(src) | ||
| dst_names = _normalize_endpoint_names(dst) | ||
| edges.append([src_names, dst_names]) | ||
|
|
||
| # Branches | ||
| branches: Dict[str, Dict[str]] = builder.branches | ||
| for source, branch_map in branches.items(): | ||
| for branch in branch_map.values(): | ||
| # branch.ends is expected to be a mapping; we use its values as destinations | ||
| dest_names = list(branch.ends.values()) | ||
| # Source is a single node here | ||
| edges.append([[source], dest_names]) | ||
|
|
||
| # Waiting edges | ||
| for src, dst in builder.waiting_edges: | ||
| src_names = _normalize_endpoint_names(src) | ||
| dst_names = _normalize_endpoint_names(dst) | ||
| edges.append([src_names, dst_names]) | ||
|
|
||
| return { | ||
| "nodes": nodes, | ||
| "edges": edges, | ||
| } | ||
|
|
||
|
|
||
| def get_graph_structure() -> str: | ||
| """ | ||
| Get graph structure as a JSON string. | ||
|
|
||
| Returns: | ||
| JSON string with structure: | ||
| { | ||
| "nodes": [...], | ||
| "edges": [[[...], [...]], ...] | ||
| } | ||
| """ | ||
| graph_structure: Dict[str, Any] = {} | ||
| graph = get_compiled_graph() | ||
| if graph: | ||
| graph_structure = build_node_graph(graph) | ||
| return json.dumps(graph_structure) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handle optional
langgraphdependency gracefully.The unconditional import of
CompiledStateGraphwill raiseImportErroriflanggraphis not installed. Since this is an instrumentation library that may be used in environments wherelanggraphisn't present, consider using a lazy import pattern.Then guard the functions accordingly:
🤖 Prompt for AI Agents