@@ -83,28 +83,29 @@ async def main():
8383 _require ("OPENAI_API_KEY" ) # read by AsyncOpenAI from the environment
8484
8585 moss = MossClient (project_id = project_id , project_key = project_key )
86- llm = AsyncOpenAI ()
87-
88- # A Moss session is the cache store. We use a unique name per run so the demo
89- # always starts empty and shows a clean MISS -> HIT (a session auto-loads an
90- # existing cloud index of the same name, which would otherwise make the first
91- # question a HIT). In production, use a stable name and call
92- # `await store.push_index()` to persist the cache across runs and processes.
93- store = await moss .session (index_name = f"qa-cache-demo-{ uuid .uuid4 ().hex [:8 ]} " )
94- cache = SemanticCache (store , llm )
95-
96- # the 2nd question means the same as the 1st, phrased differently -> cache hit
97- questions = [
98- "What are your opening hours?" ,
99- "when do you open?" ,
100- "How do I reset my password?" ,
101- ]
102- for q in questions :
103- t = time .perf_counter ()
104- answer , hit = await cache .ask (q )
105- ms = (time .perf_counter () - t ) * 1000
106- tag = "HIT " if hit else "MISS"
107- print (f"[{ tag } { ms :7.1f} ms] { q } \n -> { answer .strip ()[:90 ]} \n " )
86+
87+ # AsyncOpenAI owns an HTTP client; the context manager closes it on exit.
88+ async with AsyncOpenAI () as llm :
89+ # A Moss session is the cache store. We use a unique name per run so the demo
90+ # always starts empty and shows a clean MISS -> HIT (a session auto-loads an
91+ # existing cloud index of the same name, which would otherwise make the first
92+ # question a HIT). In production, use a stable name and call
93+ # `await store.push_index()` to persist the cache across runs and processes.
94+ store = await moss .session (index_name = f"qa-cache-demo-{ uuid .uuid4 ().hex [:8 ]} " )
95+ cache = SemanticCache (store , llm )
96+
97+ # the 2nd question means the same as the 1st, phrased differently -> cache hit
98+ questions = [
99+ "What are your opening hours?" ,
100+ "when do you open?" ,
101+ "How do I reset my password?" ,
102+ ]
103+ for q in questions :
104+ t = time .perf_counter ()
105+ answer , hit = await cache .ask (q )
106+ ms = (time .perf_counter () - t ) * 1000
107+ tag = "HIT " if hit else "MISS"
108+ print (f"[{ tag } { ms :7.1f} ms] { q } \n -> { answer .strip ()[:90 ]} \n " )
108109
109110
110111if __name__ == "__main__" :
0 commit comments