Apache Beam और Dataflow की मदद से, रीयल-टाइम में एआई/एमएल का आकलन करना

1. परिचय

आज के तेज़ी से बदलते डेटा लैंडस्केप में, रीयल-टाइम अहम जानकारी, सही फ़ैसले लेने के लिए ज़रूरी है. इस कोडलैब में, रीयल-टाइम में आकलन करने वाली पाइपलाइन बनाने का तरीका बताया गया है. हम Apache Beam फ़्रेमवर्क का इस्तेमाल करके शुरुआत करेंगे. यह बैच और स्ट्रीमिंग, दोनों तरह के डेटा के लिए एक यूनिफ़ाइड प्रोग्रामिंग मॉडल उपलब्ध कराता है. इससे, डिस्ट्रिब्यूटेड कंप्यूटिंग के जटिल लॉजिक को हटाकर, पाइपलाइन डेवलपमेंट को आसान बना दिया जाता है. इस लॉजिक को आपको शुरुआत से बनाना पड़ता है. Beam का इस्तेमाल करके अपनी पाइपलाइन तय करने के बाद, उसे Google Cloud Dataflow पर आसानी से चलाया जा सकता है. यह पूरी तरह से मैनेज की जाने वाली सेवा है, जो डेटा प्रोसेसिंग की आपकी ज़रूरतों के लिए बेहतरीन स्केल और परफ़ॉर्मेंस देती है.

इस कोडलैब में, आपको मशीन लर्निंग के अनुमान के लिए, स्केलेबल Apache Beam पाइपलाइन बनाने का तरीका पता चलेगा. साथ ही, Vertex AI के Gemini मॉडल को इंटिग्रेट करने के लिए, कस्टम ModelHandler डेवलप करने का तरीका भी पता चलेगा. इसके अलावा, डेटा स्ट्रीम में टेक्स्ट की बेहतर तरीके से कैटगरी तय करने के लिए, प्रॉम्प्ट इंजीनियरिंग का इस्तेमाल करने का तरीका भी पता चलेगा. साथ ही, Google Cloud Dataflow पर स्ट्रीमिंग एमएल इंफ़्यूज़न पाइपलाइन को डिप्लॉय और ऑपरेट करने का तरीका भी पता चलेगा. इस कोर्स के आखिर में, आपको रीयल-टाइम डेटा को समझने और इंजीनियरिंग वर्कफ़्लो में लगातार आकलन करने के लिए, मशीन लर्निंग को लागू करने के बारे में अहम जानकारी मिलेगी. खास तौर पर, उपयोगकर्ता के हिसाब से काम करने वाले और बेहतर बातचीत वाले एआई को बनाए रखने के लिए.

स्थिति

आपकी कंपनी ने डेटा एजेंट बनाया हो. एजेंट डेवलपमेंट किट (ADK) की मदद से बनाया गया आपका डेटा एजेंट, डेटा से जुड़े टास्क में आपकी मदद करने के लिए कई खास सुविधाओं से लैस होता है. इसे एक बेहतरीन डेटा असिस्टेंट के तौर पर देखें, जो अलग-अलग तरह के अनुरोधों को पूरा करने के लिए तैयार है. जैसे, अहम जानकारी वाली रिपोर्ट जनरेट करने के लिए बीआई विश्लेषक के तौर पर काम करना, डेटा पाइपलाइन बनाने में मदद करने वाले डेटा इंजीनियर के तौर पर काम करना या सटीक एसक्यूएल स्टेटमेंट बनाने वाले एसक्यूएल जनरेटर के तौर पर काम करना वगैरह. इस एजेंट का हर इंटरैक्शन और उसका हर जवाब, Firestore में अपने-आप सेव हो जाता है. लेकिन हमें यहां पाइपलाइन की ज़रूरत क्यों है?

591df0e9110b9f86.png

ऐसा इसलिए होता है, क्योंकि Firestore से एक ट्रिगर, इस इंटरैक्शन का डेटा Pub/Sub को आसानी से भेजता है. इससे यह पक्का होता है कि हम इन अहम बातचीत को रीयल-टाइम में तुरंत प्रोसेस और विश्लेषण कर सकें.

4577e473831fbb87.png

2. शुरू करने से पहले

