Search re-ranking using Gemini embeddings

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.
Note

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

Install the Google GenAI SDK

Install the Google GenAI SDK from npm.

$ npm install @google/genai

Setup your API key

You can create your API key using Google AI Studio with a single click.

Remember to treat your API key like a password. Don’t accidentally save it in a notebook or source file you later commit to GitHub. In this notebook we will be storing the API key in a .env file. You can also set it as an environment variable or use a secret manager.

Here’s how to set it up in a .env file:

$ touch .env
$ echo "GEMINI_API_KEY=<YOUR_API_KEY>" >> .env
Tip

Another option is to set the API key as an environment variable. You can do this in your terminal with the following command:

$ export GEMINI_API_KEY="<YOUR_API_KEY>"

Load the API key

To load the API key from the .env file, we will use the dotenv package. This package loads environment variables from a .env file into process.env.

$ npm install dotenv

Then, we can load the API key in our code:

const dotenv = require("dotenv") as typeof import("dotenv");

dotenv.config({
  path: "../.env",
});

const GEMINI_API_KEY = process.env.GEMINI_API_KEY ?? "";
if (!GEMINI_API_KEY) {
  throw new Error("GEMINI_API_KEY is not set in the environment variables");
}
console.log("GEMINI_API_KEY is set in the environment variables");
GEMINI_API_KEY is set in the environment variables
Note

In our particular case the .env is is one directory up from the notebook, hence we need to use ../ to go up one directory. If the .env file is in the same directory as the notebook, you can omit it altogether.

│
├── .env
└── examples
    └── Search_reranking_using_embeddings.ipynb

Initialize SDK Client

With the new SDK, now you only need to initialize a client with you API key (or OAuth if using Vertex AI). The model is now set in each call.

const google = require("@google/genai") as typeof import("@google/genai");

const ai = new google.GoogleGenAI({ apiKey: GEMINI_API_KEY });

Select a model

Now select the model you want to use in this guide, either by selecting one in the list or writing it down. Keep in mind that some models, like the 2.5 ones are thinking models and thus take slightly more time to respond (cf. thinking notebook for more details and in particular learn how to switch the thiking off).

const tslab = require("tslab") as typeof import("tslab");

const MODEL_ID = "gemini-2.5-flash-preview-05-20";

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(number) 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.
/* eslint-disable @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument */

const wikipedia = require("wikipedia") as typeof import("wikipedia");

async function wikipediaSearch(queries: string[]): Promise<string[]> {
  const n_topics = 3;
  const searchHistory = new Set<string>();
  const searchUrl: string[] = [];
  const summaryResults: string[] = [];

  for (const query of queries) {
    console.log(`Searching for "${query}"`);
    // @ts-expect-error search not available
    const search = await wikipedia.search(query, { limit: n_topics });
    const terms = search.results as { ns: string; title: string; pageid: string }[];

    console.log(`Related search terms: [${terms.map((term) => `'${term.title}'`).join(", ")}]`);

    for (const term of terms) {
      if (searchHistory.has(term.title)) continue;
      searchHistory.add(term.title);

      console.log(`Fetching page: ${term.title}`);
      // @ts-expect-error page not available
      const page = await wikipedia.page(term.title);
      searchUrl.push(page.fullurl);
      const content = await page.content();
      console.log(`Information source: ${page.fullurl}`);

      const response = await ai.models.generateContent({
        model: MODEL_ID,
        contents: `
          Extract relevant information
          about user's query: ${query}
          From this source:

          ${content}

          Note: Do not summarize. Only Extract and return the relevant information
        `,
      });
      const urls = [page.fullurl];
      if (response.candidates?.[0]?.citationMetadata) {
        const extraCitations = response.candidates[0].citationMetadata.citations ?? [];
        const extraUrls = extraCitations.map((src) => src.uri).filter((uri) => uri);
        urls.concat(extraUrls);
      }
      summaryResults.push(`${response.text ?? ""}\n\nBased on:\n${urls.join(",\n ")}`);

      await new Promise((resolve) => setTimeout(resolve, 5000));
    }
  }
  console.log("Information Sources:");
  for (const url of searchUrl) {
    console.log(`- ${url}`);
  }
  return summaryResults;
}
const example = await wikipediaSearch(["What are LLMs?"]);
Searching for "What are LLMs?"
Related search terms: ['Large language model', 'Retrieval-augmented generation', 'Prompt injection']
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: Prompt injection
Information source: https://en.wikipedia.org/wiki/Prompt_injection
Information Sources:
- https://en.wikipedia.org/wiki/Large_language_model
- https://en.wikipedia.org/wiki/Retrieval-augmented_generation
- https://en.wikipedia.org/wiki/Prompt_injection

Here is what the search results look like:

for (const e of example) {
  tslab.display.markdown(e);
  tslab.display.markdown("\n---\n");
}

A large language model (LLM) is a language model trained with self-supervised machine learning on a vast amount of text, designed for natural language processing tasks, especially language generation. The largest and most capable LLMs are generative pretrained transformers (GPTs). LLMs can be fine-tuned for specific tasks or guided by prompt engineering. These models acquire predictive power regarding syntax, semantics, and ontologies inherent in human language corpora, but they also inherit inaccuracies and biases present in the data they are trained in. An LLM is a type of foundation model (large X model) trained on language.

Based on: https://en.wikipedia.org/wiki/Large_language_model


Large language models (LLMs) are: * Models that respond to user queries. * “Traditional LLMs that rely on static training data.” * Can be “LLM-based chatbots” that “generate responses.” * Models that typically have “pre-existing training data” or an “original training set.” * Concerned with “language semantics.” * Able to “synthesize an engaging answer tailored to the user.”

LLMs’ inherent behaviors and limitations: * They “can provide incorrect information.” * They “can generate misinformation” or “hallucinate.” * They may not “know” or “understand” the context. * They “struggle to recognize when they lack sufficient information to provide a reliable response.” * They “may generate answers even when they should indicate uncertainty.” * They “lack the ability to assess its own knowledge limitations.” * They “may extract statements from a source without considering its context, resulting in an incorrect conclusion.” * When faced with conflicting information, LLMs “may struggle to determine which source is accurate.” * They “may combine details from multiple sources producing responses that merge outdated and updated information in a misleading manner.”

Based on: https://en.wikipedia.org/wiki/Retrieval-augmented_generation


The provided source does not contain a definition or explanation of what Large Language Models (LLMs) are. It primarily discusses prompt injection as a cybersecurity exploit targeting LLMs.

Based on: https://en.wikipedia.org/wiki/Prompt_injection


Pass the tools to the model

You can pass a list of FunctionDeclaration objects in the tools config. If you want the SDK itself to call the function (Auto Function Calling), you can pass a CallableTool object to the SDK and it will automatically call the function if the method supports it.

import { CallableTool, FunctionCall, FunctionDeclaration, Part, Tool } from "@google/genai";

const search_wikipedia: FunctionDeclaration = {
  name: "search_wikipedia",
  description: "Search wikipedia for each query and summarize relevant docs.",
  parameters: {
    type: google.Type.OBJECT,
    properties: {
      queries: {
        type: google.Type.ARRAY,
        description: "A list of search queries.",
        items: {
          type: google.Type.STRING,
          description: "A search query",
        },
      },
    },
    required: ["queries"],
  },
  response: {
    type: google.Type.ARRAY,
    description: "Returns relevant extracted information with respect to the query.",
    items: {
      type: google.Type.STRING,
      description: "Extracted relevant information",
    },
  },
};

const search_wikipedia_tool: CallableTool = {
  async callTool(functionCalls: FunctionCall[]): Promise<Part[]> {
    const parts: Part[] = [];
    for (const fc of functionCalls) {
      const args = fc.args as { queries: string[] };
      const results = await wikipediaSearch(args.queries);
      parts.push(
        google.createPartFromFunctionResponse(fc.id ?? "", fc.name ?? "", {
          name: fc.name ?? "",
          response: results,
        })
      );
    }
    return parts;
  },
  async tool(): Promise<Tool> {
    return { functionDeclarations: [search_wikipedia] };
  },
};

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.

