Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Include Chat History When Using Google Gemini's API

I'm trying to feed chat history to the Google Gemini API using a cURL request. I want to provide both the user's previous input and the model's previous response in the request. Here's the cURL command I'm using:

curl --location 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' \
--header 'Content-Type: application/json' \
--data '{
    "contents": [
        {
            "role": "model",
            "parts": [
                {
                    "text": "...model data"
                }
            ]
        },
        {
            "role": "user",
            "parts": [
                {
                    "text": "...user input"
                }
            ]
        }
    ],
    "history": [
        {
            "role": "user",
            "parts": [
                {
                    "text": "Hello, I have 2 dogs in my house."
                }
            ]
        },
        {
            "role": "model",
            "parts": [
                {
                    "text": "Great to meet you. What would you like to know?"
                }
            ]
        }
    ]
}'

I'm not sure if I'm formatting the contents and history sections correctly.

I expected the model to understand the previous exchanges and continue the conversation accordingly.

like image 662
ABDUL HAAFIZ Avatar asked Sep 03 '25 17:09

ABDUL HAAFIZ


1 Answers

History is part of the same cotent you just have to put it in order

"contents": [
        {
            "role": "model",
            "parts": [
                {
                    "text": "...model data"
                }
            ]
        },
        {
            "role": "user",
            "parts": [
                {
                    "text": "...user input"
                }
            ]
        }
    ],

The final one is the current one that the model will answer based upon the history or all the other entries in contents.

like image 147
DaImTo Avatar answered Sep 05 '25 16:09

DaImTo