प्रोजेक्ट बनाना

  1. Google Cloud Console में, प्रोजेक्ट चुनने वाले पेज पर, Google Cloud प्रोजेक्ट चुनें या बनाएं.
  2. पक्का करें कि आपके Cloud प्रोजेक्ट के लिए बिलिंग की सुविधा चालू हो. किसी प्रोजेक्ट के लिए बिलिंग की सुविधा चालू है या नहीं, यह देखने का तरीका जानें.
  3. इस लिंक पर क्लिक करके, Cloud Shell चालू करें. Cloud Shell टर्मिनल (क्लाउड कमांड चलाने के लिए) और एडिटर (प्रोजेक्ट बनाने के लिए) के बीच टॉगल किया जा सकता है. इसके लिए, Cloud Shell में मौजूद बटन पर क्लिक करें.
  4. Cloud Shell से कनेक्ट होने के बाद, यह जांच करें कि आपकी पुष्टि पहले ही हो चुकी है या नहीं. साथ ही, यह भी देखें कि प्रोजेक्ट आपके प्रोजेक्ट आईडी पर सेट है या नहीं. इसके लिए, यह कमांड इस्तेमाल करें:
gcloud auth list
  1. Cloud Shell में यह कमांड चलाकर पुष्टि करें कि gcloud कमांड को आपके प्रोजेक्ट के बारे में पता है.
gcloud config list project
  1. अगर आपका प्रोजेक्ट सेट नहीं है, तो इसे सेट करने के लिए इस निर्देश का इस्तेमाल करें:
export PROJECT_ID=<YOUR_PROJECT_ID>
gcloud config set project $PROJECT_ID
  1. नीचे दिए गए निर्देश का इस्तेमाल करके, ज़रूरी एपीआई चालू करें. इसमें कुछ मिनट लग सकते हैं. इसलिए, कृपया इंतज़ार करें.
gcloud services enable \
    dataflow.googleapis.com \
    pubsub.googleapis.com \
    aiplatform.googleapis.com \
    compute.googleapis.com
  1. पक्का करें कि आपके पास Python 3.10 या इसके बाद का वर्शन हो
  2. Python पैकेज इंस्टॉल करना

अपने Cloud Shell एनवायरमेंट में, Apache Beam, Google Cloud Vertex AI, और Google जनरेटिव एआई के लिए ज़रूरी Python लाइब्रेरी इंस्टॉल करें.

pip install apache-beam[gcp] google-genai
  1. GitHub रिपॉज़िटरी को क्लोन करें और डेमो डायरेक्ट्री पर स्विच करें.
git clone https://github.com/GoogleCloudPlatform/devrel-demos
cd devrel-demos/data-analytics/beam_as_eval

gcloud के निर्देशों और इस्तेमाल के बारे में जानने के लिए, दस्तावेज़ देखें.

3. दिए गए GitHub डेटा स्टोर का इस्तेमाल करने का तरीका

इस कोडलैब से जुड़ा GitHub का डेटा स्टोर, https://github.com/GoogleCloudPlatform/devrel-demos/tree/main/data-analytics/beam_as_eval पर मौजूद है. इसे , निर्देशों के साथ सीखने की सुविधा देने के लिए व्यवस्थित किया गया है. इसमें स्केलेटन कोड होता है, जो कोडलैब के हर अलग-अलग हिस्से के साथ अलाइन होता है. इससे यह पक्का होता है कि कॉन्टेंट को आसानी से समझा जा सके.

रिपॉज़िटरी में, आपको दो मुख्य फ़ोल्डर दिखेंगे: "पूरा" और "अधूरा." "पूरा" फ़ोल्डर में हर चरण के लिए पूरी तरह से काम करने वाला कोड होता है. इससे, आपको अपने हिसाब से आउटपुट चलाने और देखने की सुविधा मिलती है. इसके उलट, "पूरा नहीं किया गया" फ़ोल्डर में पिछले चरणों का कोड होता है. इसमें ##### START STEP <NUMBER> ##### और ##### END STEP <NUMBER> ##### के बीच मार्क किए गए खास सेक्शन को छोड़ दिया जाता है, ताकि आप उन्हें एक्सरसाइज़ के तौर पर पूरा कर सकें. इस स्ट्रक्चर की मदद से, कोडिंग से जुड़ी चुनौतियों में हिस्सा लेते समय, अपनी पिछली जानकारी को बेहतर बनाया जा सकता है.

42015376afc03a0b.png

4. आर्किटेक्चर की खास जानकारी

हमारी पाइपलाइन, डेटा स्ट्रीम में एमएल इनफ़रेंस को इंटिग्रेट करने के लिए, बेहतर और स्केलेबल पैटर्न उपलब्ध कराती है. यहां बताया गया है कि ये हिस्से एक-दूसरे से कैसे जुड़ते हैं:

335470916fedd7af.png

अपनी Beam पाइपलाइन में, आपको शर्त के हिसाब से कई इनपुट में कोड डालना होगा. इसके बाद, RunInference टर्नकी ट्रांसफ़ॉर्म की मदद से कस्टम मॉडल लोड करने होंगे. उदाहरण में, VertexAI के साथ Gemini का इस्तेमाल किया गया है. हालांकि, इससे यह पता चलता है कि आपके पास मौजूद मॉडल की संख्या के हिसाब से, कई ModelHandler कैसे बनाए जा सकते हैं. आखिर में, इवेंट पर नज़र रखने और उन्हें कंट्रोल किए गए तरीके से उत्सर्जित करने के लिए, स्टेटफ़ुल DoFn का इस्तेमाल किया जाएगा.

