Was Bhagavad Gita directly written by God / Sri Krishna?
No. Bhagavad Gita was a verbal discourse given by God (Sri Krishna) to Arjuna just before the beginning of Kurukshetra war.
Since no other person was around except the two, how was it recorded? Maharshi Vyasa (who was one of the incarnations of Lord Vishnu as per Bhagavata Purana) had given special powers of visualization (‘dhoordarshan‘) to Sanjaya, a personal assistant/ minister of blind Kaurava King Dhritarashtra to remotely witness all that happened in the Kurukshetra war in order to narrate them to the blind king.
Maharshi Vyasa was one of the most prime characters in Mahabharata. He was a rishi having many mystic powers. He was the one who fathered Dhritarashtra and Pandu. Thus he was the grandfather of both Kauravas (Sons of Dritarashtra) and Pandavas (sons of Pandu). He was one central personality who was a knower of trikala (past, present and future) and he would present himself physically at most critical places and times amidst his kin in order to give them solace when in trouble and guide them on dharma. Thus he was an eye-witness and also a historian of the entire Mahabharata story.
Much later after the period of Pandavas and Kauravas, he formed in his mind the entire story of Mahabharata as a grand Itihasa which was too monumental a work to put into writing. Conceding to his prayers, Lord Brahma engaged Lord Ganesha to do the writing of this grand epic on palm leaves based on the dictations of Vyasa.
Bhagavad Gita is part and parcel of Mahabharata, and it comes in the middle of Mahabharata as part of the Bhishma Parva/
Interestingly, Vyasa’s Mahabharata text as we have today is not a direct narration of Vyasa but appears as narrated by the Pouranika (Purana exponent) by name Ugrasrava, son of Romaharshana Rishi, surnamed Souti to the rishis of Naimisharanya!
He narrated it as heard by him from Maharishi Vysampayana (a disciple of Vyaasa) to King Janamejaya (Grandson of Abhimanyu and great-grandson of Arjuna ) during a Sarpa Yagna in the august presence of Sage Vyaasa himself.
We cannot help but get wonderstruck by the power of memory and transmission our rishis of the past had on account of their severe austerities (Tapas).