Bootstrap FreeKB - OpenAI - Getting Started with Mastra OpenAI on Linux
OpenAI - Getting Started with Mastra OpenAI on Linux

Updated:   |  OpenAI articles

Mastra is a framework for building AI applications and agents. On a Linux system, let's create a directory.

mkdir my_mastra_app

 

And move into the directory.

cd my_mastra_app

 

In this example, we will use Node.js to run the Mastra AI application. Let's use the Node.js package manager CLI npm to install the @master/core package.

npm install @mastra/core

 

This should create a file named package.json in your present working directory and a directory named node_modules.

~]$ ls -l

-rw-r--r--.   1 john.doe users    540 Nov 16 15:47 demo.js
drwxr-xr-x. 203 john.doe users   8192 Nov 16 15:11 node_modules
-rw-r--r--.   1 john.doe users    111 Nov 16 15:13 package.json
-rw-r--r--.   1 john.doe users 210155 Nov 16 15:13 package-lock.json

 

The package.json file should contain something like this.

~]$ cat package.json
{
  "dependencies": {
    "@mastra/core": "^0.24.1"
  }
}

 

Likewise, the npm list command should include @mastra/core.

~]$ npm list
ai_agent@ /home/john.doe/my_mastra_app
└── @mastra/core@0.24.1

 

Let's update the package.json file to contain "type": "module" so that we can run our Mastra application as a Node.js module.

~]$ cat package.json
{
  "type": "module",
  "dependencies": {
    "@mastra/core": "^0.24.1"
  }
}

 

Let's create a file named demo.js that contains the following. Notice in this example that model openai/gpt-4.1-mini is being used. https://mastra.ai/models/providers/openai contains the various different models that can be used.

import { Agent } from "@mastra/core/agent";
import { Mastra } from "@mastra/core/mastra";

export const testAgent = new Agent({
  name: "my-agent",
  instructions: "You are a helpful assistant.",
  model: "openai/gpt-4.1-mini",
});

export const mastra = new Mastra({
  agents: { testAgent },
  telemetry: {
    enabled: false,
  }
});

const agent = mastra.getAgent("testAgent");
const response = await agent.generate("Who is the current president of the United States of America?");
console.log(response.text);

 

Last but not least before running the application, at https://platform.openai.com/api-keys, create an API key and issue the following command to set the OPENAI_API_KEY variable.

export OPENAI_API_KEY=<your API key>

 

Use the node CLI to run demo.js and the application should answer the question.

~]$ node demo.js
As of June 2024, the current president of the United States of America is Joe Biden

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d15f89 in the box below so that we can be sure you are a human.