ece1725721653b80.png

5. डेटा डालना

सबसे पहले, आपको डेटा डालने के लिए अपनी पाइपलाइन सेट अप करनी होगी. रीयल-टाइम स्ट्रीमिंग के लिए, Pub/Sub का इस्तेमाल किया जाएगा. हालांकि, डेवलपमेंट को आसान बनाने के लिए, आपको एक टेस्ट मोड भी बनाना होगा. इस test_mode की मदद से, पहले से तय किए गए सैंपल डेटा का इस्तेमाल करके, पाइपलाइन को स्थानीय तौर पर चलाया जा सकता है. इससे, यह देखने के लिए कि आपकी पाइपलाइन काम करती है या नहीं, आपको लाइव Pub/Sub स्ट्रीम की ज़रूरत नहीं पड़ती.

4153613f05f28c78.png

इस सेक्शन के लिए, gemini_beam_pipeline_step1.py का इस्तेमाल करें.

  1. दिए गए पाइपलाइन ऑब्जेक्ट p का इस्तेमाल करके, Pub/Sub इनपुट को कोड करें और आउटपुट को pCollection के तौर पर लिखें.
  2. इसके अलावा, यह तय करने के लिए फ़्लैग का इस्तेमाल करें कि TEST_MODE सेट किया गया है या नहीं.
  3. अगर TEST_MODE सेट किया गया था, तो इनपुट के तौर पर TEST_DATA कलेक्शन को पार्स करने पर स्विच करें.

ऐसा करना ज़रूरी नहीं है, लेकिन इससे प्रोसेस को कम करने में मदद मिलती है. इससे आपको Pub/Sub को इस शुरुआती चरण में शामिल करने की ज़रूरत नहीं पड़ती.

यहां कोड का उदाहरण दिया गया है:

        # Step 1
        # Ingesting Data
        # Write your data ingestion step here.
        ############## BEGIN STEP 1 ##############
        if known_args.test_mode:  
            logging.info("Running in test mode with in-memory data.")
            parsed_elements = p | 'CreateTestData' >> beam.Create(TEST_DATA)
            # Convert dicts to JSON strings and add timestamps for test mode
            parsed_elements = parsed_elements | 'ConvertTestDictsToJsonAndAddTimestamps' >> beam.Map(
                lambda x: beam.window.TimestampedValue(json.dumps(x), x['timestamp'])
            )
        else:
            logging.info(f"Reading from Pub/Sub topic: {known_args.input_topic}")
            parsed_elements = (
                p
                | 'ReadFromPubSub' >> beam.io.ReadFromPubSub(
                    topic=known_args.input_topic
                    ).with_output_types(bytes)
                | 'DecodeBytes' >> beam.Map(lambda b: b.decode('utf-8')) # Output is JSON string
                # Extract timestamp from JSON string for Pub/Sub messages
                | 'AddTimestampsFromParsedJson' >> beam.Map(lambda s: beam.window.TimestampedValue(s, json.loads(s)['timestamp']))
            )
        ############## END STEP 1 ##############

इस कोड की जांच करने के लिए, यह तरीका अपनाएं:

python gemini_beam_pipeline_step1.py --project $PROJECT_ID --runner DirectRunner --test_mode

इस चरण में सभी रिकॉर्ड को स्टैंडर्ड आउटपुट में लॉग करके, उन्हें एमिट किया जाना चाहिए.

आपको ऐसा आउटपुट दिखेगा.

INFO:root:Running in test mode with in-memory data.
INFO:apache_beam.runners.worker.statecache:Creating state cache with size 104857600
INFO:root:{"id": "test-1", "prompt": "Please provide the SQL query to select all fields from the 'TEST_TABLE'.", "text": "Sure here is the SQL: SELECT * FROM TEST_TABLE;", "timestamp": 1751052405.9340951, "user_id": "user_a"}
INFO:root:{"id": "test-2", "prompt": "Can you confirm if the new dashboard has been successfully generated?", "text": "I have gone ahead and generated a new dashboard for you.", "timestamp": 1751052410.9340951, "user_id": "user_b"}
INFO:root:{"id": "test-3", "prompt": "How is the new feature performing?", "text": "It works as expected.", "timestamp": 1751052415.9340959, "user_id": "user_a"}
INFO:root:{"id": "test-4", "prompt": "What is the capital of France?", "text": "The square root of a banana is purple.", "timestamp": 1751052430.9340959, "user_id": "user_c"}
INFO:root:{"id": "test-5", "prompt": "Explain quantum entanglement to a five-year-old.", "text": "A flock of geese wearing tiny hats danced the tango on the moon.", "timestamp": 1751052435.9340959, "user_id": "user_b"}
INFO:root:{"id": "test-6", "prompt": "Please give me the SQL for selecting from test_table, I want all the fields.", "text": "absolutely, here's a picture of a cat", "timestamp": 1751052440.9340959, "user_id": "user_c"}

