File size: 943 Bytes
60870c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""Shared context helper used by both ApiHandler and WsHandler."""

import threading
from typing import Union

ThreadLockType = Union[threading.Lock, threading.RLock]


def use_context(lock: ThreadLockType, ctxid: str, create_if_not_exists: bool = True):
    from agent import AgentContext
    from initialize import initialize_agent

    with lock:
        if not ctxid:
            first = AgentContext.first()
            if first:
                AgentContext.use(first.id)
                return first
            context = AgentContext(config=initialize_agent(), set_current=True)
            return context
        got = AgentContext.use(ctxid)
        if got:
            return got
        if create_if_not_exists:
            context = AgentContext(
                config=initialize_agent(), id=ctxid, set_current=True
            )
            return context
        else:
            raise Exception(f"Context {ctxid} not found")