const userQuery = (query: string): string => `
  You have access to the Wikipedia API which you will be using
  to answer a user's query. Your job is to generate a list of search queries which
  might answer a user's question. Be creative by using various key-phrases from
  the user's query. To generate variety of queries, ask questions which are
  related to  the user's query that might help to find the answer. The more
  queries you generate the better are the odds of you finding the correct answer.
  Here is an example:
  
  user: Tell me about Cricket World cup 2023 winners.
  
  function_call: wikipedia_search(['What is the name of the team that
  won the Cricket World Cup 2023?', 'Who was the captain of the Cricket World Cup
  2023 winning team?', 'Which country hosted the Cricket World Cup 2023?', 'What
  was the venue of the Cricket World Cup 2023 final match?', 'Cricket World cup 2023',
  'Who lifted the Cricket World Cup 2023 trophy?'])
  
  The search function will return a list of article summaries, use these to
  answer the  user's question.
  
  Here is the user's query: ${query}
`;

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 automaticFunctionCalling. With it enabled, the Chat will handle the back and forth required to call the function, and return the final response:

const chat = ai.chats.create({
  model: MODEL_ID,
  config: {
    tools: [search_wikipedia_tool],
    temperature: 0.6,
  },
});
async function query(query: string): Promise<string> {
  const response = await chat.sendMessageStream({
    message: userQuery(query),
  });
  let accumulatedResponse = "";
  for await (const part of response) {
    accumulatedResponse += part.text ?? "";
  }
  return accumulatedResponse;
}
// temporarily make console.warn a no-op to avoid warnings in the output (non-text part in GenerateContentResponse caused by accessing .text)
// https://github.com/googleapis/js-genai/blob/d82aba244bdb804b063ef8a983b2916c00b901d2/src/types.ts#L2005
// copy the original console.warn function to restore it later
const warn_fn = console.warn;
// eslint-disable-next-line @typescript-eslint/no-empty-function, no-empty-function
console.warn = function () {};

const query1 = await query("Explain how deep-sea life survives.");
Searching for "How does deep-sea life survive?"
Related search terms: ['Deep sea', 'Deep-sea fish', 'Still Wakes the Deep']
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: Still Wakes the Deep
Information source: https://en.wikipedia.org/wiki/Still_Wakes_the_Deep
Searching for "Deep sea food sources"
Related search terms: ['Deep-sea fish', 'Deep-sea community', 'Deep sea']
Fetching page: Deep-sea community
Information source: https://en.wikipedia.org/wiki/Deep-sea_community
Searching for "Adaptations of deep-sea organisms to high pressure"
Related search terms: ['Deep-sea fish', 'Deep sea', 'Deep-sea gigantism']
Fetching page: Deep-sea gigantism
Information source: https://en.wikipedia.org/wiki/Deep-sea_gigantism
Searching for "Chemosynthesis in deep sea"
Related search terms: ['Deep sea', 'Deep-sea community', 'Chemosynthesis']
Fetching page: Chemosynthesis
Information source: https://en.wikipedia.org/wiki/Chemosynthesis
Searching for "Hydrothermal vents deep sea life"
Related search terms: ['Deep-sea community', 'Hydrothermal vent', 'Deep sea']
Fetching page: Hydrothermal vent
Information source: https://en.wikipedia.org/wiki/Hydrothermal_vent
Searching for "Deep sea animal adaptations to lack of light"
Related search terms: ['Deep sea', 'Deep-sea fish', 'Deep-sea community']
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
Searching for "Bioluminescence deep sea creatures"
Related search terms: ['Deep-sea community', 'Deep sea', 'Deep-sea fish']
Searching for "Deep sea fish survival mechanisms"
Related search terms: ['Seahorse', 'Deep-sea community', 'Deep sea mining']
Fetching page: Seahorse
Information source: https://en.wikipedia.org/wiki/Seahorse
Fetching page: Deep sea mining
Information source: https://en.wikipedia.org/wiki/Deep_sea_mining
Searching for "What challenges do deep sea animals face?"
Related search terms: ['Deep sea', 'Deep sea mining', 'Animal Face-Off']
Fetching page: Animal Face-Off
Information source: https://en.wikipedia.org/wiki/Animal_Face-Off
Information Sources:
- https://en.wikipedia.org/wiki/Deep_sea
- https://en.wikipedia.org/wiki/Deep-sea_fish
- https://en.wikipedia.org/wiki/Still_Wakes_the_Deep
- https://en.wikipedia.org/wiki/Deep-sea_community
- https://en.wikipedia.org/wiki/Deep-sea_gigantism
- https://en.wikipedia.org/wiki/Chemosynthesis
- https://en.wikipedia.org/wiki/Hydrothermal_vent
- https://en.wikipedia.org/wiki/Oceanic_trench
- https://en.wikipedia.org/wiki/Seahorse
- https://en.wikipedia.org/wiki/Deep_sea_mining
- https://en.wikipedia.org/wiki/Animal_Face-Off
tslab.display.markdown(query1);

Deep-sea life has evolved remarkable adaptations to survive in an environment characterized by extreme pressure, perpetual darkness, scarce food, and cold temperatures.

Here’s how deep-sea organisms manage to thrive:

  1. Food Sources:
    • Marine Snow: The primary food source for most deep-sea organisms is “marine snow,” which consists of organic detritus, dead organisms, and waste products that slowly drift down from the sunlit upper layers of the ocean.
    • Large Food Falls: Occasional large food falls, such as whale carcasses, provide substantial, albeit infrequent, feasts for scavengers like amphipods, crabs, and hagfish, creating temporary, localized ecosystems.
    • Chemosynthesis: In specific areas like hydrothermal vents and cold seeps, life doesn’t rely on sunlight. Instead, chemosynthetic bacteria form the base of the food chain by converting chemicals (like hydrogen sulfide and methane) from the Earth’s interior into organic matter. Many organisms, such as giant tube worms, clams, and mussels, form symbiotic relationships with these bacteria, hosting them internally to gain nutrients.
  2. Adaptations to High Pressure:
    • Deep-sea creatures maintain an internal pressure equal to the external hydrostatic pressure, preventing them from being crushed.
    • Their cell membranes contain a higher proportion of unsaturated fatty acids to maintain fluidity, as high pressure tends to make membranes rigid.
    • They have developed unique proteins and enzymes that function optimally under extreme pressure, with structural modifications like increased salt bridges in proteins (e.g., α-actin) to enhance stability.
    • Many deep-sea fish accumulate osmolytes like Trimethylamine N-oxide (TMAO), which protects proteins from destabilization under high pressure.
    • Some organisms, like the Mariana hadal snailfish, have evolved open skulls or cartilage-based bone structures that can withstand constant high pressure better than rigid, closed bone structures.
  3. Adaptations to Lack of Light (Darkness):
    • Sensory Enhancements: Many deep-sea organisms are blind, relying instead on highly developed senses of touch, smell, and sensitivity to pressure changes to navigate and find food or mates.
    • Enhanced Vision: For those with eyes, they are often exceptionally large and sensitive (up to 100 times more sensitive than human eyes), containing only rod cells and sometimes multiple Rhodopsin genes to detect even the faintest bioluminescent light. Some have tubular eyes that look upwards to spot silhouettes of prey against faint light from above.
    • Bioluminescence: Over 50% of deep-sea fish, shrimp, and squid produce their own light through bioluminescence. This light is used for various purposes:
      • Hunting: Lures (e.g., anglerfish) to attract prey.
      • Communication: Unique patterns to find mates or claim territory.
      • Defense: Distracting predators or using “counter-illumination” (lighting up their bellies to match ambient light from above) for camouflage.
  4. Physical and Metabolic Adaptations:
    • Buoyancy: Many deep-sea species have jelly-like flesh, high water content, and reduced skeletal and muscular structures, making them less dense and allowing them to remain suspended with minimal energy expenditure. Some squid use flotation chambers filled with ammonium chloride.
    • Slow Metabolism: Due to scarce food and low temperatures, deep-sea animals generally have very slow metabolisms, allowing them to conserve energy and survive long periods without food.
    • Feeding Strategies: They are often “lie-in-wait” predators with large, extendable mouths, sharp teeth, and expandable stomachs, enabling them to consume prey as large as or even larger than themselves when an opportunity arises. They are typically non-selective feeders.
    • Body Structure: Many have weak, watery muscles and minimal skeletal structures. Some mesopelagic fish undertake daily vertical migrations, moving to shallower waters at night to feed and returning to deeper, safer waters during the day.
  5. Reproductive Strategies:
    • Finding a mate in the vast, dark deep sea is challenging. Adaptations include:
      • Bioluminescent courtship displays.
      • Hermaphroditism: Being both male and female increases the chances of successful reproduction upon encountering another individual.
      • Male Parasitism: In some anglerfish, the tiny male permanently attaches to the female, fusing circulatory systems and becoming a sperm-producing appendage.