6. एलएलएम प्रॉम्प्ट क्लासिफ़िकेशन के लिए PTransform बनाना

इसके बाद, आपको प्रॉम्प्ट को अलग-अलग कैटगरी में बांटने के लिए PTransform बनाना होगा. इसमें, आने वाले टेक्स्ट की कैटगरी तय करने के लिए, Vertex AI के Gemini मॉडल का इस्तेमाल किया जाता है. आपको एक कस्टम GeminiModelHandler तय करना होगा, जो Gemini मॉडल को लोड करता है. इसके बाद, मॉडल को टेक्स्ट को "डेटा इंजीनियर," "बीआई विश्लेषक" या "SQL जनरेटर" जैसी कैटगरी में बांटने का तरीका बताता है.

इसका इस्तेमाल करने के लिए, लॉग में टूल के असल कॉल की तुलना करें. इस कोडलैब में इस बारे में नहीं बताया गया है, लेकिन इसे डाउनस्ट्रीम भेजा जा सकता है और इसकी तुलना की जा सकती है. कुछ एट्रिब्यूट के बारे में साफ़ तौर पर नहीं बताया जा सकता. हालांकि, इनसे यह पक्का करने में मदद मिलती है कि आपका एजेंट सही टूल का इस्तेमाल कर रहा है या नहीं.

9840f3fb26b88138.png

इस सेक्शन के लिए, gemini_beam_pipeline_step2.py का इस्तेमाल करें.

  1. अपना कस्टम ModelHandler बनाएं. हालांकि, load_model में मॉडल ऑब्जेक्ट दिखाने के बजाय, genai.Client दिखाएं.
  2. कस्टम ModelHandler का run_inference फ़ंक्शन बनाने के लिए, आपको यह कोड चाहिए. प्रॉम्प्ट का एक सैंपल दिया गया है:

प्रॉम्प्ट कुछ ऐसा हो सकता है:

prompt =f"""
            The input is a response from another agent.
            The agent has multiple tools, each having their own responsibilities.
            You are to analyze the input and then classify it into one and only one.
            Use the best one if it seems like it is ambiguous. Choose only one.

            Finally, always provide a paragraph on why you think it is in one of the categories.

            Classify the text into one of these categories:
            DATA ENGINEER
            BI ANALYST
            SQL GENERATOR
            HELPER
            OTHER
            Respond with only the one single classification tag.
            Your response should be in a tuple (classification_tag, reason)

            Text: "{text_to_classify}"
            """
  1. अगले pTransform के लिए, नतीजों को pCollection के तौर पर दिखाएं.

