-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Add lmstudio for Node SDK #3482
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
parshvadaftari
wants to merge
5
commits into
main
Choose a base branch
from
user/parshva/lmstudio_typescript
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
import { Memory } from "../../src/memory"; | ||
import { MemoryConfig } from "../../src/types"; | ||
|
||
async function main() { | ||
// LMStudio configuration | ||
const config: MemoryConfig = { | ||
llm: { | ||
provider: "lmstudio", | ||
config: { | ||
model: "llama-3.2-1b-instruct", // or any model you have loaded in LMStudio | ||
baseUrl: "http://localhost:1234/v1", // default LMStudio server URL | ||
}, | ||
}, | ||
embedder: { | ||
provider: "openai", // You can use OpenAI embeddings or any other supported embedder | ||
config: { | ||
apiKey: process.env.OPENAI_API_KEY, | ||
model: "text-embedding-3-small", | ||
}, | ||
}, | ||
vectorStore: { | ||
provider: "memory", | ||
config: { | ||
collectionName: "lmstudio-memories", | ||
}, | ||
}, | ||
}; | ||
|
||
// Initialize Memory with LMStudio | ||
const memory = new Memory(config); | ||
|
||
const userId = "user-123"; | ||
|
||
try { | ||
// Add some memories | ||
console.log("Adding memories..."); | ||
await memory.add("I love playing guitar and listening to jazz music.", { | ||
userId, | ||
}); | ||
await memory.add("I work as a software engineer at a tech startup.", { | ||
userId, | ||
}); | ||
await memory.add("My favorite programming language is TypeScript.", { | ||
userId, | ||
}); | ||
|
||
// Search for memories | ||
console.log("\nSearching for music-related memories:"); | ||
const musicMemories = await memory.search("music", { userId }); | ||
console.log(musicMemories); | ||
|
||
console.log("\nSearching for work-related memories:"); | ||
const workMemories = await memory.search("work programming", { userId }); | ||
console.log(workMemories); | ||
|
||
// Get all memories | ||
console.log("\nAll memories:"); | ||
const allMemories = await memory.getAll({ userId }); | ||
console.log(allMemories); | ||
|
||
// Update a memory | ||
console.log("\nUpdating memory..."); | ||
await memory.add( | ||
"I recently started learning to play piano alongside guitar.", | ||
{ userId }, | ||
); | ||
|
||
// Search again to see updated results | ||
console.log("\nSearching for music after update:"); | ||
const updatedMusicMemories = await memory.search("music instruments", { | ||
userId, | ||
}); | ||
console.log(updatedMusicMemories); | ||
} catch (error) { | ||
console.error("Error:", error); | ||
} | ||
} | ||
|
||
// Run the example | ||
main().catch(console.error); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
import { LMStudioClient, Chat } from "@lmstudio/sdk"; | ||
import { LLM, LLMResponse } from "./base"; | ||
import { LLMConfig, Message } from "../types"; | ||
import { logger } from "../utils/logger"; | ||
|
||
export class LMStudioLLM implements LLM { | ||
private client: LMStudioClient; | ||
private model: string; | ||
private modelHandle: any; | ||
private initialized: boolean = false; | ||
|
||
constructor(config: LLMConfig) { | ||
this.client = new LMStudioClient({ | ||
baseUrl: | ||
config.config?.baseUrl || config.baseURL || "http://localhost:1234/v1", | ||
}); | ||
this.model = config.model || "llama-3.2-1b-instruct"; | ||
this.initializeModel(); | ||
} | ||
|
||
private async initializeModel(): Promise<void> { | ||
if (this.initialized) { | ||
return; | ||
} | ||
|
||
try { | ||
// Get the model handle from LMStudio client | ||
this.modelHandle = await this.client.llm.model(this.model); | ||
this.initialized = true; | ||
logger.info(`LMStudio model ${this.model} initialized successfully`); | ||
} catch (error) { | ||
logger.error(`Error initializing LMStudio model ${this.model}: ${error}`); | ||
throw error; | ||
} | ||
} | ||
|
||
async generateResponse( | ||
messages: Message[], | ||
responseFormat?: { type: string }, | ||
tools?: any[], | ||
): Promise<string | LLMResponse> { | ||
await this.initializeModel(); | ||
|
||
try { | ||
// Convert messages to LMStudio format | ||
const lmStudioMessages = messages.map((msg) => ({ | ||
role: msg.role as "system" | "user" | "assistant", | ||
content: | ||
typeof msg.content === "string" | ||
? msg.content | ||
: JSON.stringify(msg.content), | ||
})); | ||
|
||
// Create chat context | ||
const chat = Chat.from(lmStudioMessages); | ||
|
||
// Configure prediction parameters | ||
const predictionConfig: any = {}; | ||
|
||
if (responseFormat?.type === "json_object") { | ||
predictionConfig.structured = true; | ||
} | ||
|
||
// Tools are not directly supported in the same way as OpenAI | ||
// LMStudio may handle tool calls differently or not at all | ||
if (tools) { | ||
logger.warn( | ||
"Tool calls may not be fully supported by LMStudio integration", | ||
); | ||
} | ||
|
||
// Generate response | ||
const prediction = this.modelHandle.respond(chat, predictionConfig); | ||
let fullContent = ""; | ||
|
||
// Collect the streamed response | ||
for await (const { content } of prediction) { | ||
fullContent += content; | ||
} | ||
|
||
// For simple text responses | ||
if (!tools) { | ||
return fullContent; | ||
} | ||
|
||
// For tool calls (basic support) | ||
return { | ||
content: fullContent, | ||
role: "assistant", | ||
toolCalls: [], // LMStudio may not support tool calls in the same format | ||
}; | ||
} catch (error) { | ||
logger.error(`Error generating response with LMStudio: ${error}`); | ||
throw error; | ||
} | ||
} | ||
|
||
async generateChat(messages: Message[]): Promise<LLMResponse> { | ||
await this.initializeModel(); | ||
|
||
try { | ||
// Convert messages to LMStudio format | ||
const lmStudioMessages = messages.map((msg) => ({ | ||
role: msg.role as "system" | "user" | "assistant", | ||
content: | ||
typeof msg.content === "string" | ||
? msg.content | ||
: JSON.stringify(msg.content), | ||
})); | ||
|
||
// Create chat context | ||
const chat = Chat.from(lmStudioMessages); | ||
|
||
// Generate response | ||
const prediction = this.modelHandle.respond(chat); | ||
let fullContent = ""; | ||
|
||
// Collect the streamed response | ||
for await (const { content } of prediction) { | ||
fullContent += content; | ||
} | ||
|
||
return { | ||
content: fullContent, | ||
role: "assistant", | ||
}; | ||
} catch (error) { | ||
logger.error(`Error generating chat response with LMStudio: ${error}`); | ||
throw error; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.