Notebooks
G
Google Gemini
Search Reranking Using Embeddings

Search Reranking Using Embeddings

gemini-cookbookgemini-apiexamplesgemini
Copyright 2025 Google LLC.
[ ]

Search re-ranking using Gemini embeddings

⚠️

This notebook requires paid tier rate limits to run properly.
(cf. pricing for more details).

This notebook demonstrates the use of embeddings to re-rank search results. This walkthrough will focus on the following objectives:

  1. Setting up your development environment and API access to use Gemini.
  2. Using Gemini's function calling support to access the Wikipedia API.
  3. Embedding content via Gemini API.
  4. Re-ranking the search results.

This is how you will implement search re-ranking:

  1. The user will make a search query.
  2. You will use Wikipedia API to return the relevant search results.
  3. The search results will be embedded and their relevance will be evaluated by calculating distance metrics like cosine similarity.
  4. The most relevant search result will be returned as the final answer.

The non-source code materials in this notebook are licensed under Creative Commons - Attribution-ShareAlike CC-BY-SA 4.0, https://creativecommons.org/licenses/by-sa/4.0/legalcode.

Setup

First, download and install the Gemini API Python library.

[1]

Also install the wikipedia package that will be used during this tutorial.

[2]

Note: The wikipedia package notes that it was "designed for ease of use and simplicity, not for advanced use", and that production or heavy use should instead "use Pywikipediabot or one of the other more advanced Python MediaWiki API wrappers".

[11]

Grab an API Key

Before you can use the Gemini API, you must first obtain an API key. If you don't already have one, create a key with one click in Google AI Studio.

Get an API key

In Colab, add the key to the secrets manager under the "🔑" in the left panel. Give it the name GEMINI_API_KEY.

Once you have the API key, pass it to the SDK. You can do this in two ways:

  • Put the key in the GEMINI_API_KEY environment variable (the SDK will automatically pick it up from there).
  • Pass the key to genai.Client(api_key=...)
[ ]

Select the model to be used

[7]
MODEL_ID

Define tools

As stated earlier, this tutorial uses Gemini's function calling support to access the Wikipedia API. Please refer to the docs to learn more about function calling.

Define the search function

To cater to the search engine needs, you will design this function in the following way:

  • For each search query, the search engine will use the wikipedia.search method to get relevant topics.
  • From the relevant topics, the engine will choose n_topics(int) top candidates and will use gemini-2.5-flash to extract relevant information from the page.
  • The engine will avoid duplicate entries by maintaining a search history.
[8]
[9]
Searching for "What are LLMs?"
Related search terms: ['Large language model', 'Retrieval-augmented generation', 'Gemini (chatbot)']
Fetching page: "Large language model"
Information Source: https://en.wikipedia.org/wiki/Large_language_model
Fetching page: "Retrieval-augmented generation"
Information Source: https://en.wikipedia.org/wiki/Retrieval-augmented_generation
Fetching page: "Gemini (chatbot)"
Information Source: https://en.wikipedia.org/wiki/Gemini_(chatbot)
Information Sources:
     https://en.wikipedia.org/wiki/Large_language_model
     https://en.wikipedia.org/wiki/Retrieval-augmented_generation
     https://en.wikipedia.org/wiki/Gemini_(chatbot)

Here is what the search results look like:

[10]

Pass the tools to the model

If you pass a list of functions to the GenerativeModel's tools argument, it will extract a schema from the function's signature and type hints, and then pass schema along to the API calls. In response the model may return a FunctionCall object asking to call the function.

Note: This approach only handles annotations of AllowedTypes = int | float | str | dict | list['AllowedTypes']

The request to the Gemini model will keep a reference to the function inself, so that it can execute the function locally later.

Generate supporting search queries

In order to have multiple supporting search queries to the user's original query, you will ask the model to generate more such queries. This would help the engine to cover the asked question on comprehensive levels.

[16]

In order to yield creative and a more random variety of questions, you will set the model's temperature parameter to a value higher. Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will produce responses that are more varied and creative, while a value closer to 0.0 will typically result in more straightforward responses from the model.

Enable automatic function calling and call the API

Now start a new chat with enable_automatic_function_calling=True. With it enabled, the genai.ChatSession will handle the back and forth required to call the function, and return the final response:

[15]
[18]
Searching for "Deep-sea life survival strategies"
Related search terms: ['Sea of Thieves', 'Thalassophobia', 'Whalefall (novel)']
Fetching page: "Sea of Thieves"
Information Source: https://en.wikipedia.org/wiki/Sea_of_Thieves
Fetching page: "Thalassophobia"
Information Source: https://en.wikipedia.org/wiki/Thalassophobia
Fetching page: "Whalefall (novel)"
Information Source: https://en.wikipedia.org/wiki/Whalefall_(novel)
Searching for "Adaptations of deep-sea organisms"
Related search terms: ['Deep-sea fish', 'Deep sea', 'Deep-sea gigantism']
Fetching page: "Deep-sea fish"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_fish
Fetching page: "Deep sea"
Information Source: https://en.wikipedia.org/wiki/Deep_sea
Fetching page: "Deep-sea gigantism"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_gigantism
Searching for "How do deep-sea creatures survive extreme pressure?"
Related search terms: ['Deep-sea community', 'Deep sea', 'Deep-sea fish']
Fetching page: "Deep-sea community"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_community
Searching for "Food sources in the deep sea"
Related search terms: ['Deep-sea fish', 'Deep-sea community', 'Deep sea']
Searching for "Chemosynthesis deep sea"
Related search terms: ['Deep-sea community', 'Deep sea', 'Hydrothermal vent']
Fetching page: "Hydrothermal vent"
Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent
Searching for "Hydrothermal vents deep sea life"
Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Deep sea']
Searching for "Marine snow deep sea"
Related search terms: ['Marine snow', 'Deep sea', 'Deep-sea gigantism']
Fetching page: "Marine snow"
Information Source: https://en.wikipedia.org/wiki/Marine_snow
Searching for "Bioluminescence deep sea life"
Related search terms: ['Deep sea', 'Deep-sea fish', 'Life That Glows']
Fetching page: "Life That Glows"
Information Source: https://en.wikipedia.org/wiki/Life_That_Glows
Searching for "Deep-sea fish adaptations"
Related search terms: ['Deep-sea fish', 'Deep sea', 'Deep-sea community']
Searching for "Deep-sea environment conditions"
Related search terms: ['Deep-sea gigantism', 'Deep sea', 'Deep-sea fish']
Searching for "What do deep-sea animals eat?"
Related search terms: ['Deep-sea community', 'Deep-sea fish', 'Sea urchin']
Fetching page: "Sea urchin"
Information Source: https://en.wikipedia.org/wiki/Sea_urchin
Searching for "Deep-sea extremophiles"
Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Oceanic trench']
Fetching page: "Oceanic trench"
Information Source: https://en.wikipedia.org/wiki/Oceanic_trench
Information Sources:
     https://en.wikipedia.org/wiki/Sea_of_Thieves
     https://en.wikipedia.org/wiki/Thalassophobia
     https://en.wikipedia.org/wiki/Whalefall_(novel)
     https://en.wikipedia.org/wiki/Deep-sea_fish
     https://en.wikipedia.org/wiki/Deep_sea
     https://en.wikipedia.org/wiki/Deep-sea_gigantism
     https://en.wikipedia.org/wiki/Deep-sea_community
     https://en.wikipedia.org/wiki/Hydrothermal_vent
     https://en.wikipedia.org/wiki/Marine_snow
     https://en.wikipedia.org/wiki/Life_That_Glows
     https://en.wikipedia.org/wiki/Sea_urchin
     https://en.wikipedia.org/wiki/Oceanic_trench