These diverse and specialized adaptations allow deep-sea organisms to not only survive but also flourish in one of Earth’s most extreme environments.

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:

import { Content } from "@google/genai";

function printHistory(history: Content[]) {
  for (const content of history) {
    tslab.display.markdown(`### ${content.role ?? ""}:`);
    for (const part of content.parts ?? []) {
      if (part.text) {
        tslab.display.markdown(part.text);
      }
      if (part.functionCall) {
        console.log("Function Call\n", JSON.stringify(part.functionCall, null, 2));
      }
      if (part.functionResponse) {
        console.log("Function Response\n", JSON.stringify(part.functionResponse, null, 2));
      }
    }
    tslab.display.markdown(`\n---\n`);
  }
}
printHistory(chat.getHistory());

user:

You have access to the Wikipedia API which you will be using to answer a user’s query. Your job is to generate a list of search queries which might answer a user’s question. Be creative by using various key-phrases from the user’s query. To generate variety of queries, ask questions which are related to the user’s query that might help to find the answer. The more queries you generate the better are the odds of you finding the correct answer. Here is an example:

user: Tell me about Cricket World cup 2023 winners.

function_call: wikipedia_search([‘What is the name of the team that won the Cricket World Cup 2023?’, ‘Who was the captain of the Cricket World Cup 2023 winning team?’, ‘Which country hosted the Cricket World Cup 2023?’, ‘What was the venue of the Cricket World Cup 2023 final match?’, ‘Cricket World cup 2023’, ‘Who lifted the Cricket World Cup 2023 trophy?’])

The search function will return a list of article summaries, use these to answer the user’s question.

Here is the user’s query: Explain how deep-sea life survives.


model:

Function Call
 {
  "name": "search_wikipedia",
  "args": {
    "queries": [
      "How does deep-sea life survive?",
      "Deep sea food sources",
      "Adaptations of deep-sea organisms to high pressure",
      "Chemosynthesis in deep sea",
      "Hydrothermal vents deep sea life",
      "Deep sea animal adaptations to lack of light",
      "Deep sea extremophiles",
      "Bioluminescence deep sea creatures",
      "Deep sea fish survival mechanisms",
      "What challenges do deep sea animals face?"
    ]
  }
}

user:

Function Response
 {
  "id": "",
  "name": "search_wikipedia",
  "response": {
    "name": "search_wikipedia",
    "response": [
      "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.\nExcept for the areas close to the hydrothermal vents, this energy comes from organic material drifting down from the photic zone. The sinking organic material is composed of algal particulates, detritus, and other forms of biological waste, which is collectively referred to as 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—they 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. They have elongated bodies with weak, watery muscles and skeletal structures. They 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. Their 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. The 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. This 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.\nOrganisms in the deep sea are almost entirely reliant upon sinking living and dead organic matter which falls at approximately 100 meters per day.\nLarger food falls, such as whale carcasses, also occur and studies have shown that these may happen more often than currently believed. There 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.\nThere are a number of species that do not primarily rely upon dissolved organic matter for their food. These species and communities are found at hydrothermal vents at sea-floor spreading zones. One example is the symbiotic relationship between the tube worm Riftia and chemosynthetic bacteria. It is this chemosynthesis that supports the complex communities that can be found around hydrothermal vents.\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.\nThe deep-sea organisms must have the ability to maintain well-regulated metabolic system in the face of high pressures. In order to adjust for the extreme environment, these organisms have developed unique characteristics.\nSome Deep-sea fish developed pressure tolerance through the change in mechanism of their α-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 α-Actin, which serves as the main component of muscle fiber. These specific substitutions, Q137K and V54A from C.armatus or I67P from C.yaquinae are predicted to have importance in pressure tolerance. Substitution 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, confirmed by the free energy analysis and molecular dynamics simulation. It was found that deep sea fish have more salt bridges in their actins compared to fish inhabiting the upper zones of the sea.\nSpecific osmolytes were found to be abundant in deep sea fish under high hydrostatic pressure. For certain chondrichthyans, it was found that Trimethylamine N-oxide (TMAO) increased with depth, replacing other osmolytes and urea. Due 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. Mariana hadal snailfish developed modification in the Osteocalcin(burlap) gene, where premature termination of the gene was found. Osteocalcin gene regulates bone development and tissue mineralization, and the frameshift mutation seems to have resulted in the open skull and cartilage-based bone formation. Due to high hydrostatic pressure in the deep sea, closed skulls that organisms living on the surface develop cannot withstand the enforcing stress. Similarly, common bone developments seen in surface vertebrates cannot maintain their structural integrity under constant high pressure.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Deep_sea",
      "Here is the extracted information about how deep-sea life survives:\n\n*   **Reliance on Marine Snow for Food:** Deep-sea organisms rely heavily on marine snow (organic detritus falling from upper layers) as an energy source, as sunlight cannot reach them and there is a lack of primary producers.\n*   **Adaptations to High Pressure:**\n    *   Deep-sea organisms have the same pressure within their bodies as is exerted on them from the outside, preventing them from being crushed.\n    *   They increase the proportion of unsaturated fatty acids in the lipids of their cell membranes to maintain fluidity, as high pressure reduces it.\n    *   Their metabolic processes are adapted to ultimately decrease the volume of the organism.\n    *   Deep-sea organisms contain gas-filled spaces (vacuoles), but because gas is compressed under high pressure, they can \"blow up\" if brought to the surface.\n    *   They have evolved changes in their protein structure and reaction criteria to withstand pressure, as high levels of external pressure affect metabolic processes and biochemical reactions.\n    *   Globular proteins of deep-sea fish are relatively rigid compared to surface fish, structurally strengthened by modification of bonds in their tertiary structure.\n    *   Their Na+/K+-ATPases (a lipoprotein enzyme important for osmoregulation) exhibit a much higher tolerance of hydrostatic pressure compared to shallow-water counterparts, explained by adaptations in the protein and lipid parts of the enzyme.\n    *   Ten orders, thirteen families, and about 200 known species have evolved a gelatinous layer below the skin or around the spine for buoyancy, low-cost growth, and to increase swimming efficiency by reducing drag.\n*   **Sensory Adaptations (due to lack of light):**\n    *   Many organisms are blind and rely on other senses like sensitivities to changes in local pressure and smell.\n    *   Those that aren't blind have large and sensitive eyes (up to 100 times more sensitive than human eyes) to use bioluminescent light.\n    *   Some deep-sea fish have multiple Rhodopsin (Rh1) opsin genes (e.g., silver spinyfin has 38) to help them see in dim light.\n    *   Mesopelagic fish often have large eyes, with some deeper water fish having tubular eyes with large lenses and only rod cells that look upwards for binocular vision and sensitivity to small light signals.\n    *   Important sensory systems include the inner ear (responds to sound) and the lateral line (responds to changes in water pressure).\n    *   The olfactory system can be important, especially for males to find females by smell.\n*   **Bioluminescence:**\n    *   More than 50% of deep-sea fish, shrimp, and squid are bioluminescent, producing light through the agitation of luciferin molecules in the presence of oxygen.\n    *   They often have photophores (light-producing glandular cells) which may contain lenses to intensify or lessen light.\n    *   Bioluminescence is used to search for food, attract prey (like the anglerfish's lure), claim territory, communicate and find a mate, and distract or temporarily blind predators.\n    *   In the mesopelagic zone, some organisms use counter-illumination (illuminating bellies to match ambient light) to camouflage themselves from predators below.\n*   **Physical Adaptations for Buoyancy and Movement:**\n    *   Eggs and larvae often contain oil droplets in their plasma to maintain neutral buoyancy.\n    *   Deep-sea fish usually do not have gas-filled swim bladders due to high pressure; instead, they may use structures similar to hydrofoils for hydrodynamic lift.\n    *   The deeper a fish lives, the more jelly-like its flesh and the more minimal its bone structure.\n    *   They reduce tissue density through high fat content, reduction of skeletal weight (smaller size, thickness, mineral content), and water accumulation. This makes them slower and less agile but requires less energy to stay suspended.\n    *   Body shapes are generally better adapted for periodic bursts of swimming rather than constant swimming.\n*   **Feeding Adaptations (due to scarce food):**\n    *   Some have long feelers to help locate prey or attract mates.\n    *   The deep-sea anglerfish has a bioluminescent, worm-like lure protruding from its face.\n    *   They must consume other fish of the same size or larger, so they have great sharp teeth, hinged jaws, disproportionately large mouths, and expandable bodies (e.g., gulper eel).\n    *   Bathypelagic fish have slow metabolisms and unspecialized diets, preferring to sit and wait for food rather than expend energy searching. They are almost all lie-in-wait predators.\n    *   They are not selective in their feeding habits and grab whatever comes close, using large mouths with sharp teeth and overlapping gill rakers to prevent small prey from escaping.\n*   **Reproductive Adaptations:**\n    *   Some species depend on unique bioluminescent patterns for mate attraction.\n    *   Others are hermaphrodites to increase chances of reproduction when encounters are rare.\n    *   Female anglerfish release pheromones to attract tiny males. Some anglerfish males (e.g., Haplophryne mollis) bite onto a female, release an enzyme that fuses them, and their circulatory systems join, with the male atrophying into gonads.\n*   **General Survival Characteristics:**\n    *   Many deep-sea fish are dark to blend in with their environment; red coloration also functions as camouflage as red light doesn't penetrate to deep-sea.\n    *   Bathypelagic fish have slow metabolisms, weak, watery muscles, and skeletal structures, and are slimy without scales.\n    *   Gills, kidneys, hearts, and swim bladders can be small or missing, a feature suggesting neoteny, which allows them to remain suspended with little energy expenditure.\n    *   Mesopelagic fish have muscular bodies, ossified bones, scales, well-developed gills, 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    *   Some mesopelagic fish make daily vertical migrations (following zooplankton) to feed in shallower waters at night and return to depths for safety during the day, aided by a swim bladder.\n    *   They display considerable tolerances for temperature change, migrating through thermoclines.\n    *   Lack defensive spines.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Deep-sea_fish",
      "The provided source material, \"Still Wakes the Deep,\" is a description of a psychological horror video game set on an oil rig. It does not contain information about how deep-sea life survives. The text focuses on the game's plot, gameplay, development, and reception, with the \"monsters\" in the game being mutated oil rig workers rather than natural deep-sea creatures.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Still_Wakes_the_Deep",
      "The three main sources of energy and nutrients for deep sea communities are:\n\n*   **Marine snow:** Particulate organic matter (POM) repackaged into larger particles that sink from the upper photic zone, providing food for opportunistic organisms on and in the bottom. This includes wood-boring bivalves feeding on plant remains.\n*   **Occasional surface blooms:** Sudden access to nutrients near the surface leading to blooms of plankton, algae, or animals (like salps) that sink to the bottom without being consumed. These short bursts of nutrients are rapidly consumed by animals and microbes, with waste products becoming part of deep-sea sediments.\n*   **Whale falls:** The death of a whale brings hundreds of tons of organic matter to the bottom, creating a community that progresses through three stages:\n    *   **Mobile scavenger stage:** Large, mobile deep-sea animals (amphipods, crabs, sleeper sharks, hagfish) scavenge the carcass.\n    *   **Opportunistic stage:** Organisms like *Osedax* (tube worms) colonize bones and surrounding sediments contaminated with organic matter.\n    *   **Sulfophilic stage:** Further decomposition of bones and seawater sulfate reduction create a sulphide-rich environment analogous to hydrothermal vents, attracting sulphur-loving creatures (polynoids, bivalves, gastropods).\n*   **Chemosynthesis:**\n    *   **Hydrothermal vents:** Cold seawater circulates through cracks, heats up, dissolves minerals and sulfides, and then emanates from active sub-seafloor rifts. Chemosynthesis by bacteria provides energy and organic matter for the entire food web in these ecosystems. These bacteria can form mats on the seafloor, serving as food for other creatures, and are a key energy source.\n    *   **Cold seeps:** Areas on the ocean floor where hydrogen sulfide, methane, and other hydrocarbon-rich fluids seep, often forming brine pools. These provide energy to chemosynthetic extremophiles.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Deep-sea_community",
      "Based on the provided text, there is no information about \"Adaptations of deep-sea organisms to high pressure.\"\n\nThe text mentions \"hydrostatic pressure\" once in the \"Lower temperature\" section, stating: \"In Arctic and Antarctic seas where there is a reduced vertical temperature gradient, there is also a reduced trend towards increased body size with depth, arguing against hydrostatic pressure being an important parameter.\" This suggests that hydrostatic pressure is *not* considered an important factor for deep-sea gigantism according to the text's explanations.\n\nThe text discusses other environmental factors like temperature, food scarcity, predation pressure, and dissolved oxygen levels, but does not detail adaptations *to high pressure* itself.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Deep-sea_gigantism",
      "Many microorganisms in dark regions of the oceans use chemosynthesis to produce biomass from single-carbon molecules.\nIn most oceanic environments, energy for chemosynthesis derives from reactions in which substances such as hydrogen sulfide or ammonia are oxidized.\nLarge populations of animals can be supported by chemosynthetic secondary production at hydrothermal vents, methane clathrates, cold seeps, whale falls, and isolated cave water.\nGiant tube worms use bacteria in their trophosome to fix carbon dioxide (using hydrogen sulfide as their energy source) and produce sugars and amino acids.\nWinogradsky's suggestion was confirmed nearly 90 years later, when hydrothermal ocean vents were discovered in the 1970s.\nThe hot springs and strange creatures were discovered by Alvin, the world's first deep-sea submersible, in 1977 at the Galapagos Rift.\nAt about the same time, then-graduate student Colleen Cavanaugh proposed chemosynthetic bacteria that oxidize sulfides or elemental sulfur as a mechanism by which tube worms could survive near hydrothermal vents.\nCavanaugh later managed to confirm that this was indeed the method by which the worms could thrive, and is generally credited with the discovery of chemosynthesis.\nIn 2013, researchers reported their discovery of bacteria living in the rock of the oceanic crust below the thick layers of sediment, and apart from the hydrothermal vents that form along the edges of the tectonic plates.\nPreliminary findings are that these bacteria subsist on the hydrogen produced by chemical reduction of olivine by seawater circulating in the small veins that permeate the basalt that comprises oceanic crust.\nThe bacteria synthesize methane by combining hydrogen and carbon dioxide.\nChemosynthetic communities in different environments are important biological systems in terms of their ecology, evolution and biogeography, as well as their potential as indicators of the availability of permanent hydrocarbon- based energy sources.\nIn the process of chemosynthesis, bacteria produce organic matter where photosynthesis is impossible.\nIsolation of thermophilic sulfate-reducing bacteria Thermodesulfovibrio yellowstonii and other types of chemosynthetics provides prospects for further research.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Chemosynthesis",
      "The following information about deep sea life at hydrothermal vents is extracted from the provided source:\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*   Hydrothermal vents have been hypothesized to have been a significant factor to starting abiogenesis and the survival of primitive life. The conditions of these vents have been shown to support the synthesis of molecules important to life.\n*   There are numerous species of extremophiles and other organisms currently living immediately around deep-sea vents, suggesting that this is indeed a possible scenario for the origin of life.\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. 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*   These organisms include yeti crabs, which have long hairy arms that they reach out over the vent to collect food with.\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. 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 vents' impact on the living environment goes beyond the organisms that lives around them, as they act as a significant source of iron in the oceans, providing iron for the phytoplankton.\n*   The oldest confirmed record of a \"modern\" biological community related with a vent is the Figueroa Sulfide, from the Early Jurassic of California.\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*   While 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*   The main families of organisms found around seafloor vents are annelids, pogonophorans, gastropods, and crustaceans, with large bivalves, vestimentiferan worms, and \"eyeless\" shrimp making up the bulk of nonmicrobial organisms.\n*   Siboglinid tube worms, which may grow to over 2 m (6.6 ft) tall in the largest species, often form an important part of the community around a hydrothermal vent. They have no mouth or digestive tract, and like parasitic worms, absorb nutrients produced by the bacteria in their tissues.\n*   About 285 billion bacteria are found per ounce of tubeworm tissue.\n*   Tubeworms have red plumes which contain hemoglobin. Hemoglobin combines with hydrogen sulfide and transfers it to the bacteria living inside the worm. In return, the bacteria nourish the worm with carbon compounds.\n*   Two of the species that inhabit a hydrothermal vent are *Tevnia jerichonana*, and *Riftia pachyptila*.\n*   One discovered community, dubbed \"Eel City\", consists predominantly of the eel *Dysommina rugosa*. Though eels are not uncommon, invertebrates typically dominate hydrothermal vents.\n*   In 1993, already more than 100 gastropod species were known to occur in hydrothermal vents.\n*   Over 300 new species have been discovered at hydrothermal vents, many of them \"sister species\" to others found in geographically separated vent areas.\n*   The examples of convergent evolution seen between distinct hydrothermal vents is seen as major support for the theory of natural selection and of evolution as a whole.\n*   Although life is very sparse at these depths, black smokers are the centers of entire ecosystems. 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*   A species of phototrophic bacterium has been found living near a black smoker off the coast of Mexico at a depth of 2,500 m (8,200 ft). This is the first organism discovered in nature to exclusively use a light other than sunlight for photosynthesis.\n*   New and unusual species are constantly being discovered in the neighborhood of black smokers.\n*   The Pompeii worm *Alvinella pompejana*, which is capable of withstanding temperatures up to 80 °C (176 °F), was found in the 1980s.\n*   A scaly-foot gastropod *Chrysomallon squamiferum* was found in 2001 during an expedition to the Indian Ocean's Kairei hydrothermal vent field. This gastropod uses iron sulfides (pyrite and greigite) for the structure of its dermal sclerites (hardened body parts), instead of calcium carbonate. This armor plating probably serves as a defense against the venomous radula (teeth) of predatory snails in that community.\n*   In March 2017, researchers reported evidence of possibly the oldest forms of life on Earth. Putative fossilized microorganisms were discovered in hydrothermal vent precipitates in the Nuvvuagittuq Belt of Quebec, Canada, that may have lived as early as 4.280 billion years ago.\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. 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*   The symbiont converts inorganic molecules (H2S, CO2, O) to organic molecules that the host then uses as nutrition.\n*   Scientists were astounded when they first found hydrothermal vents teeming with life in 1977. 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*   Scientists are studying how the microbial symbionts aid in sulfide detoxification (therefore allowing the host to survive the otherwise toxic conditions). Host-associated microbiomes are also important in host development, nutrition, defense against predators, and detoxification.\n*   In return, the host provides the symbiont with chemicals required for chemosynthesis, such as carbon, sulfide, and oxygen.\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*   In 1981, it was understood that giant tubeworm nutrition acquisition occurred as a result of chemoautotrophic bacterial endosymbionts.\n*   Symbiotic relationships between chemoautotrophs and macrofauna invertebrate species were found to be ubiquitous. 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\", where they deal with nutrition and where their endosymbionts are found. 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*   The tubeworms hemoglobin is capable of carrying oxygen without interference or inhibition from sulfide, due to zinc ions that bind the hydrogen sulfide, reducing tissue exposure to sulfide and providing bacteria with sulfide for chemoautotrophy.\n*   Tubeworms can metabolize CO2 in two different ways, and can alternate between the two as needed.\n*   In 1988, research confirmed thiotrophic (sulfide-oxidizing) bacteria in *Alviniconcha hessleri*, a large vent mollusk.\n*   Mussels convert sulfide to thiosulfate before carrying it over to the symbionts to circumvent sulfide toxicity.\n*   Motile organisms such as alvinocarid shrimp must track oxic (oxygen-rich) / anoxic (oxygen-poor) environments as they fluctuate.\n*   Organisms living at the edge of hydrothermal vent fields, such as pectinid scallops, also carry endosymbionts in their gills, but their dependence on the microbial endosymbiont for nutrition is lessened.\n*   Not all host animals have endosymbionts; some have episymbionts—symbionts living on the animal as opposed to inside the animal. Shrimp found at vents in the Mid-Atlantic Ridge were discovered to carry episymbionts in 1988. Other organisms like *Lepetodrilis fucensis* also carry episymbionts.\n*   While some symbionts reduce sulfur compounds, others are known as \"methanotrophs\" and reduce carbon compounds, namely methane. Bathmodiolid mussels are an example of a host that contains methanotrophic endosymbionts; however, the latter mostly occur in cold seeps as opposed to hydrothermal vents.\n*   While chemosynthesis 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ápagos Rift submarine hydrothermal vents were first directly observed in 1977.\n*   In 1979, a team of biologists led by J. Frederick Grassle returned to the Galápagos Rift to investigate the biological communities discovered two year earlier.\n*   On Easter Sunday April 15, 1979, during a dive of Alvin to 2,600 meters, Roger Larson and Bruce Luyendyk found a hydrothermal vent field with a biological community similar to the Galápagos vents.\n*   The unique depositing of metals and altered local chemistry in turn allow for conditions to support life of thermophiles and other organisms.\n*   The highly saline character of the waters in the Red Sea hot brines was not hospitable to living organisms.\n*   Conservation of hydrothermal vent ecosystems after mining would depend on the recolonization of chemosynthetic bacteria, and the continuation of hydrothermal vent fluid.\n*   Studies on recolonization after volcanic destruction show it took 3–5 years for bacteria to recolonize, and around 10 years for megafauna to return. There was also a shift in species composition and the presence of immigrant species.\n*   Research on deep sea shrimp has shown the potential for flood lights used on the sea floor to cause permanent retinal damage, warranting further research into the potential risk to other vent organisms.\n*   A large percent of benthic organisms communicate using very low-frequency sounds; increasing ambient noise levels on the seafloor could potentially mask communication and alter behavioral patterns.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Hydrothermal_vent",
      "From the provided source, the following information is relevant to \"Deep sea extremophiles\":\n\n*   \"These support unique biomes based on chemotrophic microorganisms.\"\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.\"\n*   \"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:\nhttps://en.wikipedia.org/wiki/Oceanic_trench",
      "The provided text focuses exclusively on seahorses (genus Hippocampus), which are explicitly stated to be \"mainly found in shallow tropical and temperate salt water throughout the world.\"\n\nTherefore, this source does not contain relevant information about \"deep sea fish survival mechanisms.\"\n\nBased on:\nhttps://en.wikipedia.org/wiki/Seahorse",
      "The provided text does not contain information about \"deep sea fish survival mechanisms.\" It focuses on deep sea mining, its types, locations, regulations, environmental impacts, and related economic and geopolitical aspects.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Deep_sea_mining",
      "The provided source describes the television program \"Animal Face-Off\" and does not contain information about the challenges deep sea animals face.\n\nBased on:\nhttps://en.wikipedia.org/wiki/Animal_Face-Off"
    ]
  }
}