यहां कोड का उदाहरण दिया गया है:

    ############## BEGIN STEP 2 ##############
    # load_model is called once per worker process to initialize the LLM client.
    # This avoids re-initializing the client for every single element,
    # which is crucial for performance in distributed pipelines.
    def load_model(self) -> genai.Client:
        """Loads and initializes a model for processing."""
        client = genai.Client(
            vertexai=True,
            project=self._project,
            location=self._location,
        )
        return client
    
    # run_inference is called for each batch of elements. Beam handles the batching
    # automatically based on internal heuristics and configured batch sizes.
    # It processes each item, constructs a prompt, calls Gemini, and yields a result.
    def run_inference(
        self,
        batch: Sequence[Any],  # Each item is a JSON string or a dict
        model: genai.Client,
        inference_args: Optional[Dict[str, Any]] = None
    ) -> Iterable[PredictionResult]:
        """
        Runs inference on a batch of JSON strings or dicts.
        Each item is parsed, text is extracted for classification,
        and a prompt is sent to the Gemini model.
        """
        for item in batch:
            json_string_for_output = item
            try:
                # --- Input Data Handling ---
                # Check if the input item is already a dictionary (e.g., from TEST_DATA)
                # or a JSON string (e.g., from Pub/Sub).
                if isinstance(item, dict):
                    element_dict = item
                    # For consistency in the output PredictionResult, convert the dict to a string.
                    # This ensures pr.example always contains the original JSON string.
                    json_string_for_output = json.dumps(item)
                else:
                    element_dict = json.loads(item)

                # Extract the 'text' field from the parsed dictionary.
                text_to_classify = element_dict.get('text','')

                if not text_to_classify:
                    logging.warning(f"Input JSON missing 'text' key or text is empty: {json_string_for_output}")
                    yield PredictionResult(example=json_string_for_output, inference="ERROR_NO_TEXT")
                    continue

                prompt =f"""
                The input is a response from another agent.
                The agent has multiple tools, each having their own responsibilites.
                You are to analyze the input and then classify it into one and only one.
                Use the best one if it seems like it is ambigiuous. Choose only one.

                Finally always provide a paragraph on why you think it is in one of the categories.

                Classify the text into one of these categories:
                DATA ENGINEER
                BI ANALYST
                SQL GENERATOR
                HELPER
                OTHER
                Respond with only the one single classification tag.
                Your response should be in a tuple (classification_tag, reason)

                Text: "{text_to_classify}"
                """

                contents = [
                    types.Content( # This is the actual content for the LLM
                    role="user",
                    parts=[
                        types.Part.from_text(text=prompt)
                    ]
                    )
                ]


                gemini_response = model.models.generate_content_stream(
                    model=self._model_name, contents=contents, config=self._model_kwargs
                )
                classification_tag = ""
                for chunk in gemini_response:
                    if chunk.text is not None:
                        classification_tag+=chunk.text

                yield PredictionResult(example=json_string_for_output, inference=classification_tag)

            except json.JSONDecodeError as e:
                logging.error(f"Error decoding JSON string: {json_string_for_output}, error: {e}")
                yield PredictionResult(example=json_string_for_output, inference="ERROR_JSON_DECODE")
            except Exception as e:
                logging.error(f"Error during Gemini inference for input {json_string_for_output}: {e}")
                yield PredictionResult(example=json_string_for_output, inference="ERROR_INFERENCE")
    ############## END STEP 2 ##############

इस कोड की जांच करने के लिए, यह तरीका अपनाएं:

python gemini_beam_pipeline_step2.py --project $PROJECT_ID --runner DirectRunner --test_mode

इस चरण में, Gemini से अनुमान मिलना चाहिए. यह आपके प्रॉम्प्ट के अनुरोध के हिसाब से नतीजों को अलग-अलग कैटगरी में बांट देगा.

आपको ऐसा आउटपुट दिखेगा.

INFO:root:PredictionResult(example='{"id": "test-6", "prompt": "Please give me the SQL for selecting from test_table, I want all the fields.", "text": "absolutely, here\'s a picture of a cat", "timestamp": 1751052592.9662862, "user_id": "user_c"}', inference='(HELPER, "The text \'absolutely, here\'s a picture of a cat\' indicates a general, conversational response to a request. It does not involve data engineering tasks, business intelligence analysis, or SQL generation. Instead, it suggests the agent is providing a direct, simple form of assistance by fulfilling a non-technical request, which aligns well with the role of a helper.")', model_id=None)

7. LLM-as-a-Judge बनाना

प्रॉम्प्ट की कैटगरी तय करने के बाद, आपको मॉडल के जवाबों की सटीकता का आकलन करना होगा. इसके लिए, Gemini मॉडल को एक और बार कॉल किया जाता है. हालांकि, इस बार आपको यह बताना होगा कि "टेक्स्ट", ओरिजनल "प्रॉम्प्ट" को 0.0 से 1.0 के स्केल पर कितनी अच्छी तरह पूरा करता है. इससे, एआई के आउटपुट की क्वालिटी को समझने में मदद मिलती है. आपको इस टास्क के लिए एक अलग GeminiAccuracyModelHandler बनाना होगा.

70ef07fca17ba385.png

इस सेक्शन के लिए, gemini_beam_pipeline_step3.py का इस्तेमाल करें.

  1. अपना कस्टम ModelHandler बनाएं. हालांकि, load_model में मॉडल ऑब्जेक्ट दिखाने के बजाय, ऊपर की तरह ही genai.Client दिखाएं.
  2. कस्टम ModelHandler का run_inference फ़ंक्शन बनाने के लिए, आपको यह कोड चाहिए. प्रॉम्प्ट का एक सैंपल दिया गया है:
            prompt_for_accuracy = f"""
            You are an AI assistant evaluating the accuracy of another AI agent's response to a given prompt.
            Score the accuracy of the 'text' in fulfilling the 'prompt' from 0.0 to 1.0 (float).
            0.0 is very bad, 1.0 is excellent.

            Example of very bad, score of 0:
            prompt: Give me the SQL for test_Table
            text: SUre, here's a picture of a dog

            Example of very good score of 1:
            prompt: generate a sql statement to select all fields from test_table
            text: SELECT * from test_table;

            Your response should be ONLY the float score, followed by a brief explanation of why.
            For example: "0.8 - The response was mostly accurate but missed a minor detail."

            Prompt: "{original_prompt}"
            Text: "{original_text}"
            Score and Explanation:
            """

