Pastebin

Paste #28299: No description

< previous paste - next paste>

Pasted by Anonymous Coward

Download View as text

import requests
import json

def query_gemini(current_sentence, prefix_string, api_key):
    """
    Takes a sentence, prefixes it with a string, sends to Gemini model using requests,
    and stores the response in a variable.
    
    Args:
        current_sentence (str): The current sentence to process
        prefix_string (str): The prefix to add before the sentence
        api_key (str): Your Gemini API key
        
    Returns:
        str: The response from the Gemini model
    """
    # Combine the prefix and the current sentence
    prompt = f"{prefix_string} {current_sentence}"
    
    # Prepare the request
    url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent"
    headers = {
        "Content-Type": "application/json"
    }
    
    # Add API key as query parameter
    url = f"{url}?key={api_key}"
    
    # Prepare the payload
    payload = {
        "contents": [{"parts": [{"text": prompt}]}]
    }
    
    # Send the request
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    
    # Parse the response
    if response.status_code == 200:
        response_json = response.json()
        # Extract text from the response
        if 'candidates' in response_json and len(response_json['candidates']) > 0:
            candidate = response_json['candidates'][0]
            if 'content' in candidate and 'parts' in candidate['content']:
                gemini_response = candidate['content']['parts'][0]['text']
                return gemini_response
    
    # Return error message if something went wrong
    return f"Error: {response.status_code}, {response.text}"

# Example usage
if __name__ == "__main__":
    # Replace with your API key
    api_key = "AIzaSyCQf_SF4Sbwd-m-D2IYx8XTw21B18gBnIU"
    
    # Example sentence and prefix
    current_sentence = "What are the key features of Python?"
    prefix_string = "Explain briefly:"
    
    # Call the function and store the response
    result = query_gemini(current_sentence, prefix_string, api_key)
    
    # Print the result
    print(f"Prompt: {prefix_string} {current_sentence}")
    print(f"Response from Gemini: {result}")

New Paste


Do not write anything in this field if you're a human.

Go to most recent paste.