model:

Deep-sea life has evolved remarkable adaptations to survive in an environment characterized by extreme pressure, perpetual darkness, scarce food, and cold temperatures.

Here’s how deep-sea organisms manage to thrive:

  1. **Food

model:

Sources: * Marine Snow:** The primary food source for most deep-sea organisms is “marine snow,” which consists of organic detritus, dead organisms, and waste products that slowly drift down from the sunlit upper layers


model:

of the ocean. * Large Food Falls: Occasional large food falls, such as whale carcasses, provide substantial, albeit infrequent, feasts for scavengers like amphipods, crabs, and hagfish, creating temporary,


model:

localized ecosystems. * Chemosynthesis: In specific areas like hydrothermal vents and cold seeps, life doesn’t rely on sunlight. Instead, chemosynthetic bacteria form the base of the food chain by converting chemicals (


model:

like hydrogen sulfide and methane) from the Earth’s interior into organic matter. Many organisms, such as giant tube worms, clams, and mussels, form symbiotic relationships with these bacteria, hosting them internally to gain nutrients.

  1. **Adaptations

model:

to High Pressure:** * Deep-sea creatures maintain an internal pressure equal to the external hydrostatic pressure, preventing them from being crushed. * Their cell membranes contain a higher proportion of unsaturated fatty acids to maintain fluidity, as high