[19]
Warning: there are non-text parts in the response: ['thought_signature'], returning concatenated text result from text parts. Check the full candidates.content.parts accessor to get the full model response.

That looks like it worked. You can go through the chat history to see the details of what was sent and received in the function calls:

[28]
user -> {
  "text": "You have access to the Wikipedia API which you will be using\nto answer a user's query. Your job is to generate a list of search queries which\nmight answer a user's question. Be creative by using various key-phrases from\nthe user's query. To generate variety of queries, ask questions which are\nrelated to  the user's query that might help to find the answer. The more\nqueries you generate the better are the odds of you finding the correct answer.\nHere is an example:\n\nuser: Tell me about Cricket World cup 2023 winners.\n\nfunction_call: wikipedia_search(['What is the name of the team that\nwon the Cricket World Cup 2023?', 'Who was the captain of the Cricket World Cup\n2023 winning team?', 'Which country hosted the Cricket World Cup 2023?', 'What\nwas the venue of the Cricket World Cup 2023 final match?', 'Cricket World cup 2023',\n'Who lifted the Cricket World Cup 2023 trophy?'])\n\nThe search function will return a list of article summaries, use these to\nanswer the  user's question.\n\nHere is the user's query: Explain how deep-sea life survives.\n"
}
------------------------------------------------------------
model -> {
  "thought_signature": "CoIJAVSoXO7fBR_lSxtkrTPzNSYCxfZDP5VTvmZjXzFeZaYBWG2jVGLKvU0nkurOCUuBN4xh5HSf0Im3XE617RaHrHeT-_B8B7P4TCVgm9ur2hz9TiI48GMhAzc1TDUUHy2wq6znFCihVFNSXofh95kWR1mJSNnyF0U6Wfew07t98GuN_ZcpG7p4EoGKGIjQMR4KrH5E9gFWVXQO_811Y5zfcTnl1AIENT5PAsxQ4mYYOhxxdw7dsLZGnyPggFUgHHyKcBOXRJzNr4zCes19lDUeAiI_WgpYLag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DIZJkm5Shj8wHBApuQhy_5Yks_ut79dB191hGaXEPGXoPH4MnGrj3WCx8VWRurFcc6Vxev-y2Xu-GDneQ2PacGoR8_I0Ej1PB6x7IPCQjXaq52ma4YTbfssh7EiVRyhwrv_WLAM_5YANiKZoOQ9nQFkmWwAggqcc=",
  "function_call": {
    "args": {
      "search_queries": [
        "Deep-sea life survival strategies",
        "Adaptations of deep-sea organisms",
        "How do deep-sea creatures survive extreme pressure?",
        "Food sources in the deep sea",
        "Chemosynthesis deep sea",
        "Hydrothermal vents deep sea life",
        "Marine snow deep sea",
        "Bioluminescence deep sea life",
        "Deep-sea fish adaptations",
        "Deep-sea environment conditions",
        "What do deep-sea animals eat?",
        "Deep-sea extremophiles"
      ]
    },
    "name": "wikipedia_search"
  }
}
------------------------------------------------------------
user -> {
  "function_response": {
    "name": "wikipedia_search",
    "response": {
      "result": [
        "The provided text is about the video game \"Sea of Thieves\" and does not contain any information about deep-sea life survival strategies.\n\nBased on:\n  https://en.wikipedia.org/wiki/Sea_of_Thieves",
        "The provided source text focuses exclusively on \"Thalassophobia,\" which is the fear of deep bodies of water. It discusses the definition, causes, symptoms, diagnosis, and treatment of this phobia.\n\nThe text **does not contain any information** about \"Deep-sea life survival strategies.\" It only mentions \"aquatic animals\" and \"sea creatures\" in the context of things that people with thalassophobia might fear or that could trigger their fear.\n\nBased on:\n  https://en.wikipedia.org/wiki/Thalassophobia",
        "Based on the provided source, there is no information about \"Deep-sea life survival strategies.\" The text is a summary of the novel \"Whalefall\" and focuses on the plot, characters, and reception of the book, which involves a human character's survival inside a whale, not the survival strategies of deep-sea life.\n\nBased on:\n  https://en.wikipedia.org/wiki/Whalefall_(novel)",
        "The following information describes adaptations of deep-sea organisms:\n\n*   Deep-sea organisms rely heavily on marine snow as an energy source.\n*   Deep-sea organisms have the same pressure within their bodies as is exerted on them from the outside, so they are not crushed by the extreme pressure.\n*   Their high internal pressure results in the reduced fluidity of their membranes because molecules are squeezed together; organisms have adapted to this circumstance by increasing the proportion of unsaturated fatty acids in the lipids of the cell membranes.\n*   Their metabolic processes must ultimately decrease the volume of the organism to some degree.\n*   Deep-sea organisms contain gas-filled spaces (vacuoles), which means they can blow up if they come to the surface due to gas expansion.\n*   Many deep-sea fish are blind and rely on their other senses, such as sensitivities to changes in local pressure and smell, to catch their food and avoid being caught.\n*   Those that aren't blind have large and sensitive eyes that can use bioluminescent light, being as much as 100 times more sensitive to light than human eyes.\n*   Some deep-sea fish have several Rhodopsin (Rh1) genes (e.g., silver spinyfin has 38), which may help them see in the depths of the ocean.\n*   Many species are dark to blend in with their environment and avoid predation.\n*   Many deep-sea fish are bioluminescent, with extremely large eyes adapted to the dark.\n*   Bioluminescence is used to search for food and attract prey (e.g., anglerfish), claim territory through patrol, communicate and find a mate, and distract or temporarily blind predators to escape.\n*   Some organisms camouflage themselves from predators below them by illuminating their bellies (counter-illumination) to match the colour and intensity of light from above so that no shadow is cast in the mesopelagic zone.\n*   Deep-sea fishes usually do not have swim bladders because of the high pressure of their environment.\n*   Instead, they exhibit structures similar to hydrofoils in order to provide hydrodynamic lift.\n*   The deeper a fish lives, the more jelly-like its flesh and the more minimal its bone structure.\n*   They reduce their tissue density through high fat content, reduction of skeletal weight (through reductions of size, thickness and mineral content), and water accumulation.\n*   The body shapes of deep-sea fish are generally better adapted for periodic bursts of swimming rather than constant swimming.\n*   Some have long feelers to help them locate prey or attract mates in the pitch black of the deep ocean.\n*   The deep-sea angler fish has a long fishing-rod-like adaptation protruding from its face, on the end of which is a bioluminescent piece of skin that wriggles like a worm to lure its prey.\n*   To consume other fish that are the same size or larger, they have great sharp teeth, hinged jaws, disproportionately large mouths, and expandable bodies (e.g., gulper eel).\n*   Ray finned species with spiny fins are rare, suggesting deep-sea fish are ancient and well adapted, making invasions by more modern fishes unsuccessful.\n*   Most mesopelagic fish make daily vertical migrations, moving at night into the epipelagic zone to feed and returning to the depths for safety during the day, often following zooplankton.\n*   Vertical migrations are undertaken with the assistance of a swim bladder, which is inflated to move up and deflated to return to depths, adjusting to pressure changes.\n*   Some mesopelagic fishes make daily migrations through the thermocline, displaying considerable tolerances for temperature change.\n*   Mesopelagic fish have muscular bodies, ossified bones, scales, well developed gills and central nervous systems, and large hearts and kidneys.\n*   Mesopelagic plankton feeders have small mouths with fine gill rakers, while piscivores have larger mouths and coarser gill rakers.\n*   Most mesopelagic fish are visual predators with large eyes.\n*   Some deeper water fish have tubular eyes with big lenses and only rod cells that look upwards, providing binocular vision and great sensitivity to small light signals, allowing them to pick out prey silhouetted against the gloom above.\n*   Mesopelagic fish usually lack defensive spines, and use colour to camouflage themselves: ambush predators are dark, black or red (red functions as black due to light absorption).\n*   Migratory forms use countershaded silvery colours.\n*   On their bellies, they often display photophores producing low grade light for counter-illumination.\n*   Some predators have yellow lenses that filter ambient light, leaving bioluminescence visible.\n*   The brownsnout spookfish employs a mirror, not a lens, to focus an image in its eyes.\n*   Bathypelagic fish have slow metabolisms and unspecialized diets, preferring to sit and wait for food.\n*   Their bodies are elongated with weak, watery muscles and skeletal structures, allowing them to not be compressed by great pressures.\n*   They often have extensible, hinged jaws with recurved teeth.\n*   They are slimy, without scales.\n*   The central nervous system is confined to the lateral line and olfactory systems; eyes are small and may not function; gills, kidneys, hearts, and swim bladders are small or missing. These features (acquired through neoteny) allow them to remain suspended in water with little energy expenditure.\n*   The swim bladders of bathypelagic fish are either absent or scarcely operational, and they do not normally undertake vertical migrations.\n*   Some deep-sea fishes have swim bladders that function when young in the upper epipelagic zone, but they wither or fill with fat as the fish move to adult habitat.\n*   Cusk-eel and rough abyssal grenadier, found at great depths, still have functional swim bladders, allowing them to maintain high bone density and strong jaws.\n*   Their most important sensory systems are usually the inner ear (responds to sound) and the lateral line (responds to changes in water pressure); the olfactory system can also be important for males finding females by smell.\n*   Bathypelagic fish are black, or sometimes red, with few photophores, used to entice prey or attract a mate.\n*   They are not selective in feeding, grabbing whatever comes close, accomplished by having a large mouth with sharp teeth for grabbing large prey and overlapping gill rakers to prevent small prey from escaping.\n*   For finding a mate, some species depend on bioluminescence with unique patterns; others are hermaphrodites.\n*   Female anglerfish release pheromones to attract tiny males; when a male finds her, he bites on to her and never lets go, fusing their circulatory systems and atrophying into gonads, ensuring a mate is immediately available for spawning.\n*   Deep-sea organisms possess adaptations at cellular and physiological levels to survive in environments of great pressure.\n*   Species have evolved changes in their protein structure and reaction criteria to withstand pressure.\n*   Deep-sea cellular membranes favor phospholipid bilayers with a higher proportion of unsaturated fatty acids, inducing higher fluidity.\n*   Deep-sea species exhibit lower changes of entropy and enthalpy.\n*   Globular proteins of deep-sea fish (e.g., G-actin) are relatively rigid compared to surface fish.\n*   Proteins in deep-sea fish are structurally strengthened by modification of bonds in the tertiary structure, which also induces high levels of thermal stability.\n*   Na+/K+ -ATPases of deep-sea fishes exhibit a much higher tolerance of hydrostatic pressure compared to shallow-water counterparts, due to adaptations in the protein and lipid moieties.\n*   Ten orders, thirteen families and about 200 known species of deep-sea fish have evolved a gelatinous layer below the skin or around the spine, used for buoyancy, low-cost growth and to increase swimming efficiency by reducing drag.\n\nBased on:\n  https://en.wikipedia.org/wiki/Deep-sea_fish",
        "Organisms living within the deep sea have a variety of adaptations to survive in these conditions.\nOrganisms can survive in the deep sea through a number of feeding methods including scavenging, predation and filtration, with a number of organisms surviving by feeding on marine snow.\nInstead of relying on gas for their buoyancy, many deep-sea species have jelly-like flesh consisting mostly of glycosaminoglycans, which provides them with very low density.\nIt is also common among deep water squid to combine the gelatinous tissue with a flotation chamber filled with a coelomic fluid made up of the metabolic waste product ammonium chloride, which is lighter than the surrounding water.\nThe midwater fish have special adaptations to cope with these conditions\u2014they are small, usually being under 25 centimetres (10 in); they have slow metabolisms and unspecialized diets, preferring to sit and wait for food rather than waste energy searching for it.\nThey have elongated bodies with weak, watery muscles and skeletal structures.\nThey often have extendable, hinged jaws with recurved teeth.\nBecause of the sparse distribution and lack of light, finding a partner with which to breed is difficult, and many organisms are hermaphroditic.\nBecause light is so scarce, fish often have larger than normal, tubular eyes with only rod cells.\nTheir upward field of vision allows them to seek out the silhouette of possible prey.\nPrey fish however also have adaptations to cope with predation. These adaptations are mainly concerned with reduction of silhouettes, a form of camouflage.\nThe two main methods by which this is achieved are reduction in the area of their shadow by lateral compression of the body, and counter illumination via bioluminescence.\nThis is achieved by production of light from ventral photophores, which tend to produce such light intensity to render the underside of the fish of similar appearance to the background light.\nFor more sensitive vision in low light, some fish have a retroreflector behind the retina.\nFlashlight fish have this plus photophores, which combination they use to detect eyeshine in other fish.\nThere are many scavengers that feed primarily or entirely upon large food falls.\nThere are a number of filter feeders that feed upon organic particles using tentacles, such as Freyella elegans.\nOne example is the symbiotic relationship between the tube worm Riftia and chemosynthetic bacteria.\nDeep-sea fish have different adaptations in their proteins, anatomical structures, and metabolic systems to survive in the Deep sea, where the inhabitants have to withstand great amount of hydrostatic pressure.\nDeep sea species must undergo physiological and structural adaptations to preserve protein functionality against pressure.\nSome Deep-sea fish developed pressure tolerance through the change in mechanism of their \u03b1-actin.\nIn some species that live in depths greater than 5 km (3.1 mi), C.armatus and C.yaquinae have specific substitutions on the active sites of \u03b1-Actin, which serves as the main component of muscle fiber.\nThese specific substitutions, Q137K and V54A from C.armatus or I67P from C.yaquinae are predicted to have importance in pressure tolerance.\nSubstitution in the active sites of actin result in significant changes in the salt bridge patterns of the protein, which allows for better stabilization in ATP binding and sub unit arrangement.\nIt was found that deep sea fish have more salt bridges in their actins compared to fish inhabiting the upper zones of the sea.\nFor certain chondrichthyans, it was found that Trimethylamine N-oxide (TMAO) increased with depth, replacing other osmolytes and urea.\nDue to the ability of TMAO being able to protect proteins from high hydrostatic pressure destabilizing proteins, the osmolyte adjustment serves are an important adaptation for deep sea fish to withstand high hydrostatic pressure.\nDeep-sea organisms possess molecular adaptations to survive and thrive in the deep oceans.\nMariana hadal snailfish developed modification in the Osteocalcin(burlap) gene, where premature termination of the gene was found.\nThe frameshift mutation seems to have resulted in the open skull and cartilage-based bone formation in Mariana hadal snailfish.\n\nBased on:\n  https://en.wikipedia.org/wiki/Deep_sea",
        "Adaptations of deep-sea organisms mentioned in the source include:\n\n*   **Deep-sea gigantism:** The tendency for species of deep-sea dwelling animals to be larger than their shallower-water relatives. This is considered a necessary adaptation to colder temperature, food scarcity, reduced predation pressure, and increased dissolved oxygen concentrations.\n*   **Response to lower temperature:** Decreasing temperature is thought to result in increased cell size and increased life span (associated with delayed sexual maturity), both leading to an increase in maximum body size. Continued growth throughout life is characteristic of crustaceans in this environment.\n*   **Response to food scarcity:** Larger body size can improve ability to forage for widely scattered resources. Larger offspring, with greater initial stored food reserves, can drift for greater distances. Giant isopods gorge on food when available, distending their bodies, and can also survive 5 years without food in captivity. A larger animal's metabolism becomes more efficient, which provides benefit under conditions of limited food supply.\n*   **Response to reduced predation pressure:** Reduced predation pressure in deeper waters is a possible influence on adaptations.\n*   **Response to increased dissolved oxygen:** Deep-sea gigantism could be an adaptive trait to combat asphyxiation in frigid, dense ocean waters. Larger organisms are able to intake more dissolved oxygen within the ocean, allowing for sufficient respiration.\n\nBased on:\n  https://en.wikipedia.org/wiki/Deep-sea_gigantism",
        "From the \"Hyperbaricity\" section:\n*   \"These animals have evolved to survive the extreme pressure of the sub-photic zones.\"\n*   \"To cope with the pressure, many fish are rather small, usually not exceeding 25 cm in length.\"\n*   \"Scientists have discovered that the deeper these creatures live, the more gelatinous their flesh and more minimal their skeletal structure.\"\n*   \"These creatures have also eliminated all excess cavities that would collapse under the pressure, such as swim bladders.\"\n\nFrom the \"Bathyal\" section:\n*   \"The fish that do live there [bathyal zone] may have reduced or completely lost their gills, kidneys, hearts, and swimbladders, have slimy instead of scaly skin, and have a weak skeletal and muscular build.\"\n*   \"This lack of ossification is an adaptation to save energy when food is scarce.\"\n\nBased on:\n  https://en.wikipedia.org/wiki/Deep-sea_community",
        "Here's the extracted information about \"Chemosynthesis deep sea\":\n\n*   Relative to the majority of the deep sea, the areas around hydrothermal vents are biologically more productive, often hosting complex communities fueled by the chemicals dissolved in the vent fluids.\n*   Chemosynthetic bacteria and archaea found around hydrothermal vents form the base of the food chain, supporting diverse organisms including giant tube worms, clams, limpets, and shrimp.\n*   Life has traditionally been seen as driven by energy from the sun, but deep-sea organisms have no access to sunlight, so biological communities around hydrothermal vents must depend on nutrients found in the dusty chemical deposits and hydrothermal fluids in which they live.\n*   Previously, benthic oceanographers assumed that vent organisms were dependent on marine snow, as deep-sea organisms are.\n*   Some hydrothermal vent organisms do consume this \"rain\", but with only such a system, life forms would be sparse.\n*   Compared to the surrounding sea floor, however, hydrothermal vent zones have a density of organisms 10,000 to 100,000 times greater.\n*   The hydrothermal vents are recognized as a type of chemosynthetic based ecosystems (CBE) where primary productivity is fuelled by chemical compounds as energy sources instead of light (chemoautotrophy).\n*   Hydrothermal vent communities are able to sustain such vast amounts of life because vent organisms depend on chemosynthetic bacteria for food.\n*   The water from the hydrothermal vent is rich in dissolved minerals and supports a large population of chemoautotrophic bacteria.\n*   These bacteria use sulfur compounds, particularly hydrogen sulfide, a chemical highly toxic to most known organisms, to produce organic material through the process of chemosynthesis.\n*   The ecosystem so formed is reliant upon the continued existence of the hydrothermal vent field as the primary source of energy, which differs from most surface life on Earth, which is based on solar energy.\n*   However, although it is often said that these communities exist independently of the sun, some of the organisms are actually dependent upon oxygen produced by photosynthetic organisms, while others are anaerobic.\n*   The chemosynthetic bacteria grow into a thick mat which attracts other organisms, such as amphipods and copepods, which graze upon the bacteria directly.\n*   Larger organisms, such as snails, shrimp, crabs, tube worms, fish (especially eelpout, cutthroat eel, Ophidiiformes and Symphurus thermophilus), and octopuses (notably Vulcanoctopus hydrothermalis), form a food chain of predator and prey relationships above the primary consumers.\n*   Sunlight is nonexistent, so many organisms, such as archaea and extremophiles, convert the heat, methane, and sulfur compounds provided by black smokers into energy through a process called chemosynthesis.\n*   More complex life forms, such as clams and tubeworms, feed on these organisms.\n*   The organisms at the base of the food chain also deposit minerals into the base of the black smoker, therefore completing the life cycle.\n*   Hydrothermal vent ecosystems have enormous biomass and productivity, but this rests on the symbiotic relationships that have evolved at vents.\n*   Deep-sea hydrothermal vent ecosystems differ from their shallow-water and terrestrial hydrothermal counterparts due to the symbiosis that occurs between macroinvertebrate hosts and chemoautotrophic microbial symbionts in the former.\n*   Since sunlight does not reach deep-sea hydrothermal vents, organisms in deep-sea hydrothermal vents cannot obtain energy from the sun to perform photosynthesis.\n*   Instead, the microbial life found at hydrothermal vents is chemosynthetic; they fix carbon by using energy from chemicals such as sulfide, as opposed to light energy from the sun.\n*   In other words, the symbiont converts inorganic molecules (H2S, CO2, O) to organic molecules that the host then uses as nutrition.\n*   What was discovered was the ubiquitous symbiosis of chemoautotrophs living in (endosymbiosis) the vent animals' gills; the reason why multicellular life is capable to survive the toxicity of vent systems.\n*   In the early stages of studying life at hydrothermal vents, there were differing theories regarding the mechanisms by which multicellular organisms were able to acquire nutrients from these environments, and how they were able to survive in such extreme conditions.\n*   In 1977, it was hypothesized that the chemoautotrophic bacteria at hydrothermal vents might be responsible for contributing to the diet of suspension-feeding bivalves.\n*   Finally, in 1981, it was understood that giant tubeworm nutrition acquisition occurred as a result of chemoautotrophic bacterial endosymbionts.\n*   As scientists continued to study life at hydrothermal vents, it was understood that symbiotic relationships between chemoautotrophs and macrofauna invertebrate species was ubiquitous.\n*   For instance, in 1983, clam gill tissue was confirmed to contain bacterial endosymbionts; in 1984 vent bathymodiolid mussels and vesicomyid clams were also found to carry endosymbionts.\n*   Tubeworms have no mouth and no gut, but they do have a \"trophosome\", which is where they deal with nutrition and where their endosymbionts are found.\n*   They also have a bright red plume, which they use to uptake compounds such as O, H2S, and CO2, which feed the endosymbionts in their trophosome.\n*   In 1988, research confirmed thiotrophic (sulfide-oxidizing) bacteria in Alviniconcha hessleri, a large vent mollusk.\n*   Furthermore, while some symbionts reduce sulfur compounds, others are known as \"methanotrophs\" and reduce carbon compounds, namely methane.\n*   While chemosynthesis occurring at the deep ocean allows organisms to live without sunlight in the immediate sense, they technically still rely on the sun for survival, since oxygen in the ocean is a byproduct of photosynthesis.\n*   However, if the sun were to suddenly disappear and photosynthesis ceased to occur on our planet, life at the deep-sea hydrothermal vents could continue for millennia (until the oxygen was depleted).\n*   Chemosynthetic ecosystems surrounding the Gal\u00e1pagos Rift submarine hydrothermal vents were first directly observed in 1977.\n*   Conservation of hydrothermal vent ecosystems after the fact of mining of an active system would depend on the recolonization of chemosynthetic bacteria, and therefore the continuation of the hydrothermal vent fluid as it is the main hydrothermal energy source.\n*   Hydrogen sulfide chemosynthesis - system of generating energy used in hydrothermal vents (from \"See also\" section).\n\nBased on:\n  https://en.wikipedia.org/wiki/Hydrothermal_vent",
        "Here is the relevant information about marine snow in the deep sea:\n\n*   In the deep ocean, marine snow is a continuous shower of mostly organic detritus falling from the upper layers of the water column.\n*   It is a significant means of exporting energy from the light-rich photic zone to the aphotic zone below, which is referred to as the biological pump.\n*   Export production is the amount of organic matter produced in the ocean by primary production that is not recycled (remineralised) before it sinks into the aphotic zone.\n*   Marine snow can be an important food source for organisms living in the aphotic zone, particularly for organisms that live very deep in the water column.\n*   Most organic components of marine snow are consumed by microbes, zooplankton and other filter-feeding animals within the first 1,000 metres of their journey.\n*   Marine snow may be considered the foundation of deep-sea mesopelagic and benthic ecosystems: As sunlight cannot reach them, deep-sea organisms rely heavily on marine snow as an energy source.\n*   The small percentage of material not consumed in shallower waters becomes incorporated into the muddy \"ooze\" blanketing the ocean floor, where it is further decomposed through biological activity.\n*   As the aggregates slowly sink to the bottom of the ocean, the many microorganisms residing on them are constantly respiring and contribute greatly to the microbial loop.\n*   Aggregates that sink more quickly to the bottom of the ocean have a greater chance of exporting carbon to the deep sea floor.\n*   Carbon export to the deep ocean in regions with high dust deposition is strongly controlled by dust input to the surface ocean while suspended dust particles in deeper water layers do not significantly interact with sinking aggregates.\n*   The particulate organic carbon formed in the euphotic zone is processed by marine microorganisms (microbes), zooplankton and their consumers into organic aggregates (marine snow), which is then exported to the mesopelagic (200\u20131000 m depth) and bathypelagic zones by sinking and vertical migration by zooplankton and fish.\n*   Sequestration flux is the sedimentation out of the mesopelagic zone (at approximately 1000 m depth).\n*   A portion of the particulate organic carbon is respired back to CO2 in the oceanic water column at depth, mostly by heterotrophic microbes and zooplankton, thus maintaining a vertical gradient in concentration of dissolved inorganic carbon (DIC).\n*   This deep-ocean DIC returns to the atmosphere on millennial timescales through thermohaline circulation.\n*   Only about 1% of the surface production reaches the sea floor.\n*   Marine snow aggregates collected from the bathypelagic zone were found to consist largely of fungi and labyrinthulomycetes.\n*   Smaller aggregates do not harbor as many eukaryotic organisms which is similar to what is found in the deep ocean.\n*   The bathypelagic aggregates mostly resembled those found in the surface ocean.\n*   It implies higher rates of remineralization in the bathypelagic zone.\n*   Remineralization occurs typically below 200 m depth.\n*   The dark ocean harbors around 65% of all pelagic Bacteria and Archaea.\n*   The deep ocean harbors more than 98% of the dissolved inorganic carbon pool, along with a rapid sedimentation rate that results in low particulate organic carbon inputs.\n*   There is a mismatch from the microbial carbon demand in the deep ocean and the carbon export from the surface ocean.\n*   Because of the relatively long residence time of the ocean's thermohaline circulation, carbon transported as marine snow into the deep ocean by the biological pump can remain out of contact with the atmosphere for more than 1000 years.\n*   When the marine snow is finally decomposed to inorganic nutrients and dissolved carbon dioxide, these are effectively isolated from the surface ocean for relatively long time scales related to ocean circulation.\n*   Enhancing the quantity of marine snow that reaches the deep ocean is the basis of several geoengineering schemes to enhance carbon sequestration by the ocean.\n*   Increases in ocean temperatures may result in a decrease in the production of marine snow due to the enhanced stratification of the water column.\n*   Recent research indicates transported bacteria may exchange genes with previously thought to be isolated populations of bacteria inhabiting the breadth of the ocean floor.\n*   In such an immense area there may be as yet undiscovered species tolerant of high pressures and extreme cold, perhaps finding use in bioengineering and pharmacy.\n\nBased on:\n  https://en.wikipedia.org/wiki/Marine_snow",
        "The programme then introduces many luminous deep sea animals, including the vampire squid, the polychaete worm Tomopteris that generates yellow light, the jellyfish Atolla, the comb jelly Beroe, the viper fish, pyrosomes, a dragonfish, and the polychaete worm Flota. Next, the programme discusses specialised adaptations in the eyes of particular animals to see bioluminescence, such as the barreleye fish and the cock-eyed squid.\n\nBased on:\n  https://en.wikipedia.org/wiki/Life_That_Glows",
        "Sea urchins inhabit depth zones from the intertidal zone to deep seas of 5,000 m (16,000 ft), and even to hadal zone depths (6850 metres).\n\nSea urchins feed primarily on algae, but also eat slow-moving or sessile animals such as crinoids and sponges. They are primarily herbivores but can feed on sea cucumbers and a wide range of invertebrates, such as mussels, polychaetes, sponges, brittle stars, and crinoids, making them omnivores, consumers at a range of trophic levels.\n\nBased on:\n  https://en.wikipedia.org/wiki/Sea_urchin",
        "Here's the relevant information about deep-sea extremophiles from the provided source:\n\n*   Much of the fluid trapped in sediments of the subducting slab returns to the surface at the oceanic trench, producing mud volcanoes and cold seeps. These support unique biomes based on chemotrophic microorganisms.\n*   The fluids released at mud volcanoes and cold seeps are rich in methane and hydrogen sulfide, providing chemical energy for chemotrophic microorganisms that form the base of a unique trench biome.\n*   Cold seep communities have been identified in the inner trench slopes of the western Pacific (especially Japan), South America, Barbados, the Mediterranean, Makran, and the Sunda trench. These are found at depths as great as 6,000 meters (20,000 ft).\n*   The genome of the extremophile Deinococcus from Challenger Deep has sequenced for its ecological insights and potential industrial uses.\n*   Because trenches are the lowest points in the ocean floor, there is concern that plastic debris may accumulate in trenches and endanger the fragile trench biomes.\n\nBased on:\n  https://en.wikipedia.org/wiki/Oceanic_trench"
      ]
    }
  }
}
------------------------------------------------------------
model -> {
  "thought_signature": "CpQwAVSoXO6mZ72FvYSu-DZp-MR28zWVKDqT5anfFFdWVXZ-xV5-aUFsiF3_XCyRqK0r52pPzvHpoERv2QC1HDl5klmGJ2JKkdmqvK0vsFrH6O7ps1FAVkh5o9PBVGggpzJj4mN2z2GUF0XhZUTKBKiz0Ko9Lryo7FzCSlhS6gbBI7_ZxgdMRx32GqLapNj132ImizDccZiwjoPwTrADsUNqFrL5NllaEfPpBkghLVOcTN5nBA_txIhOYSlgRDJUpihhUsXe4LOWcR6x16YvIOLE36FK6hLW1ho-xWLqtRkGSYEE-jfTo5PNh8TEVVjnS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KNAzdP_PxPPXgw2SkMwcJ9P1KxGctLOLr64ZdS5GvkoVbsiaSpL-nBdA79sW5BRIRPc9cxoRWKKZEy-M6BdYbM1I3V0q4ap8EfUjXOFUjsPU-clYTXuCszmMX0V2p-ug_z8ZrJvM2SVh9pxEfZrwGknKuGq7TbkBYI1R-CfyZhBdj6uQPlaGDwPgJLfwWD1mRPbA4XDbTz9AbvpOW9TzSxqi6wskXntz5QAp_edJfnfwLDXmQkJtt8PfNDZ228Lk7ldqlZq-OJTQcOy7dUVp2CZf_7RRChhT0JcOUIA1r64AuZe3nqq1cyA=",
  "text": "Deep-sea life has evolved remarkable adaptations to survive the harsh conditions of its environment, characterized by immense pressure, perpetual darkness, extremely cold temperatures, and scarce food resources.\n\nHere's how deep-sea organisms manage to thrive:\n\n1.  **Pressure Adaptations:**\n    *   **Internal Pressure Equalization:** Deep-sea creatures maintain an internal body pressure that is equal to the external hydrostatic pressure, preventing them from being crushed.\n    *   **Flexible Bodies:** Many species have gelatinous, watery flesh with minimal bone structure and reduced tissue density. This allows their bodies to compress without damage.\n    *   **Absence of Gas-Filled Spaces:** Most deep-sea fish lack swim bladders (gas-filled organs used for buoyancy in shallower waters) as these would collapse under pressure. Instead, some use lipid-rich tissues or have hydrofoil-like fins for lift.\n    *   **Molecular Adaptations:** At a cellular level, their proteins and enzymes are specially adapted to function under high pressure, often being more rigid or having modified structures (e.g., increased salt bridges in actin, higher proportion of unsaturated fatty acids in cell membranes to maintain fluidity). Some use osmolytes like Trimethylamine N-oxide (TMAO) to protect proteins.\n\n2.  **Food Acquisition:**\n    *   **Marine Snow:** In the vast majority of the deep sea, the primary food source is \"marine snow\"\u2014a continuous shower of organic detritus (dead organisms, fecal pellets, etc.) falling from the productive upper layers of the ocean. Organisms filter this snow or scavenge larger food falls.\n    *   **Chemosynthesis:** Around hydrothermal vents and cold seeps, life thrives independently of sunlight through chemosynthesis. Specialized bacteria and archaea convert chemical compounds (like hydrogen sulfide and methane) from the Earth's interior into organic matter. These microorganisms form the base of the food web, supporting dense communities of unique organisms, often through symbiotic relationships (e.g., tube worms hosting chemosynthetic bacteria).\n    *   **Efficient Feeding:** Due to food scarcity, many deep-sea fish have slow metabolisms and unspecialized diets, preferring to \"sit and wait\" for prey. They often possess large, hinged, and extensible jaws with sharp, recurved teeth to engulf prey of their own size or larger.\n\n3.  **Light and Sensory Adaptations:**\n    *   **Bioluminescence:** In the absence of sunlight, many deep-sea creatures produce their own light through bioluminescence. This is used for various purposes: attracting prey (like the anglerfish's glowing lure), finding mates, deterring predators (e.g., by startling or counter-illuminating their undersides to blend with faint overhead light), and communication.\n    *   **Enhanced Vision:** While some deep-sea fish are blind, others have exceptionally large, tubular eyes with highly sensitive rod cells that are adapted to detect the faintest flickers of bioluminescence or silhouettes against the dim light from above.\n    *   **Other Senses:** Given the limited utility of sight, deep-sea organisms heavily rely on other senses. They possess highly developed lateral line systems to detect changes in water pressure and vibrations, an acute sense of smell (olfactory system) to locate food or mates, and sensitive inner ears. Many also have long feelers or tentacles to navigate and find prey in the darkness.\n\n4.  **Metabolic and Physical Adaptations:**\n    *   **Slow Metabolism:** To conserve energy in a food-scarce environment, deep-sea organisms generally have very slow metabolisms and often grow slowly and live long lives.\n    *   **Body Shape and Movement:** Their bodies are often elongated with weak, watery muscles and minimal skeletal structures, which allows them to remain suspended in water with little energy expenditure. Their body shapes are generally better suited for periodic bursts of swimming rather than continuous movement.\n    *   **Deep-Sea Gigantism:** Some deep-sea species exhibit gigantism, growing much larger than their shallow-water relatives. This is thought to be an adaptation to colder temperatures, food scarcity (larger size improves foraging ability and metabolic efficiency), and reduced predation pressure.\n\n5.  **Reproduction:**\n    *   Finding a mate in the vast, dark deep sea can be challenging. Adaptations include hermaphroditism (being both male and female) or unique reproductive strategies, such as the parasitic male anglerfish, which permanently attaches to the female, ensuring a mate is always available."
}
------------------------------------------------------------

