77"""
88import os
99import json
10- from pydantic import BaseModel
10+ from datetime import datetime
11+ from pydantic import BaseModel , Field
1112from typing import Type , TypeVar , List
1213from dotenv import load_dotenv
1314from langchain_openai import AzureChatOpenAI , AzureOpenAIEmbeddings
14- from azure .cosmos import CosmosClient , ContainerProxy
15+ from azure .cosmos import CosmosClient , ContainerProxy , PartitionKey
1516from langchain_core .prompts import ChatPromptTemplate , MessagesPlaceholder
1617from langchain_core .tools import StructuredTool
1718from langchain .agents .agent_toolkits import create_retriever_tool
3637product_v_container = db .get_container_client ("product_v" )
3738sales_order_container = db .get_container_client ("salesOrder" )
3839
40+ # Initialize the chat session container, create if not exists
41+ db .create_container_if_not_exists (id = "chat_session" , partition_key = PartitionKey (path = "/id" ))
42+ chat_session_container = db .get_container_client ("chat_session" )
43+
44+
45+ class ChatSession (BaseModel ):
46+ id : str # The session ID
47+ title : str # The title of the chat session
48+ history : List [dict ] = Field (default_factory = list ) # The chat history
49+
3950class CosmicWorksAIAgent :
4051 """
4152 The CosmicWorksAIAgent class creates Cosmo, an AI agent
@@ -44,6 +55,9 @@ class CosmicWorksAIAgent:
4455 """
4556 def __init__ (self , session_id : str ):
4657 self .session_id = session_id
58+
59+ self .chat_session = self .load_or_create_chat_session (session_id )
60+
4761 llm = AzureChatOpenAI (
4862 temperature = 0 ,
4963 openai_api_version = AOAI_API_VERSION ,
@@ -97,10 +111,46 @@ def run(self, prompt: str) -> str:
97111 """
98112 Run the AI agent.
99113 """
100- result = self .agent_executor .invoke ({"input" : prompt })
101- return result ["output" ]
102114
115+ # Add the existing chat history to the prompt
116+ chat_history = [{"role" : msg ["role" ], "content" : msg ["content" ]} for msg in self .chat_session .history ]
117+ full_prompt = {
118+ "input" : prompt ,
119+ "chat_history" : chat_history
120+ }
121+
122+ # Run the AI agent with the chat history context
123+ result = self .agent_executor .invoke (full_prompt )
124+ response = result ["output" ]
125+
126+ # Update chat history with new interaction
127+ self .chat_session .history .append ({"role" : "user" , "content" : prompt })
128+ self .chat_session .history .append ({"role" : "assistant" , "content" : response })
129+
130+ # Save updated chat history to Cosmos DB
131+ chat_session_container .upsert_item (self .chat_session .dict ())
103132
133+ return response
134+
135+ def load_or_create_chat_session (self , session_id : str ) -> ChatSession :
136+ """
137+ Load an existing session from the Cosmos DB container, or create a new one if not found.
138+ """
139+ try :
140+ # Try to read the session from Cosmos DB
141+ session_item = chat_session_container .read_item (item = session_id , partition_key = session_id )
142+ return ChatSession (** session_item )
143+ except Exception :
144+ # If the session is not found, create a new one
145+ new_session = ChatSession (
146+ id = session_id ,
147+ session_id = session_id ,
148+ title = f"{ datetime .utcnow ().strftime ('%Y-%m-%d %H:%M:%S UTC' )} " ,
149+ chat_history = []
150+ )
151+ chat_session_container .upsert_item (new_session .model_dump ())
152+ return new_session
153+
104154# Tools helper methods
105155def delete_attribute_by_alias (instance : BaseModel , alias :str ):
106156 """
0 commit comments