model:

pressure tends to make membranes rigid. * They have developed unique proteins and enzymes that function optimally under extreme pressure, with structural modifications like increased salt bridges in proteins (e.g., α-actin) to enhance stability.


model:

  • Many deep-sea fish accumulate osmolytes like Trimethylamine N-oxide (TMAO), which protects proteins from destabilization under high pressure.
    • Some organisms, like the Mariana hadal snailfish, have evolved

model:

open skulls or cartilage-based bone structures that can withstand constant high pressure better than rigid, closed bone structures.

  1. Adaptations to Lack of Light (Darkness):
    • Sensory Enhancements: Many deep

model:

-sea organisms are blind, relying instead on highly developed senses of touch, smell, and sensitivity to pressure changes to navigate and find food or mates. * Enhanced Vision: For those with eyes, they are often exceptionally large and sensitive (


model:

up to 100 times more sensitive than human eyes), containing only rod cells and sometimes multiple Rhodopsin genes to detect even the faintest bioluminescent light. Some have tubular eyes that look upwards to spot silhouettes of prey against faint


model:

light from above. * Bioluminescence: Over 50% of deep-sea fish, shrimp, and squid produce their own light through bioluminescence. This light is used for various purposes: * **


model:

Hunting:** Lures (e.g., anglerfish) to attract prey. * Communication: Unique patterns to find mates or claim territory. * Defense: Distracting predators or using “counter-illumination


model:

” (lighting up their bellies to match ambient light from above) for camouflage.

  1. Physical and Metabolic Adaptations:
    • Buoyancy: Many deep-sea species have jelly-like flesh,

model:

high water content, and reduced skeletal and muscular structures, making them less dense and allowing them to remain suspended with minimal energy expenditure. Some squid use flotation chambers filled with ammonium chloride. * Slow Metabolism: Due to scarce food and


model:

low temperatures, deep-sea animals generally have very slow metabolisms, allowing them to conserve energy and survive long periods without food. * Feeding Strategies: They are often “lie-in-wait” predators with large, extend


model:

able mouths, sharp teeth, and expandable stomachs, enabling them to consume prey as large as or even larger than themselves when an opportunity arises. They are typically non-selective feeders. * Body Structure: Many have weak, watery muscles and


model:

minimal skeletal structures. Some mesopelagic fish undertake daily vertical migrations, moving to shallower waters at night to feed and returning to deeper, safer waters during the day.

  1. Reproductive Strategies:
    • Finding

model:

a mate in the vast, dark deep sea is challenging. Adaptations include: * Bioluminescent courtship displays. * Hermaphroditism: Being both male and female increases the chances of successful reproduction upon


model:

encountering another individual. * Male Parasitism: In some anglerfish, the tiny male permanently attaches to the female, fusing circulatory systems and becoming a sperm-producing appendage.

These diverse and specialized adaptations allow deep-sea organisms


model:

to not only survive but also flourish in one of Earth’s most extreme environments.


In the chat history you can see all 4 steps:

  1. The user sent the query.
  2. The model replied with a FunctionCall calling the wikipedia_search with a number of relevant searches.
  3. Because you set Chat has auto function calling enabled by default for sendMessageStream, it executed the search function and returned the list of article summaries to the model.
  4. Following 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.

const manualChat = ai.chats.create({
  model: MODEL_ID,
  config: {
    tools: [search_wikipedia_tool],
    temperature: 0.6,
    automaticFunctionCalling: {
      disable: true,
    },
  },
});
const manualChatResponse1 = await manualChat.sendMessage({
  message: userQuery("Explain how deep-sea life survives."),
});

Initially the model returns a FunctionCall:

console.log(JSON.stringify(manualChatResponse1.functionCalls, null, 2));
[
  {
    "name": "search_wikipedia",
    "args": {
      "queries": [
        "How does deep-sea life survive?",
        "Deep-sea adaptations",
        "Deep-sea food sources",
        "Chemosynthesis deep sea",
        "Hydrothermal vents deep sea life",
        "Deep-sea pressure adaptation",
        "Deep-sea temperature adaptation",
        "Deep-sea bioluminescence",
        "Deep-sea extremophiles"
      ]
    }
  }
]

Call the function with generated arguments to get the results.

const functionCall = manualChatResponse1.functionCalls?.[0];
const { queries } = functionCall?.args as { queries: string[] };
console.log("Function Call Arguments:", JSON.stringify(queries, null, 2));
const summaries = await wikipediaSearch(queries);
Function Call Arguments: [
  "How does deep-sea life survive?",
  "Deep-sea adaptations",
  "Deep-sea food sources",
  "Chemosynthesis deep sea",
  "Hydrothermal vents deep sea life",
  "Deep-sea pressure adaptation",
  "Deep-sea temperature adaptation",
  "Deep-sea bioluminescence",
  "Deep-sea extremophiles"
]
Searching for "How does deep-sea life survive?"
Related search terms: ['Deep sea', 'Deep-sea fish', 'Still Wakes the Deep']
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: Still Wakes the Deep
Information source: https://en.wikipedia.org/wiki/Still_Wakes_the_Deep
Searching for "Deep-sea adaptations"
Related search terms: ['Deep-sea fish', 'Deep sea', 'Deep-sea gigantism']
Fetching page: Deep-sea gigantism
Information source: https://en.wikipedia.org/wiki/Deep-sea_gigantism
Searching for "Deep-sea food sources"
Related search terms: ['Deep-sea fish', 'Deep-sea community', 'Deep sea']
Fetching page: Deep-sea community
Information source: https://en.wikipedia.org/wiki/Deep-sea_community
Searching for "Chemosynthesis deep sea"
Related search terms: ['Deep-sea community', 'Deep sea', 'Chemosynthesis']
Fetching page: Chemosynthesis
Information source: https://en.wikipedia.org/wiki/Chemosynthesis
Searching for "Hydrothermal vents deep sea life"
Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Deep sea']
Fetching page: Hydrothermal vent
Information source: https://en.wikipedia.org/wiki/Hydrothermal_vent
Searching for "Deep-sea pressure adaptation"
Related search terms: ['Deep-sea gigantism', 'Deep sea', 'Deep-sea fish']
Searching for "Deep-sea temperature adaptation"
Related search terms: ['Deep-sea gigantism', 'Deep sea', 'Deep-sea fish']
Searching for "Deep-sea bioluminescence"
Related search terms: ['Stomiidae', 'Deep sea', 'Bioluminescence']
Fetching page: Stomiidae
Information source: https://en.wikipedia.org/wiki/Stomiidae
Fetching page: Bioluminescence
Information source: https://en.wikipedia.org/wiki/Bioluminescence
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/Deep_sea
- https://en.wikipedia.org/wiki/Deep-sea_fish
- https://en.wikipedia.org/wiki/Still_Wakes_the_Deep
- https://en.wikipedia.org/wiki/Deep-sea_gigantism
- https://en.wikipedia.org/wiki/Deep-sea_community
- https://en.wikipedia.org/wiki/Chemosynthesis
- https://en.wikipedia.org/wiki/Hydrothermal_vent
- https://en.wikipedia.org/wiki/Stomiidae
- https://en.wikipedia.org/wiki/Bioluminescence
- https://en.wikipedia.org/wiki/Oceanic_trench

Now send the FunctionResponse to the model.

const functionResponse = google.createPartFromFunctionResponse(functionCall.id ?? "", functionCall.name ?? "", {
  name: functionCall.name ?? "",
  response: summaries,
});

const manualChatResponse2 = await manualChat.sendMessage({
  message: functionResponse,
});
tslab.display.markdown(manualChatResponse2.text ?? "");

Deep-sea life survives in an environment characterized by extreme pressure, perpetual darkness, and scarce food, through a remarkable array of biological and physiological adaptations:

