Skip to content

add openai env variables #826

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

philippderdiedas
Copy link

@philippderdiedas philippderdiedas commented Jun 19, 2025

Add ENV variables to change OpenAI model types.
Update example env file

What kind of change does this PR introduce?

This PR removes the OPEN_API_KEY variables from the openai constructor calls.
The offical openai node package already uses ENVs for setting the OPENAI_API_KEY and OPENAI_BASE_URL.
So only the model name overrides were missing.
New Envs:
OPENAI_TEXT_MODEL defaults to gpt-4.1
OPENAI_TEXT_MODEL_MINI defaults to gpt-4o-mini
OPENAI_IMAGE_MODEL defaults to gpt-image-1

Why was this change needed?

See Issue #256
Also:
Some custom OpenAI compatible server require no API-Key, see commit e1486f7

Other information:

Tested with myLabs AI Server Platform (at university wide instance)
Example envs:

OPENAI_BASE_URL="https://models.mylab.*OMITTED*/v1"
OPENAI_API_KEY=""
OPENAI_TEXT_MODEL="chat-lts"
OPENAI_TEXT_MODEL_MINI="chat-lts"
OPENAI_IMAGE_MODEL="flux.1-schnell"

Checklist:

Put a "X" in the boxes below to indicate you have followed the checklist;

  • I have read the CONTRIBUTING guide.
  • I checked that there were not similar issues or PRs already open for this.
  • This PR fixes just ONE issue (do not include multiple issues or types of change in the same PR) For example, don't try and fix a UI issue and include new dependencies in the same PR.

Summary by CodeRabbit

  • New Features
    • Added support for configuring OpenAI model names and API endpoints via environment variables.
  • Chores
    • Updated example environment file with new variables for OpenAI integration.
  • Refactor
    • Switched model selection and API endpoint configuration to use environment variables with sensible defaults.
    • Removed explicit API key assignment in OpenAI-related services, relying on environment configuration instead.

add custom base_url
add custom models
Copy link

vercel bot commented Jun 19, 2025

Someone is attempting to deploy a commit to the Listinai Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented Jun 19, 2025

Walkthrough

The changes update OpenAI integration across several backend and library files. Environment variables are introduced for specifying OpenAI API endpoints and model names, replacing hardcoded values. The explicit use of the OpenAI API key is removed from code, and model selection is now driven by environment variables, with sensible defaults provided.

Changes

File(s) Change Summary
.env.example Added four new environment variables for OpenAI integration: OPENAI_BASE_URL, OPENAI_TEXT_MODEL, OPENAI_TEXT_MODEL_MINI, and OPENAI_IMAGE_MODEL, each with default values and comments.
apps/backend/src/api/routes/copilot.controller.ts Updated chat enablement check to require both API key and base URL to be missing before aborting; model selection now uses environment variables with fallback defaults instead of hardcoded strings.
libraries/nestjs-libraries/src/agent/agent.graph.insert.service.ts Removed explicit API key usage for ChatOpenAI; model name now comes from OPENAI_TEXT_MODEL environment variable or a default value.
libraries/nestjs-libraries/src/agent/agent.graph.service.ts, libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts Removed direct API key assignment for ChatOpenAI and DallEAPIWrapper; model selection now relies on OPENAI_TEXT_MODEL and OPENAI_IMAGE_MODEL environment variables with defaults.
libraries/nestjs-libraries/src/openai/openai.service.ts Removed explicit API key from OpenAI client; all model names for image and text generation now use environment variables with fallback defaults.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Backend API
    participant OpenAI Service

    Client->>Backend API: Request (e.g., chat, image generation)
    Backend API->>OpenAI Service: Prepare OpenAI call (model/env vars)
    OpenAI Service->>OpenAI: Call with model from env var (no explicit API key)
    OpenAI-->>OpenAI Service: Response
    OpenAI Service-->>Backend API: Result
    Backend API-->>Client: Response
Loading

Poem

In the garden of code, a bunny hops,
Swapping keys for models, with elegant stops.
No more secrets in plain sight,
Just env vars guiding the light.
Now OpenAI listens with models anew,
As the backend hums, and carrots accrue! 🥕

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/backend/src/api/routes/copilot.controller.ts

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)

libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)

libraries/nestjs-libraries/src/openai/openai.service.ts

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d610117 and 61d2d6c.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • apps/backend/src/api/routes/copilot.controller.ts (2 hunks)
  • libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts (1 hunks)
  • libraries/nestjs-libraries/src/openai/openai.service.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • libraries/nestjs-libraries/src/openai/openai.service.ts
  • .env.example
  • apps/backend/src/api/routes/copilot.controller.ts
  • libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-and-publish
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@egelhaus egelhaus added the type: feature-request New feature or request label Jun 19, 2025
@egelhaus egelhaus linked an issue Jun 19, 2025 that may be closed by this pull request
1 task
@philippderdiedas philippderdiedas marked this pull request as ready for review June 20, 2025 17:01
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
apps/backend/src/api/routes/copilot.controller.ts (2)

17-17: Clarify the environment variable check logic and improve the comment.

The logic !process.env.OPENAI_API_KEY && !process.env.OPENAI_BASE_URL will only abort if both variables are missing. While this supports the use case of custom servers without API keys, the comment "if using official OpenAI API, abort if no key" doesn't accurately describe this behavior.

Consider updating the comment to better reflect the actual logic:

-      !process.env.OPENAI_API_KEY && !process.env.OPENAI_BASE_URL // if using offical OpenAI API, abort if no key
+      !process.env.OPENAI_API_KEY && !process.env.OPENAI_BASE_URL // abort only if both API key and base URL are missing

26-34: Consider adding environment variable validation.

The implementation directly uses environment variables without validation. Invalid model names could cause runtime errors when making API calls.

Consider adding validation for the environment variables:

+    const textModel = process.env.OPENAI_TEXT_MODEL || 'gpt-4';
+    const textModelMini = process.env.OPENAI_TEXT_MODEL_MINI || 'gpt-4o-mini';
+    
+    // Basic validation could be added here
+    if (!textModel.startsWith('gpt-')) {
+      Logger.warn(`Potentially invalid OpenAI model name: ${textModel}`);
+    }

     const copilotRuntimeHandler = copilotRuntimeNestEndpoint({
       endpoint: '/copilot/chat',
       runtime: new CopilotRuntime(),
       serviceAdapter: new OpenAIAdapter({
         model:
           // @ts-ignore
           req?.body?.variables?.data?.metadata?.requestType ===
           'TextareaCompletion'
-            ? (process.env.OPENAI_TEXT_MODEL_MINI || 'gpt-4o-mini')
-            : (process.env.OPENAI_TEXT_MODEL || 'gpt-4.1'),
+            ? textModelMini
+            : textModel,
       }),
     });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ad21ea0 and e1486f7.

📒 Files selected for processing (6)
  • .env.example (1 hunks)
  • apps/backend/src/api/routes/copilot.controller.ts (2 hunks)
  • libraries/nestjs-libraries/src/agent/agent.graph.insert.service.ts (1 hunks)
  • libraries/nestjs-libraries/src/agent/agent.graph.service.ts (1 hunks)
  • libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts (1 hunks)
  • libraries/nestjs-libraries/src/openai/openai.service.ts (8 hunks)
🧰 Additional context used
🪛 dotenv-linter (3.3.0)
.env.example

[warning] 77-77: [ValueWithoutQuotes] This value needs to be surrounded in quotes


[warning] 79-79: [ValueWithoutQuotes] This value needs to be surrounded in quotes

🔇 Additional comments (3)
libraries/nestjs-libraries/src/agent/agent.graph.insert.service.ts (1)

11-14: LGTM! Good environment variable integration.

The changes correctly remove explicit API key usage and implement environment-driven model selection with a sensible fallback. This supports the PR's objective of enabling custom OpenAI-compatible servers.

libraries/nestjs-libraries/src/openai/openai.service.ts (1)

7-7: LGTM! Correct removal of explicit API key.

The empty constructor allows the OpenAI client to use environment variables automatically, which aligns with the PR objectives.

apps/backend/src/api/routes/copilot.controller.ts (1)

