DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Building a Voice-Powered Smart Kitchen App Using LLaMA 3.1, Firebase, and Node.js
  • AI-Powered Flashcard Application With Next.js, Clerk, Firebase, Material UI, and LLaMA 3.1
  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Trending

  • How to Merge HTML Documents in Java
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Event Driven Architecture (EDA) - Optimizer or Complicator
  • Using Python Libraries in Java
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Firebase Genkit With Ollama

Firebase Genkit With Ollama

Explore a Firebase project that uses the Gen AI Kit with Gemma using Ollama and learn how to test it locally with the Firebase emulator and the Gen UI Kit.

By 
Xavier Portilla Edo user avatar
Xavier Portilla Edo
DZone Core CORE ·
May. 27, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
1.5K Views

Join the DZone community and get the full member experience.

Join For Free

This is a simple example of a Firebase function that uses Genkit and Ollama to translate any test to Spanish.

This project uses the following technologies:

  1. Firebase Functions
  2. Firebase Genkit
  3. Ollama

This project uses the following Node.js Packages:

  1. @genkit-ai/firebase: Genkit Firebase SDK to be able to use Genkit in Firebase Functions
  2. genkitx-ollama: Genkit Ollama plugin to be able to use Ollama in Genkit
  3. @genkit-ai/ai, @genkit-ai/core and @genkit-ai/flow: Genkit AI Core SDK
  4. @genkit-ai/dotprompt: Plugin to use DotPrompt in Genkit

Setup

  1. Clone this GitHub repository.
  2. Run npm install to install the dependencies in the functions folder.
  3. Run firebase login to log in to your Firebase account.
  4. Install genkit-cli by running npm install -g genkit. 

This repo is supposed to be used with Node.js version 20.

Run the Firebase Emulator

To run the function locally, run GENKIT_ENV=dev firebase emulators:start --inspect-functions. 

The emulator will be available at http://localhost:4000.

Open Genkit UI

Go to the functions folder and run genkit start --attach http://localhost:3100 --port 4001 to open the Genkit UI. The UI will be available at http://localhost:4001.

Open Genkit UI

Run Gemma With Ollama

You will need to install Ollama by running brew install ollama and then run ollama run gemma to start the Ollama server.

Code Explanation

The code is in the functions/index.ts file. The function is called translatorFlow and it uses the Genkit SDK to translate the text into Spanish.

First, we have to configure the Genkit SDK with the Ollama plugin:

configureGenkit({
  plugins: [
    firebase(),
    ollama({
      models: [{ name: 'gemma' }],
      serverAddress: 'http://127.0.0.1:11434', // default ollama local address
    }),
  ],
  logLevel: "debug",
  enableTracingAndMetrics: true,
});


Then, we define the function - in the Gen AI Kit, they call it Flows. Flows are functions with some additional characteristics: they are strongly typed, streamable, locally and remotely callable, and fully observable. Firebase Genkit provides CLI and Developer UI tooling for working with flows (running, debugging, etc):

export const translatorFlow = onFlow(
  {
    name: "translatorFlow",
    inputSchema: z.object({ text: z.string() }),
    outputSchema: z.string(),
    authPolicy: noAuth(), // Not requiring authentication, but you can change this. It is highly recommended to require authentication for production use cases.
  },
  async (toTranslate) => {
    const prompt =
      `Translate this ${toTranslate.text} to Spanish. Autodetect the language.`;

    const llmResponse = await generate({
      model: 'ollama/gemma',
      prompt: prompt,
      config: {
        temperature: 1,
      },
    });

    return llmResponse.text();
  }
);


As we saw above, we use Zod to define the input and output schema of the function. We also use the generate function from the Genkit SDK to generate the translation.

We also have disabled the authentication for this function, but you can change this by changing the authPolicy property:

firebaseAuth((user) => {
  if (!user.email_verified) {
    throw new Error('Verified email required to run flow');
  }
});


For the example above, you will need to import the firebaseAuth function from the @genkit-ai/firebase/auth package:

import { firebaseAuth } from '@genkit-ai/firebase/auth';


Invoke the Function Locally

Now you can invoke the function by running genkit flow:run translatorFlow '{"text":"hi"}' in the terminal.

You can also make a curl command by running curl -X GET -H "Content-Type: application/json" -d '{"data": { "text": "hi" }}' http://127.0.0.1:5001/<firebase-project>/<region>/translatorFlow in the terminal.

For example:

> curl -X GET -H "Content-Type: application/json" -d '{"data": { "text": "hi" }}' http://127.0.0.1:5001/action-helloworld/us-central1/translatorFlow
{"result":"Hola\n\nThe translation of \"hi\" to Spanish is \"Hola\"."}


You can also use Postman or any other tool to make a GET request to the function:

Make a GET request to the function

Deploy

To deploy the function, run firebase deploy --only functions. You will need to change the Ollama URL in the function to the URL of the Ollama server.

Conclusion

As you can see, it is very easy to use Genkit and Ollama in Firebase Functions. You can use this example as a starting point to create your own functions using Genkit and Ollama.

You can find the full code of this example in the GitHub repository (linked earlier).

Happy coding!

Resources

  • Firebase Genkit
  • Ollama
  • Firebase Functions
AI Firebase

Published at DZone with permission of Xavier Portilla Edo, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building a Voice-Powered Smart Kitchen App Using LLaMA 3.1, Firebase, and Node.js
  • AI-Powered Flashcard Application With Next.js, Clerk, Firebase, Material UI, and LLaMA 3.1
  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!