Skip to content

Instantly share code, notes, and snippets.

@muyiwexy
Created November 28, 2023 21:48
Show Gist options
  • Save muyiwexy/54045436d58e6ab667c213fc2377bf53 to your computer and use it in GitHub Desktop.
Save muyiwexy/54045436d58e6ab667c213fc2377bf53 to your computer and use it in GitHub Desktop.
class ProviderLocator {
// provider tree
static Future<MultiProvider> getProvider(Widget child) async {
final langchainService = await _createLangchainService();
return MultiProvider(
providers: [
Provider<LangchainService>.value(value: langchainService),
ChangeNotifierProvider<IndexNotifier>(
create: (_) => IndexNotifier(langchainService: langchainService),
),
],
child: child,
);
}
// langchain services function
static Future<LangchainService> _createLangchainService() async {
final connection = await createPostgresConnection();
final embeddings = await _createEmbeddings();
final openAI = await _createOpenAIConnection();
return LangchainServicesImpl(
connection: connection,
embeddings: embeddings,
openAI: openAI,
);
}
// postgres connection
static Future<Connection> createPostgresConnection() async {
const maxRetries = 3;
for (var retry = 0; retry < maxRetries; retry++) {
try {
final endpoint = Endpoint(
host: dotenv.env['PGHOST']!,
database: dotenv.env['PGDATABASE']!,
port: 5432,
username: dotenv.env['PGUSER']!,
password: dotenv.env['PGPASSWORD']!,
);
final connection = await Connection.open(
endpoint,
settings: ConnectionSettings(
sslMode: SslMode.verifyFull,
connectTimeout: const Duration(milliseconds: 20000),
),
);
if (connection.isOpen) {
if (kDebugMode) {
print("Connection Established!");
}
return connection;
}
} catch (e) {
if (kDebugMode) {
print('Error creating PostgreSQL connection: $e');
}
}
await Future.delayed(const Duration(seconds: 2));
}
// If maxRetries is reached and the connection is still not open, throw an exception
throw Exception(
'Failed to establish a PostgreSQL connection after $maxRetries retries');
}
// Lanchain openAI embeddings
static Future<OpenAIEmbeddings> _createEmbeddings() async {
return OpenAIEmbeddings(
apiKey: dotenv.env['OPENAI_API_KEY'],
model: "text-embedding-ada-002",
);
}
// openAi connection
static Future<OpenAI> _createOpenAIConnection() async {
return OpenAI(apiKey: dotenv.env['OPENAI_API_KEY']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment