MCPcopy Create free account
hub / github.com/google/adk-python / inject_session_state

Function inject_session_state

src/google/adk/utils/instructions_utils.py:30–124  ·  view source on GitHub ↗

Populates values in the instruction template, e.g. state, artifact, etc. This method is intended to be used in InstructionProvider based instruction and global_instruction which are called with readonly_context. e.g. ``` ... from google.adk.utils.instructions_utils import inject_sessio

(
    template: str,
    readonly_context: ReadonlyContext,
)

Source from the content-addressed store, hash-verified

28
29
30async def inject_session_state(
31 template: str,
32 readonly_context: ReadonlyContext,
33) -> str:
34 """Populates values in the instruction template, e.g. state, artifact, etc.
35
36 This method is intended to be used in InstructionProvider based instruction
37 and global_instruction which are called with readonly_context.
38
39 e.g.
40 ```
41 ...
42 from google.adk.utils.instructions_utils import inject_session_state
43
44 async def build_instruction(
45 readonly_context: ReadonlyContext,
46 ) -> str:
47 return await inject_session_state(
48 'You can inject a state variable like {var_name} or an artifact '
49 '{artifact.file_name} into the instruction template.',
50 readonly_context,
51 )
52
53 agent = Agent(
54 model="gemini-2.5-flash",
55 name="agent",
56 instruction=build_instruction,
57 )
58 ```
59
60 Args:
61 template: The instruction template.
62 readonly_context: The read-only context
63
64 Returns:
65 The instruction template with values populated.
66 """
67
68 invocation_context = readonly_context._invocation_context
69
70 async def _async_sub(pattern, repl_async_fn, string) -> str:
71 result = []
72 last_end = 0
73 for match in re.finditer(pattern, string):
74 result.append(string[last_end : match.start()])
75 replacement = await repl_async_fn(match)
76 result.append(replacement)
77 last_end = match.end()
78 result.append(string[last_end:])
79 return ''.join(result)
80
81 async def _replace_match(match) -> str:
82 var_name = match.group().lstrip('{').rstrip('}').strip()
83 optional = False
84 if var_name.endswith('?'):
85 optional = True
86 var_name = var_name.removesuffix('?')
87 if var_name.startswith('artifact.'):

Callers

nothing calls this directly

Calls 1

_async_subFunction · 0.85

Tested by

no test coverage detected