In the chat history you can see all 4 steps:

  1. The user sent the query.
  2. The model replied with a genai.protos.FunctionCall calling the wikipedia_search with a number of relevant searches.
  3. Because you set enable_automatic_function_calling=True when creating the genai.ChatSession, it executed the search function and returned the list of article summaries to the model.
  4. Folliwing the instructions in the prompt, the model generated a final answer based on those summaries.

[Optional] Manually execute the function call

If you want to understand what happened behind the scenes, this section executes the FunctionCall manually to demonstrate.

[29]
[30]
Searching for "How do deep-sea creatures adapt to high pressure?"
Related search terms: ['Deep sea', 'Deep-sea fish', 'Oceanic zone']
Fetching page: "Deep sea"
Information Source: https://en.wikipedia.org/wiki/Deep_sea
Fetching page: "Deep-sea fish"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_fish
Fetching page: "Oceanic zone"
Information Source: https://en.wikipedia.org/wiki/Oceanic_zone
Searching for "What are the food sources for deep-sea life?"
Related search terms: ['Deep-sea fish', 'Deep-sea wood', 'Deep sea']
Fetching page: "Deep-sea wood"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_wood
Searching for "How do deep-sea organisms survive in the absence of sunlight?"
Related search terms: ['Deep-sea community', 'Hydrothermal vent', 'Abyssal zone']
Fetching page: "Deep-sea community"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_community
Fetching page: "Hydrothermal vent"
Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent
Fetching page: "Abyssal zone"
Information Source: https://en.wikipedia.org/wiki/Abyssal_zone
Searching for "What are the unique adaptations of deep-sea animals?"
Related search terms: ['Deep sea', 'Deep-sea community', 'Deep-sea fish']
Searching for "Deep-sea hydrothermal vents and life"
Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Hydrothermal vent microbial communities']
Fetching page: "Hydrothermal vent microbial communities"
Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities
Searching for "Deep-sea chemosynthesis"
Related search terms: ['Deep-sea community', 'Deep sea', 'Hydrothermal vent']
Searching for "Bioluminescence in deep-sea creatures"
Related search terms: ['Deep-sea community', 'Deep sea', 'Deep-sea fish']
Searching for "Deep-sea extremophiles survival mechanisms"
Related search terms: ['Hydrothermal vent', 'Extremophile', 'Deep-sea community']
Fetching page: "Extremophile"
Information Source: https://en.wikipedia.org/wiki/Extremophile
Searching for "How do deep-sea fish regulate buoyancy?"
Related search terms: ['Deep sea', 'Deep sea mining', 'Neutral buoyancy']
Fetching page: "Deep sea mining"
Information Source: https://en.wikipedia.org/wiki/Deep_sea_mining
Fetching page: "Neutral buoyancy"
Information Source: https://en.wikipedia.org/wiki/Neutral_buoyancy
Searching for "What is marine snow and its role in deep-sea ecosystems?"
Related search terms: ['Deep-sea community', 'Deep-sea fish', 'Deep sea']
Information Sources:
     https://en.wikipedia.org/wiki/Deep_sea
     https://en.wikipedia.org/wiki/Deep-sea_fish
     https://en.wikipedia.org/wiki/Oceanic_zone
     https://en.wikipedia.org/wiki/Deep-sea_wood
     https://en.wikipedia.org/wiki/Deep-sea_community
     https://en.wikipedia.org/wiki/Hydrothermal_vent
     https://en.wikipedia.org/wiki/Abyssal_zone
     https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities
     https://en.wikipedia.org/wiki/Extremophile
     https://en.wikipedia.org/wiki/Deep_sea_mining
     https://en.wikipedia.org/wiki/Neutral_buoyancy

Initially the model returns a FunctionCall:

[59]
{
  "args": {
    "search_queries": [
      "How do deep-sea creatures adapt to high pressure?",
      "What are the food sources for deep-sea life?",
      "How do deep-sea organisms survive in the absence of sunlight?",
      "What are the unique adaptations of deep-sea animals?",
      "Deep-sea hydrothermal vents and life",
      "Deep-sea chemosynthesis",
      "Bioluminescence in deep-sea creatures",
      "Deep-sea extremophiles survival mechanisms",
      "How do deep-sea fish regulate buoyancy?",
      "What is marine snow and its role in deep-sea ecosystems?"
    ]
  },
  "name": "wikipedia_search"
}
[62]
'wikipedia_search'

Call the function with generated arguments to get the results.

[63]
Searching for "How do deep-sea creatures adapt to high pressure?"
Related search terms: ['Deep sea', 'Deep-sea fish', 'Oceanic zone']
Fetching page: "Deep sea"
Information Source: https://en.wikipedia.org/wiki/Deep_sea
Fetching page: "Deep-sea fish"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_fish
Fetching page: "Oceanic zone"
Information Source: https://en.wikipedia.org/wiki/Oceanic_zone
Searching for "What are the food sources for deep-sea life?"
Related search terms: ['Deep-sea fish', 'Deep-sea wood', 'Deep sea']
Fetching page: "Deep-sea wood"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_wood
Searching for "How do deep-sea organisms survive in the absence of sunlight?"
Related search terms: ['Deep-sea community', 'Hydrothermal vent', 'Abyssal zone']
Fetching page: "Deep-sea community"
Information Source: https://en.wikipedia.org/wiki/Deep-sea_community
Fetching page: "Hydrothermal vent"
Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent
Fetching page: "Abyssal zone"
Information Source: https://en.wikipedia.org/wiki/Abyssal_zone
Searching for "What are the unique adaptations of deep-sea animals?"
Related search terms: ['Deep sea', 'Deep-sea community', 'Deep-sea fish']
Searching for "Deep-sea hydrothermal vents and life"
Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Hydrothermal vent microbial communities']
Fetching page: "Hydrothermal vent microbial communities"
Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities
Searching for "Deep-sea chemosynthesis"
Related search terms: ['Deep-sea community', 'Deep sea', 'Hydrothermal vent']
Searching for "Bioluminescence in deep-sea creatures"
Related search terms: ['Deep-sea community', 'Deep sea', 'Deep-sea fish']
Searching for "Deep-sea extremophiles survival mechanisms"
Related search terms: ['Hydrothermal vent', 'Extremophile', 'Deep-sea community']
Fetching page: "Extremophile"
Information Source: https://en.wikipedia.org/wiki/Extremophile
Searching for "How do deep-sea fish regulate buoyancy?"
Related search terms: ['Deep sea', 'Deep sea mining', 'Neutral buoyancy']
Fetching page: "Deep sea mining"
Information Source: https://en.wikipedia.org/wiki/Deep_sea_mining
Fetching page: "Neutral buoyancy"
Information Source: https://en.wikipedia.org/wiki/Neutral_buoyancy
Searching for "What is marine snow and its role in deep-sea ecosystems?"
Related search terms: ['Deep-sea community', 'Deep-sea fish', 'Deep sea']
Information Sources:
     https://en.wikipedia.org/wiki/Deep_sea
     https://en.wikipedia.org/wiki/Deep-sea_fish
     https://en.wikipedia.org/wiki/Oceanic_zone
     https://en.wikipedia.org/wiki/Deep-sea_wood
     https://en.wikipedia.org/wiki/Deep-sea_community
     https://en.wikipedia.org/wiki/Hydrothermal_vent
     https://en.wikipedia.org/wiki/Abyssal_zone
     https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities
     https://en.wikipedia.org/wiki/Extremophile
     https://en.wikipedia.org/wiki/Deep_sea_mining
     https://en.wikipedia.org/wiki/Neutral_buoyancy