31-32: Verify the default model name gpt-4.1.

The default model name 'gpt-4.1' appears to be non-standard. OpenAI typically uses model names like gpt-4, gpt-4-turbo, gpt-4o, etc. This could lead to API errors if used with the official OpenAI API.

Please verify that gpt-4.1 is a valid model name:

What are the current available OpenAI GPT-4 model names and is "gpt-4.1" a valid model?

If this is intended for a custom server, consider using a more standard default or adding validation to ensure the model name is appropriate for the configured endpoint.

Comment on lines 34 to 41
const model = new ChatOpenAI({
apiKey: process.env.OPENAI_API_KEY || 'sk-proj-',
model: 'gpt-4.1',
model: process.env.OPENAI_TEXT_MODEL || 'gpt-4.1',
temperature: 0.7,
});

const dalle = new DallEAPIWrapper({
apiKey: process.env.OPENAI_API_KEY || 'sk-proj-',
model: 'gpt-image-1',
model: process.env.OPENAI_IMAGE_MODEL || 'gpt-image-1',
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix invalid model names in both ChatOpenAI and DallEAPIWrapper.

Both fallback model names are invalid:

  1. 'gpt-4.1' is not a valid OpenAI text model
  2. 'gpt-image-1' is not a valid OpenAI image model and inconsistent with other files that use 'dall-e-3'

Apply this diff to use valid model names:

-  model:  process.env.OPENAI_TEXT_MODEL || 'gpt-4.1',
+  model: process.env.OPENAI_TEXT_MODEL || 'gpt-4',
-  model: process.env.OPENAI_IMAGE_MODEL || 'gpt-image-1',
+  model: process.env.OPENAI_IMAGE_MODEL || 'dall-e-3',
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const model = new ChatOpenAI({
apiKey: process.env.OPENAI_API_KEY || 'sk-proj-',
model: 'gpt-4.1',
model: process.env.OPENAI_TEXT_MODEL || 'gpt-4.1',
temperature: 0.7,
});
const dalle = new DallEAPIWrapper({
apiKey: process.env.OPENAI_API_KEY || 'sk-proj-',
model: 'gpt-image-1',
model: process.env.OPENAI_IMAGE_MODEL || 'gpt-image-1',
});
const model = new ChatOpenAI({
model: process.env.OPENAI_TEXT_MODEL || 'gpt-4',
temperature: 0.7,
});
const dalle = new DallEAPIWrapper({
model: process.env.OPENAI_IMAGE_MODEL || 'dall-e-3',
});
🤖 Prompt for AI Agents
In libraries/nestjs-libraries/src/database/prisma/autopost/autopost.service.ts
between lines 34 and 41, the fallback model names for ChatOpenAI and
DallEAPIWrapper are invalid. Replace 'gpt-4.1' with a valid OpenAI text model
name such as 'gpt-4', and replace 'gpt-image-1' with the consistent and valid
image model name 'dall-e-3' to align with other files.

Copy link
Collaborator

@egelhaus egelhaus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You forgot to use an API Key in the OpenAI API requests, correct me if I'm wrong please.

@philippderdiedas
Copy link
Author

philippderdiedas commented Jun 20, 2025

maintainer, i see there were some inconsistencies with some model names, was this intended?

Copy link
Collaborator

@egelhaus egelhaus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Above

@egelhaus
Copy link
Collaborator

@maintainer, i see there were some inconsistencies with some model names, was this intended?

You pinged a random person right now, @nevo-david is the right person

@egelhaus egelhaus requested a review from nevo-david June 20, 2025 17:23
@philippderdiedas
Copy link
Author

philippderdiedas commented Jun 20, 2025

You forgot to use an API Key in the OpenAI API requests, correct me if I'm wrong please.

well the readme of the openai-node package states that it the fallback for an undefined apiKey is the env variable
see

and here the code which does that.

or did you mean something else?

Copy link
Collaborator

@egelhaus egelhaus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, I see that this is in fact true, but please reimplement it just in case something goes wrong

@susesKaninchen
Copy link

Any updates?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: feature-request New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support custom openAI endpoints for AI selfhosters
3 participants