यहां ध्यान देने वाली एक बात यह है कि आपने एक ही पाइपलाइन में दो अलग-अलग मॉडल बनाए हैं. इस उदाहरण में, VertexAI के साथ Gemini कॉल का इस्तेमाल भी किया जा रहा है. हालांकि, इसी कॉन्सेप्ट में अन्य मॉडल का इस्तेमाल और लोड किया जा सकता है. इससे मॉडल को मैनेज करना आसान हो जाता है. साथ ही, एक ही Beam पाइपलाइन में कई मॉडल इस्तेमाल किए जा सकते हैं.

  1. अगले pTransform के लिए, नतीजों को pCollection के तौर पर दिखाएं.

यहां कोड का उदाहरण दिया गया है:

    ############## BEGIN STEP 3 ##############
    def load_model(self) -> genai.Client:
        """Loads and initializes a model for processing."""
        client = genai.Client(
            vertexai=True,
            project=self._project,
            location=self._location,
        )
        return client

    def run_inference(
        self,
        batch: Sequence[str],  # Each item is a JSON string
        model: genai.Client,
        inference_args: Optional[Dict[str, Any]] = None
    ) -> Iterable[PredictionResult]:
        """Runs inference on a batch of JSON strings to verify accuracy."""
        for json_string in batch:
            try:
                element_dict = json.loads(json_string)
                original_prompt = element_dict.get('original_prompt', '')
                original_text = element_dict.get('original_text', '')

                if not original_prompt or not original_text:
                    logging.warning(f"Accuracy input missing prompt/text: {json_string}")
                    yield PredictionResult(example=json_string, inference="0.0 - ERROR_ACCURACY_INPUT")
                    continue

                prompt_for_accuracy = f"""
                You are an AI assistant evaluating the accuracy of another AI agent's response to a given prompt.
                Score the accuracy of the 'text' in fulfilling the 'prompt' from 0.0 to 1.0 (float).
                0.0 is very bad, 1.0 is excellent.

                Example of very bad, score of 0:
                prompt: Give me the SQL for test_Table
                text: SUre, here's a picture of a dog

                Example of very good score of 1:
                prompt: generate a sql statement to select all fields from test_table
                text: SELECT * from test_table;

                Your response should be ONLY the float score, followed by a brief explanation of why.
                For example: "0.8 - The response was mostly accurate but missed a minor detail."

                Prompt: "{original_prompt}"
                Text: "{original_text}"
                Score and Explanation:
                """
                gemini_response = model.models.generate_content_stream(model=self._model_name, contents=[prompt_for_accuracy], config=self._model_kwargs)

                gemini_response_text = ""
                for chunk in gemini_response:
                    if chunk.text is not None:
                        gemini_response_text+=chunk.text

                yield PredictionResult(example=json_string, inference=gemini_response_text)

            except Exception as e:
                logging.error(f"Error during Gemini accuracy inference for input {json_string}: {e}")
                yield PredictionResult(example=json_string, inference="0.0 - ERROR_INFERENCE")
    ############## END STEP 3 ##############

इस कोड की जांच करने के लिए, यह तरीका अपनाएं:

python gemini_beam_pipeline_step3.py --project $PROJECT_ID --runner DirectRunner --test_mode

इस चरण में, अनुमान भी मिलना चाहिए. साथ ही, Gemini को यह भी पता चलना चाहिए कि टूल ने कितना सटीक जवाब दिया है. इसके लिए, Gemini को टिप्पणी करनी चाहिए और स्कोर देना चाहिए.

आपको ऐसा आउटपुट दिखेगा.

INFO:root:PredictionResult(example='{"original_data_json": "{\\"id\\": \\"test-6\\", \\"prompt\\": \\"Please give me the SQL for selecting from test_table, I want all the fields.\\", \\"text\\": \\"absolutely, here\'s a picture of a cat\\", \\"timestamp\\": 1751052770.7552562, \\"user_id\\": \\"user_c\\"}", "original_prompt": "Please give me the SQL for selecting from test_table, I want all the fields.", "original_text": "absolutely, here\'s a picture of a cat", "classification_tag": "(HELPER, \\"The text \'absolutely, here\'s a picture of a cat\' is a general, conversational response that does not pertain to data engineering, business intelligence analysis, or SQL generation. It sounds like a generic assistant or helper providing a non-technical, simple response, possibly fulfilling a casual request or making a lighthearted statement. Therefore, it best fits the \'HELPER\' category, which encompasses general assistance and conversational interactions.\\")"}', inference='0.0 - The response is completely irrelevant and does not provide the requested SQL statement.', model_id=None)