1. Adapting to Extreme Pressure: Deep-sea organisms maintain internal pressure equal to the immense external hydrostatic pressure. Their bodies exhibit several adaptations to prevent collapse: * Protein Structure: Proteins are modified to function under high pressure, for example, through increased salt bridges in their structure (e.g., in actin) or the presence of osmolytes like Trimethylamine N-oxide (TMAO) that protect proteins. * Cell Membranes: Cell membranes have a higher proportion of unsaturated fatty acids, which helps maintain their fluidity despite the pressure. * Skeletal and Body Structure: Many deep-sea fish have gelatinous, watery muscles and minimal skeletal structures (e.g., open skulls in hadal snailfish) to avoid being crushed. Gas-filled swim bladders, common in shallow-water fish, are often absent or filled with fat, as gas would be compressed at such depths.

2. Surviving in Darkness: With no sunlight, deep-sea creatures have evolved unique ways to navigate, find food, and avoid predators: * Sensory Reliance: They rely heavily on senses other than sight, such as sensitivity to changes in local pressure, smell, and touch, often using long feelers. * Vision: Those that do have eyes often possess large, sensitive, tubular eyes with only rod cells and an upward field of vision to detect faint light or silhouettes of prey. Some have multiple rhodopsin genes or retroreflectors behind the retina for enhanced low-light vision. * Bioluminescence: Many organisms produce their own light through bioluminescence. This light is used for: * Attracting Prey: Like the anglerfish’s glowing lure. * Communication: To find mates or signal within their species. * Camouflage: Through counter-illumination, where light is emitted from the belly to match the dim light from above, eliminating a shadow. * Distraction: Releasing a cloud of luminous material to startle or distract predators. * Coloration: Many are black or red, as red light wavelengths do not penetrate to the deep sea, making red effectively invisible in the dark.

3. Overcoming Food Scarcity: Food is extremely scarce, so deep-sea life has adapted diverse strategies for energy acquisition: * Marine Snow: The primary food source for many, consisting of organic detritus, fecal matter, and dead organisms that drift down from the more productive upper layers of the ocean. * Chemosynthesis: In unique ecosystems around hydrothermal vents and cold seeps, life thrives without sunlight. Chemosynthetic bacteria form the base of the food chain by converting chemical compounds (like hydrogen sulfide and methane) into organic matter. Many animals, such as tube worms and clams, live in symbiotic relationships with these bacteria, hosting them in their tissues to obtain nutrients. * Whale Falls: The carcasses of whales that sink to the seafloor provide massive, albeit temporary, food sources, supporting a succession of scavengers and specialized organisms. * Opportunistic Feeding: Many are “sit-and-wait” predators with slow metabolisms to conserve energy. They often have large, extendable, hinged jaws and sharp teeth to capture and swallow prey larger than themselves when the opportunity arises. * Deep-Sea Gigantism: Some deep-sea species are significantly larger than their shallow-water relatives. This is thought to be an adaptation to scarce food (larger size improves foraging efficiency), colder temperatures (leading to increased cell size and lifespan), reduced predation pressure, and increased dissolved oxygen concentrations.

4. Reproduction in a Sparse Environment: Finding a mate in the vast, dark deep sea is challenging, leading to adaptations like: * Hermaphroditism: Many species are hermaphroditic, increasing the chances of successful reproduction when an encounter occurs. * Chemical Signals: Pheromones are used to attract mates over distances. * Permanent Mating: In some species, like anglerfish, the male permanently attaches to the female, ensuring a mate is always available for spawning.

5. Buoyancy and Movement: * Low-Density Tissues: Many organisms have jelly-like flesh, high fat content, and reduced skeletal weight to achieve neutral buoyancy without expending much energy. * Efficient Movement: Body shapes are often adapted for periodic bursts of swimming rather than continuous movement, further conserving energy.

Re-ranking the search results

Helper function to embed the content:

const EMBEDDING_MODEL_ID = "gemini-embedding-001";

async function embedContent(contents: string[]): Promise<number[][]> {
  const response = await ai.models.embedContent({
    model: EMBEDDING_MODEL_ID,
    contents: contents,
    config: {
      taskType: "semantic_similarity",
    },
  });
  return response.embeddings?.map((embedding) => embedding.values) ?? [];
}

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 will be ~1. Hence, calculating cosine similarity is esentially same as calculating their dot product score.

function dotProduct(a: number[], b: number[]): number {
  return a.reduce((sum, value, index) => sum + value * b[index], 0);
}

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.

const searchResults = await embedContent(summaries);
const queryEmbedding = await embedContent(["Explain how deep-sea life survives."]);

Calculate similarity score:

const similarityScores = searchResults.map((result) => dotProduct(result, queryEmbedding[0]));
console.log("Similarity Scores:", similarityScores);
Similarity Scores: [
  0.9117504634217665,
  0.878951087997969,
  0.8209106391648435,
  0.8783796961153858,
  0.8736032494958526,
  0.8513247283724289,
  0.8334251232616245,
  0.789654151444905,
  0.8101736873042428,
  0.8353845714633688
]

Order the summary search results by their similarity scores to the user’s query. The highest score will be the most relevant result.

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

Answer:

const bestCandidateIndex = similarityScores.indexOf(Math.max(...similarityScores));
console.log(`Best Candidate Index: ${bestCandidateIndex} with score ${similarityScores[bestCandidateIndex]}`);
tslab.display.markdown(summaries[bestCandidateIndex] ?? "");
Best Candidate Index: 0 with score 0.9117504634217665

Deep-sea life survives through a variety of adaptations to conditions of low temperatures, darkness, and high pressure, and through diverse feeding methods.

Feeding and Energy Acquisition: * Organisms survive through feeding methods including scavenging, predation, and filtration. * Many organisms survive by feeding on marine snow, which is organic material that has fallen from upper waters. * Energy generally comes from organic material (algal particulates, detritus, biological waste, marine snow) drifting down from the photic zone. * Food also consists of carcasses derived from the productive zone above. * There are many scavengers that feed primarily or entirely upon large food falls, such as whale carcasses. * A number of filter feeders feed upon organic particles using tentacles. * At hydrothermal vents, some species and communities do not primarily rely upon dissolved organic matter for food but depend on chemosynthesis, for example, through a symbiotic relationship between tube worms and chemosynthetic bacteria. These communities are one of the few ecosystems that do not rely upon sunlight for energy.

Adaptations to Physical Conditions (Pressure, Buoyancy, Body Structure, Metabolism): * Many deep-sea species have jelly-like flesh consisting mostly of glycosaminoglycans, which provides them with very low density for buoyancy, instead of relying on gas. * Deep water squid combine gelatinous tissue with a flotation chamber filled with coelomic fluid made up of ammonium chloride, which is lighter than the surrounding water. * Midwater fish are small, usually under 25 centimetres, have slow metabolisms and unspecialized diets, preferring to sit and wait for food to conserve energy. * They have elongated bodies with weak, watery muscles and skeletal structures. * They often have extendable, hinged jaws with recurved teeth for feeding. * Deep-sea fish have adaptations in their proteins, anatomical structures, and metabolic systems to withstand great hydrostatic pressure. * They maintain well-regulated metabolic systems despite high pressures. * They preserve protein functionality against pressure through physiological and structural adaptations. * Some deep-sea fish developed pressure tolerance through changes in the mechanism of their α-actin protein, specifically through substitutions on its active sites (e.g., Q137K, V54A, I67P), leading to significant changes in salt bridge patterns for better stabilization in ATP binding and subunit arrangement. Deep-sea fish have more salt bridges in their actins. * Specific osmolytes are abundant in deep-sea fish under high hydrostatic pressure; for certain chondrichthyans, Trimethylamine N-oxide (TMAO) increases with depth, protecting proteins from destabilization by high hydrostatic pressure. * Mariana hadal snailfish developed modifications in the Osteocalcin gene (e.g., premature termination) which resulted in open skull and cartilage-based bone formation, as closed skulls and common bone developments of surface vertebrates cannot withstand the extreme hydrostatic pressure.

