python --version
pip install google-generativeai
export GOOGLE_API_KEY=...
Use Google Gemini API for text, multimodal inputs, function calling, and structured JSON output.
1 import os 2 import json 3 import google.generativeai as genai 4 5 genai.configure(api_key=os.environ["GOOGLE_API_KEY"]) 6 7 # ── 1. Basic text inference ───────────────────────────────────────── 8 model = genai.GenerativeModel("gemini-1.5-flash") 9 response = model.generate_content("Explain transformer architecture in 3 bullet points.") 10 print("=== Text ===") 11 print(response.text) 12 13 # ── 2. Structured JSON output ─────────────────────────────────────── 14 import typing_extensions as typing 15 16 class Movie(typing.TypedDict): 17 title: str 18 year: int 19 genre: str 20 rating: float 21 22 model_structured = genai.GenerativeModel( 23 "gemini-1.5-flash", 24 generation_config=genai.GenerationConfig( 25 response_mime_type="application/json", 26 response_schema=list[Movie], 27 ), 28 ) 29 30 result = model_structured.generate_content( 31 "List 3 classic sci-fi movies with their year, genre, and IMDB rating." 32 ) 33 movies = json.loads(result.text) 34 print("\n=== Structured Output ===") 35 for movie in movies: 36 print(f" {movie['title']} ({movie['year']}) — {movie['rating']}/10") 37 38 # ── 3. Function calling ───────────────────────────────────────────── 39 def search_products(query: str, max_price: float = 100.0) -> dict: 40 """Simulate a product search.""" 41 return { 42 "results": [ 43 {"name": f"Product for {query}", "price": max_price * 0.8}, 44 ] 45 } 46 47 search_tool = genai.protos.Tool( 48 function_declarations=[ 49 genai.protos.FunctionDeclaration( 50 name="search_products", 51 description="Search for products by query and max price", 52 parameters=genai.protos.Schema( 53 type=genai.protos.Type.OBJECT, 54 properties={ 55 "query": genai.protos.Schema(type=genai.protos.Type.STRING), 56 "max_price": genai.protos.Schema(type=genai.protos.Type.NUMBER), 57 }, 58 required=["query"], 59 ), 60 ) 61 ] 62 ) 63 64 chat = model.start_chat() 65 response = chat.send_message( 66 "Find me laptops under $800", 67 tools=[search_tool], 68 ) 69 print("\n=== Function Call ===") 70 for part in response.candidates[0].content.parts: 71 if fn := part.function_call: 72 print(f"Function: {fn.name}, Args: {dict(fn.args)}") 73 # Execute and send result back 74 result = search_products(**fn.args) 75 response2 = chat.send_message( 76 genai.protos.Content(parts=[ 77 genai.protos.Part(function_response=genai.protos.FunctionResponse( 78 name=fn.name, response=result 79 )) 80 ]) 81 ) 82 print(f"Final: {response2.text}") 83
Sign in to share your feedback and join the discussion.