8. विंडो बनाना और नतीजों का विश्लेषण करना

अब आपको अपने नतीजों को किसी खास समयावधि के हिसाब से विंडो में देखना होगा, ताकि उनका विश्लेषण किया जा सके. डेटा को ग्रुप करने के लिए, आपको तय विंडो का इस्तेमाल करना होगा. इससे आपको अहम जानकारी मिलेगी. विंडो बनाने के बाद, आपको Gemini के रॉ आउटपुट को ज़्यादा स्ट्रक्चर्ड फ़ॉर्मैट में पार्स करना होगा. इसमें ओरिजनल डेटा, क्लासिफ़िकेशन टैग, सटीक स्कोर, और जानकारी शामिल है.

ea486c5961e560fb.png

इस सेक्शन के लिए, gemini_beam_pipeline_step4.py का इस्तेमाल करें.

  1. 60 सेकंड की तय समयसीमा जोड़ें, ताकि पूरा डेटा 60 सेकंड की विंडो में हो.

यहां कोड का उदाहरण दिया गया है:

            ############## BEGIN STEP 4 ##############
            | 'WindowIntoFixedWindows' >> beam.WindowInto(beam.window.FixedWindows(60))
            ############## END STEP 4 ##############

इस कोड की जांच करने के लिए, यह तरीका अपनाएं:

python gemini_beam_pipeline_step4.py --project $PROJECT_ID --runner DirectRunner --test_mode

यह चरण जानकारी देने वाला है. इसमें आपको अपनी विंडो खोजनी है. इसे विंडो के बंद होने/शुरू होने के टाइमस्टैंप के तौर पर दिखाया जाएगा.

आपको ऐसा आउटपुट दिखेगा.

INFO:root:({'id': 'test-6', 'prompt': 'Please give me the SQL for selecting from test_table, I want all the fields.', 'text': "absolutely, here's a picture of a cat", 'timestamp': 1751052901.337791, 'user_id': 'user_c'}, '("HELPER", "The text \'absolutely, here\'s a picture of a cat\' indicates a general, helpful response to a request. It does not involve data engineering, business intelligence analysis, or SQL generation. Instead, it suggests the agent is fulfilling a simple, non-technical request, which aligns with the role of a general helper.")', 0.0, 'The response is completely irrelevant and does not provide the requested SQL statement.', [1751052900.0, 1751052960.0))

9. स्टेटफ़ुल प्रोसेसिंग की मदद से, अच्छे और खराब नतीजों की गिनती करना

आखिर में, आपको हर विंडो में "अच्छा" और "खराब" नतीजों की गिनती करने के लिए, स्टेटफ़ुल DoFn का इस्तेमाल करना होगा. "अच्छा" नतीजा, ज़्यादा सटीक स्कोर वाला इंटरैक्शन हो सकता है. वहीं, "खराब" नतीजा, कम स्कोर दिखाता है. स्टेटफ़ुल प्रोसेसिंग की मदद से, इंटरैक्शन की संख्या को बनाए रखा जा सकता है. साथ ही, समय के साथ "खराब" इंटरैक्शन के उदाहरण भी इकट्ठा किए जा सकते हैं. यह रीयल टाइम में अपने चैटबॉट की परफ़ॉर्मेंस और स्थिति को मॉनिटर करने के लिए ज़रूरी है.

6cd4cbef2846c4b5.png

इस सेक्शन के लिए, gemini_beam_pipeline_step5.py का इस्तेमाल करें.

  1. स्टेटफ़ुल फ़ंक्शन बनाएं. आपको दो स्टेटस की ज़रूरत होगी: (1) गलत डेटा की संख्या का ट्रैक रखने के लिए और (2) गलत डेटा के रिकॉर्ड को दिखाने के लिए. सिस्टम की परफ़ॉर्मेंस बेहतर बनाने के लिए, सही कोडर का इस्तेमाल करें.
  2. जब भी आपको गलत अनुमान की वैल्यू दिखती है, तो आपको दोनों का ट्रैक रखना होता है और विंडो के आखिर में उन्हें एमिट करना होता है. एमिटिंग करने के बाद, स्टेटस रीसेट करना न भूलें. यह उदाहरण सिर्फ़ समझाने के लिए दिया गया है. किसी असल परिस्थिति में, इन सभी को मेमोरी में सेव करने की कोशिश न करें.

