def test_tokens_chat()

in python/count_tokens.py [0:0]


    def test_tokens_chat(self):
        # [START tokens_chat]
        from google import genai
        from google.genai import types

        client = genai.Client()

        chat = client.chats.create(
            model="gemini-2.0-flash",
            history=[
                types.Content(
                    role="user", parts=[types.Part(text="Hi my name is Bob")]
                ),
                types.Content(role="model", parts=[types.Part(text="Hi Bob!")]),
            ],
        )
        # Count tokens for the chat history.
        print(
            client.models.count_tokens(
                model="gemini-2.0-flash", contents=chat.get_history()
            )
        )
        # ( e.g., total_tokens: 10 )

        response = chat.send_message(
            message="In one sentence, explain how a computer works to a young child."
        )
        print(response.usage_metadata)
        # ( e.g., prompt_token_count: 25, candidates_token_count: 21, total_token_count: 46 )

        # You can count tokens for the combined history and a new message.
        extra = types.UserContent(
            parts=[
                types.Part(
                    text="What is the meaning of life?",
                )
            ]
        )
        history = chat.get_history()
        history.append(extra)
        print(client.models.count_tokens(model="gemini-2.0-flash", contents=history))