|
| 1 | +"""Google Gemini chat with tool calling, tracked by PostHog.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import json |
| 5 | +import urllib.request |
| 6 | +from google.genai import types |
| 7 | +from posthog import Posthog |
| 8 | +from posthog.ai.gemini import Client |
| 9 | + |
| 10 | +posthog = Posthog( |
| 11 | + os.environ["POSTHOG_API_KEY"], |
| 12 | + host=os.environ.get("POSTHOG_HOST", "https://us.i.posthog.com"), |
| 13 | +) |
| 14 | +client = Client(api_key=os.environ["GEMINI_API_KEY"], posthog_client=posthog) |
| 15 | + |
| 16 | +tool_declarations = [ |
| 17 | + { |
| 18 | + "name": "get_weather", |
| 19 | + "description": "Get current weather for a location", |
| 20 | + "parameters": { |
| 21 | + "type": "object", |
| 22 | + "properties": { |
| 23 | + "latitude": {"type": "number"}, |
| 24 | + "longitude": {"type": "number"}, |
| 25 | + "location_name": {"type": "string"}, |
| 26 | + }, |
| 27 | + "required": ["latitude", "longitude", "location_name"], |
| 28 | + }, |
| 29 | + } |
| 30 | +] |
| 31 | + |
| 32 | + |
| 33 | +def get_weather(latitude: float, longitude: float, location_name: str) -> str: |
| 34 | + url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,relative_humidity_2m,wind_speed_10m" |
| 35 | + with urllib.request.urlopen(url) as resp: |
| 36 | + data = json.loads(resp.read()) |
| 37 | + current = data["current"] |
| 38 | + return f"Weather in {location_name}: {current['temperature_2m']}°C, humidity {current['relative_humidity_2m']}%, wind {current['wind_speed_10m']} km/h" |
| 39 | + |
| 40 | + |
| 41 | +config = types.GenerateContentConfig( |
| 42 | + tools=[types.Tool(function_declarations=tool_declarations)] |
| 43 | +) |
| 44 | + |
| 45 | +response = client.models.generate_content( |
| 46 | + model="gemini-2.5-flash", |
| 47 | + posthog_distinct_id="example-user", |
| 48 | + contents=[{"role": "user", "parts": [{"text": "What's the weather in London?"}]}], |
| 49 | + config=config, |
| 50 | +) |
| 51 | + |
| 52 | +# In production, send tool results back to the model for a final response. |
| 53 | +for candidate in response.candidates: |
| 54 | + for part in candidate.content.parts: |
| 55 | + if hasattr(part, "function_call") and part.function_call: |
| 56 | + result = get_weather( |
| 57 | + latitude=part.function_call.args["latitude"], |
| 58 | + longitude=part.function_call.args["longitude"], |
| 59 | + location_name=part.function_call.args["location_name"], |
| 60 | + ) |
| 61 | + print(result) |
| 62 | + elif hasattr(part, "text"): |
| 63 | + print(part.text) |
| 64 | + |
| 65 | +posthog.shutdown() |
0 commit comments