Now send the FunctionResult to the model.

[65]
Warning: there are non-text parts in the response: ['thought_signature'], returning concatenated text result from text parts. Check the full candidates.content.parts accessor to get the full model response.

Re-ranking the search results

Helper function to embed the content:

[69]
EMBEDDINGS_MODEL_ID

Please refer to the embeddings guide for more information on embeddings.

Your next step is to define functions that you can use to calculate similarity scores between two embedding vectors. These scores will help you decide which embedding vector is the most relevant vector to the user's query.

You will now implement cosine similarity as your metric. Here returned embedding vectors will be of unit length and hence their L1 norm (np.linalg.norm()) will be ~1. Hence, calculating cosine similarity is esentially same as calculating their dot product score.

[76]

Similarity with user's query

Now it's time to find the most relevant search result returned by the Wikipedia API.

Use Gemini API to get embeddings for user's query and search results.

[70]

Calculate similarity score:

[77]

using np.argmax best candidate is selected.

Users's Input: Explain how deep-sea life survives.

Answer:

[79]

Similarity with Hypothetical Document Embeddings (HyDE)

Drawing inspiration from Gao et al the objective here is to generate a template answer to the user's query using gemini-2.5-flash's internal knowledge. This hypothetical answer will serve as a baseline to calculate relevance of all the search results.

[81]

Use Gemini API to get embeddings for the baseline answer and compare them with search results

[82]

Calculate similarity scores to rank the search results

[83]
[84]
0.8530243497361725

using np.argmax best candidate is selected.

Users's Input: Explain how deep-sea life survives.

Answer:

[85]

You have now created a search re-ranking engine using embeddings!

Next steps

I hope you found this example helpful! Check out more examples in the Gemini API cookbook to learn more.