optimize chat funtion