How to store db_connection inside Runtime[ContextSchema]?

Hello, from the Documentation we see that

Static runtime context represents immutable data like user metadata, tools, and database connections that are passed to an application at the start of a run via the context argument to invoke/stream

Up until now I’ve been using RunnableConfig to define a schema to provide an Assistant (Langgraph Platform) configuration for prompts, but I’m interested to understand how I can use the Runtime to continue to do this but also potentially provide additional functionality of holding runtime data.

Thank you

1 Like

Yeah i am also wondering this since the documentation is really just scratching the surface at this point have you figured it out ? I am looking for a way to initiate a AsyncConnectionPool on startup which gets then passed as an object in runtime context.

You define a ContextSchema, init and pass to invoke / stream, then get via runtime injection.

@dataclass

class ContextSchema:

    db: AsyncDatabaseSession

from langgraph.runtime import Runtime

context = {"db": db}

graph.ainvoke(input, config=config, context=context)

class Node(state, config, runtime: Runtime[ContextSchema]):

    db = runtime.context.db

from langchain.tools import tool, ToolRuntime

@tool

def tool_node(arg1, arg2, runtime: ToolRuntime[ContextSchema]):

    db = runtime.context.db
2 Likes

The issue with Runtime Context though is that I don’t use .invoke()on the graph when using LangGraph Server. How do you suggest we inject the db when running via LangGraph Server?

2 Likes

Yes same issue for me. Basically I no longer rely on context. I populate whats needed in configurable, and instantiate any instances using those static values in the graph.

Same issue for me, what i did in the end was initializing my db connection via a custom lifespan event., following this doc: How to add custom lifespan events - Docs by LangChain , this seems to work well with my async db pool, though i am still not sure whats the best way to access my db objects now via graph nodes.