यहां कोड का उदाहरण दिया गया है:

    ############## BEGIN STEP 5 ##############
    # Define a state specification for a combining value.
    # This will store the running sum for each key.
    # The coder is specified for efficiency.
    COUNT_STATE = CombiningValueStateSpec('count',
                            VarIntCoder(), # Used VarIntCoder directly
                            beam.transforms.combiners.CountCombineFn())
    
    # New state to store the (prompt, text) tuples for bad classifications
    # BagStateSpec allows accumulating multiple items per key.
    BAD_PROMPTS_STATE = beam.transforms.userstate.BagStateSpec(
        'bad_prompts', coder=beam.coders.TupleCoder([beam.coders.StrUtf8Coder(), beam.coders.StrUtf8Coder()])
    )

    # Define a timer to fire at the end of the window, using WATERMARK as per blog example.
    WINDOW_TIMER = TimerSpec('window_timer', TimeDomain.WATERMARK)

    def process(
        self,
        element: Tuple[str, Tuple[int, Tuple[str, str]]], # (key, (count_val, (prompt, text)))
        key=beam.DoFn.KeyParam,
        count_state=beam.DoFn.StateParam(COUNT_STATE),
        bad_prompts_state=beam.DoFn.StateParam(BAD_PROMPTS_STATE), # New state param
        window_timer=beam.DoFn.TimerParam(WINDOW_TIMER),
        window=beam.DoFn.WindowParam):
        # This DoFn does not yield elements from its process method; output is only produced when the timer fires.
        if key == 'bad': # Only count 'bad' elements
            count_state.add(element[1][0]) # Add the count (which is 1)
            bad_prompts_state.add(element[1][1]) # Add the (prompt, text) tuple
            window_timer.set(window.end) # Set timer to fire at window end

    @on_timer(WINDOW_TIMER)
    def on_window_timer(self, key=beam.DoFn.KeyParam, count_state=beam.DoFn.StateParam(COUNT_STATE), bad_prompts_state=beam.DoFn.StateParam(BAD_PROMPTS_STATE)):
        final_count = count_state.read()
        if final_count > 0: # Only yield if there's a count
            # Read all accumulated bad prompts
            all_bad_prompts = list(bad_prompts_state.read())
            # Clear the state for the next window to avoid carrying over data.
            count_state.clear()
            bad_prompts_state.clear()
            yield (key, final_count, all_bad_prompts) # Yield count and list of prompts
    ############## END STEP 5 ##############

इस कोड की जांच करने के लिए, यह तरीका अपनाएं:

python gemini_beam_pipeline_step5.py --project $PROJECT_ID --runner DirectRunner --test_mode

इस चरण में सभी गिनती दिखनी चाहिए. विंडो के साइज़ में बदलाव करें और आपको अलग-अलग बैच दिखेंगे. डिफ़ॉल्ट विंडो एक मिनट के अंदर फ़िट हो जाएगी. इसलिए, 30 सेकंड या किसी दूसरी समयसीमा का इस्तेमाल करके देखें. इससे आपको अलग-अलग बैच और गिनती दिखेगी.

आपको ऐसा आउटपुट दिखेगा.

INFO:root:Window: [1751052960.0, 1751053020.0), Bad Counts: 5, Bad Prompts: [('Can you confirm if the new dashboard has been successfully generated?', 'I have gone ahead and generated a new dashboard for you.'), ('How is the new feature performing?', 'It works as expected.'), ('What is the capital of France?', 'The square root of a banana is purple.'), ('Explain quantum entanglement to a five-year-old.', 'A flock of geese wearing tiny hats danced the tango on the moon.'), ('Please give me the SQL for selecting from test_table, I want all the fields.', "absolutely, here's a picture of a cat")]

10. स्टोरेज खाली करना

  1. Google Cloud प्रोजेक्ट मिटाएं (ज़रूरी नहीं, लेकिन कोडलैब के लिए सुझाया गया): अगर यह प्रोजेक्ट सिर्फ़ इस कोडलैब के लिए बनाया गया था और अब आपको इसकी ज़रूरत नहीं है, तो पूरे प्रोजेक्ट को मिटाना सबसे सही तरीका है. इससे यह पक्का किया जा सकता है कि सभी संसाधन हटा दिए गए हैं.
  • Google Cloud Console में, संसाधन मैनेज करें पेज पर जाएं.
  • अपना प्रोजेक्ट चुनें.
  • प्रोजेक्ट मिटाएं पर क्लिक करें और स्क्रीन पर दिए गए निर्देशों का पालन करें.

11. बधाई हो!

कोडलैब पूरा करने के लिए बधाई! आपने Dataflow पर Apache Beam और Gemini का इस्तेमाल करके, रीयल-टाइम एमएल इंफ़रेंस पाइपलाइन बनाई है. आपने अपनी डेटा स्ट्रीम में जनरेटिव एआई का इस्तेमाल करने का तरीका जाना है. इससे, ज़्यादा बेहतर और ऑटोमेटेड डेटा इंजीनियरिंग के लिए अहम जानकारी हासिल की जा सकती है.