Adaptations to Darkness and Reproduction: * Many organisms are hermaphroditic due to sparse distribution and difficulty in finding a partner for breeding in the dark. * Fish often have larger than normal, tubular eyes with only rod cells and an upward field of vision to seek out the silhouette of possible prey. * Prey fish reduce their silhouettes through lateral compression of the body and counter illumination via bioluminescence (producing light from ventral photophores) to camouflage themselves. * Some fish have a retroreflector behind the retina for more sensitive vision in low light. * Flashlight fish use a retroreflector plus photophores to detect eyeshine in other fish.

Based on: https://en.wikipedia.org/wiki/Deep_sea

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.

const res = await ai.models.generateContent({
  model: MODEL_ID,
  contents: `
      Generate a hypothetical answer
      to the user's query by using your own knowledge. Assume that you know everything
      about the said topic. Do not use factual information, instead use placeholders
      to complete your answer. Your answer should feel like it has been written by a human.

      query: "Explain how deep-sea life survives."
    `,
});
tslab.display.markdown(res.text ?? "");

Oh, it’s truly astonishing how life manages to thrive in the deepest parts of our planet, isn’t it? It’s a world of immense pressure, perpetual darkness, and biting cold, yet these incredible organisms have developed some remarkably ingenious solutions to survive, and even flourish.

One of the most immediate challenges is the overwhelming pressure. Imagine the weight! Deep-sea life deals with this by having bodies that are fundamentally different from surface creatures. They often lack the air-filled spaces that would collapse under such force. Instead, their internal structures and cellular components are designed to perfectly balance the external force. Many possess specialized [placeholder for internal stabilizing compounds] and unique [placeholder for cellular architecture] that maintain the integrity of their tissues and organs, preventing them from being crushed or deformed. Their very [placeholder for bodily consistency] is often adapted to be in equilibrium with their surroundings.

Then there’s the complete absence of sunlight. Down there, traditional photosynthesis, which powers most life on the surface, is impossible. So, how do they get energy? This is where it gets truly fascinating. Many deep-sea inhabitants rely on what you might call ‘alternative energy pathways.’ Instead of the sun, they tap into energy from [placeholder for geological processes] or [placeholder for chemical reactions] occurring at [placeholder for specific deep-sea features]. They often do this with the help of tiny [placeholder for symbiotic organisms] that live within or near them, converting these [placeholder for energy-rich substances] into usable fuel. Other creatures are masters of efficiency, extracting every last bit of nutrient from the scarce organic ‘rain’ that drifts down from above, or are adept predators in the dark, some even generating their own [placeholder for light-like emissions] for communication or hunting.

The extreme cold is another hurdle. Deep-sea organisms manage this by having very efficient [placeholder for metabolic rates] that allow them to operate optimally at low temperatures. Some even produce specialized [placeholder for internal chemical compounds] that act like a natural antifreeze, preventing ice crystals from forming within their cells.

As for food scarcity, it’s a truly sparse environment. So, they’ve adapted by being incredibly efficient and opportunistic. Their [placeholder for digestive systems] are often highly specialized to extract maximum nutrients from whatever infrequent meals they find, and many have developed [placeholder for slow life processes] or [placeholder for energy conservation strategies] to minimize their energy expenditure, allowing them to go for very long periods without food.

Even finding a mate in such a vast, dark expanse is a monumental task. They’ve developed some truly ingenious solutions, like using powerful [placeholder for chemical signals], unique [placeholder for light displays], or highly sensitive [placeholder for sensory organs] to detect each other across great distances.

Ultimately, deep-sea life is a testament to the incredible adaptability of living things. Every aspect of their [placeholder for biological systems] – from their molecular makeup to their sensory organs – has been fine-tuned over countless [placeholder for periods of time] to not just endure, but to genuinely thrive in one of Earth’s most challenging environments. It’s a world where [placeholder for unique biological principles] seem to be at play, allowing life to persist against all odds.

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

const hypotheticalAnswer = await embedContent([res.text ?? ""]);

Calculate similarity scores to rank the search results

const similarityScoresFromHyDE = searchResults.map((result) => dotProduct(result, hypotheticalAnswer[0]));
console.log("Similarity Scores from HyDE:", similarityScoresFromHyDE);
Similarity Scores from HyDE: [
  0.8824987051617097,
  0.8606763507470175,
  0.7755931754943494,
  0.8378522917247573,
  0.8291790160640604,
  0.8156207966301365,
  0.8130383455248943,
  0.7818944367323967,
  0.7959257563521293,
  0.8140033334818754
]

Order the summary search results by their similarity scores to the user’s query. The highest score will be the most relevant result.

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

Answer:

const bestCandidateIndexFromHyDE = similarityScoresFromHyDE.indexOf(Math.max(...similarityScoresFromHyDE));
console.log(
  `Best Candidate Index from HyDE: ${bestCandidateIndexFromHyDE} with score ${similarityScoresFromHyDE[bestCandidateIndexFromHyDE]}`
);
tslab.display.markdown(summaries[bestCandidateIndexFromHyDE] ?? "");
Best Candidate Index from HyDE: 0 with score 0.8824987051617097

Deep-sea life survives through a variety of adaptations to conditions of low temperatures, darkness, and high pressure, and through diverse feeding methods.

Feeding and Energy Acquisition: * Organisms survive through feeding methods including scavenging, predation, and filtration. * Many organisms survive by feeding on marine snow, which is organic material that has fallen from upper waters. * Energy generally comes from organic material (algal particulates, detritus, biological waste, marine snow) drifting down from the photic zone. * Food also consists of carcasses derived from the productive zone above. * There are many scavengers that feed primarily or entirely upon large food falls, such as whale carcasses. * A number of filter feeders feed upon organic particles using tentacles. * At hydrothermal vents, some species and communities do not primarily rely upon dissolved organic matter for food but depend on chemosynthesis, for example, through a symbiotic relationship between tube worms and chemosynthetic bacteria. These communities are one of the few ecosystems that do not rely upon sunlight for energy.

Adaptations to Physical Conditions (Pressure, Buoyancy, Body Structure, Metabolism): * Many deep-sea species have jelly-like flesh consisting mostly of glycosaminoglycans, which provides them with very low density for buoyancy, instead of relying on gas. * Deep water squid combine gelatinous tissue with a flotation chamber filled with coelomic fluid made up of ammonium chloride, which is lighter than the surrounding water. * Midwater fish are small, usually under 25 centimetres, have slow metabolisms and unspecialized diets, preferring to sit and wait for food to conserve energy. * They have elongated bodies with weak, watery muscles and skeletal structures. * They often have extendable, hinged jaws with recurved teeth for feeding. * Deep-sea fish have adaptations in their proteins, anatomical structures, and metabolic systems to withstand great hydrostatic pressure. * They maintain well-regulated metabolic systems despite high pressures. * They preserve protein functionality against pressure through physiological and structural adaptations. * Some deep-sea fish developed pressure tolerance through changes in the mechanism of their α-actin protein, specifically through substitutions on its active sites (e.g., Q137K, V54A, I67P), leading to significant changes in salt bridge patterns for better stabilization in ATP binding and subunit arrangement. Deep-sea fish have more salt bridges in their actins. * Specific osmolytes are abundant in deep-sea fish under high hydrostatic pressure; for certain chondrichthyans, Trimethylamine N-oxide (TMAO) increases with depth, protecting proteins from destabilization by high hydrostatic pressure. * Mariana hadal snailfish developed modifications in the Osteocalcin gene (e.g., premature termination) which resulted in open skull and cartilage-based bone formation, as closed skulls and common bone developments of surface vertebrates cannot withstand the extreme hydrostatic pressure.

Adaptations to Darkness and Reproduction: * Many organisms are hermaphroditic due to sparse distribution and difficulty in finding a partner for breeding in the dark. * Fish often have larger than normal, tubular eyes with only rod cells and an upward field of vision to seek out the silhouette of possible prey. * Prey fish reduce their silhouettes through lateral compression of the body and counter illumination via bioluminescence (producing light from ventral photophores) to camouflage themselves. * Some fish have a retroreflector behind the retina for more sensitive vision in low light. * Flashlight fish use a retroreflector plus photophores to detect eyeshine in other fish.

Based on: https://en.wikipedia.org/wiki/Deep_sea

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.