iassafc / LangChainJSDotNet

⚡ A thin .NET wrapper around the official LangChain.js library⚡
MIT License
33 stars 2 forks source link

Program not work.... #128

Open hernanjls opened 2 months ago

hernanjls commented 2 months ago

Hi... I try to usage your lib in an console program... I receive this console errors

WARNING: [WARNING]: Importing from "langchain/load/serializable" is deprecated.

Instead, please import from "@langchain/core/load/serializable".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/base_language" is deprecated.

Instead, please import from "@langchain/core/language_models/base".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/serpapi" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/serpapi".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/dadjokeapi" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/dadjokeapi".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/bingserpapi" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/bingserpapi".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/ifttt" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/ifttt".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/serper" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/serper".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/google_custom_search" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/google_custom_search".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/aiplugin" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/aiplugin".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/brave_search" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/brave_search".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/wikipedia_query_run" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/wikipedia_query_run".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/wolframalpha" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/wolframalpha".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/dataforseo_api_search" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/dataforseo_api_search".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/searxng_search" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/searxng_search".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/searchapi" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/searchapi".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/tools/calculator" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/tools/calculator".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/prompts" is deprecated.

Instead, please import from "@langchain/core/prompts".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/embeddings/base" is deprecated.

Instead, please import from "@langchain/core/embeddings".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/embeddings/openai" is deprecated.

Instead, please add the "@langchain/openai" package to your project with e.g.

$ npm install @langchain/openai

and import from "@langchain/openai".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/embeddings/cohere" is deprecated.

Instead, please add the "@langchain/cohere" package to your project with e.g.

$ npm install @langchain/cohere

and import from "@langchain/cohere".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/base" is deprecated.

Instead, please import from "@langchain/core/language_models/llms".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/openai" is deprecated.

Instead, please add the "@langchain/openai" package to your project with e.g.

$ npm install @langchain/openai

and import from "@langchain/openai".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/ai21" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/llms/ai21".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/aleph_alpha" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/llms/aleph_alpha".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/cohere" is deprecated.

Instead, please add the "@langchain/cohere" package to your project with e.g.

$ npm install @langchain/cohere

and import from "@langchain/cohere".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/hf" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/llms/hf".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/ollama" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/llms/ollama".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/llms/replicate" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/llms/replicate".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/base" is deprecated.

Instead, please import from "@langchain/core/vectorstores".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/elasticsearch" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/elasticsearch".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/chroma" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/chroma".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/hnswlib" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/hnswlib".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/faiss" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/faiss".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/weaviate" is deprecated.

Instead, please add the "@langchain/weaviate" package to your project with e.g.

$ npm install @langchain/weaviate

and import from "@langchain/weaviate".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/lancedb" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/lancedb".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/mongodb_atlas" is deprecated.

Instead, please add the "@langchain/mongodb" package to your project with e.g.

$ npm install @langchain/mongodb

and import from "@langchain/mongodb".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/pinecone" is deprecated.

Instead, please add the "@langchain/pinecone" package to your project with e.g.

$ npm install @langchain/pinecone

and import from "@langchain/pinecone".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/supabase" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/supabase".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/prisma" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/prisma".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/typesense" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/typesense".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/vectorstores/vectara" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/vectorstores/vectara".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/document_transformers/html_to_text" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/document_transformers/html_to_text".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/chat_models/base" is deprecated.

Instead, please import from "@langchain/core/language_models/chat_models".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/chat_models/openai" is deprecated.

Instead, please add the "@langchain/openai" package to your project with e.g.

$ npm install @langchain/openai

and import from "@langchain/openai".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/chat_models/baiduwenxin" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/chat_models/baiduwenxin".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/chat_models/ollama" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/chat_models/ollama".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/schema" is deprecated.

Instead, please import from the appropriate entrypoint in "@langchain/core" or "langchain".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/schema/document" is deprecated.

Instead, please import from "@langchain/core/documents".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/schema/output_parser" is deprecated.

Instead, please import from "@langchain/core/output_parsers".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/schema/retriever" is deprecated.

Instead, please import from "@langchain/core/retrievers".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/schema/runnable" is deprecated.

Instead, please import from "@langchain/core/runnables".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/schema/storage" is deprecated.

Instead, please import from "@langchain/core/stores".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/callbacks" is deprecated.

Instead, please import from "@langchain/core/callbacks/base".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/callbacks/handlers/initialize" is deprecated.

Instead, please import from "@langchain/core/tracers/initialize".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/callbacks" is deprecated.

Instead, please import from "@langchain/core/callbacks/manager".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/retrievers/supabase" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/retrievers/supabase".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/retrievers/metal" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/retrievers/metal".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/retrievers/databerry" is deprecated.

Instead, please add the "@langchain/community" package to your project with e.g.

$ npm install @langchain/community

and import from "@langchain/community/retrievers/databerry".

This will be mandatory after the next "langchain" minor version bump to 0.2. WARNING: [WARNING]: Importing from "langchain/cache" is deprecated.

Instead, please import from "@langchain/core/caches".

This will be mandatory after the next "langchain" minor version bump to 0.2. Error al procesar la consulta: ReferenceError: GoogleGenerativeAI is not defined

=============================================================================================================================== the program usage this lib.....

namespace ConsoleApp.Services { public class LangChainService { private readonly DatabaseService _databaseService; private readonly string _apiKey;

    public LangChainService(DatabaseService databaseService, string apiKey)
    {
        _databaseService = databaseService;
        _apiKey = apiKey; // Consider using secure storage for API keys
    }

    public async Task<string> ProcessQueryAsync(string query)
    {
        var langchainjs = new LangChainJS();

        langchainjs.SetEnvironmentVariable("GOOGLE_API_KEY", _apiKey);

        // Configure LangChainJS with Gemini
        langchainjs.Setup(@"
        const model = new GoogleGenerativeAI();

        const tools = [
            new DynamicTool({
                name: 'ListProductsByCategory',
                description: 'List products by category. Input should be the category name.',
                func: async (parameters) => {
                    const category = parameters.category;
                    try {
                        const products = await listProductsByCategory(category);
                        return JSON.stringify(products);
                    } catch (error) {
                        return `Error: ${error.message}`;
                    }
                },
            }),
            new DynamicTool({
                name: 'AddToCart',
                description: 'Add a product to the cart. Input should be the product name and quantity.',
                func: async (parameters) => {
                    const productName = parameters.productName;
                    const quantity = parameters.quantity;
                    try {
                        await addToCart(productName, quantity);
                        return 'Product added to cart.';
                    } catch (error) {
                        return `Error: ${error.message}`;
                    }
                },
            }),
            new DynamicTool({
                name: 'ClearCart',
                description: 'Clear the shopping cart.',
                func: async () => {
                    try {
                        await clearCart();
                        return 'Shopping cart cleared.';
                    } catch (error) {
                        return `Error: ${error.message}`;
                    }
                },
            }),
            new DynamicTool({
                name: 'ListCartItems',
                description: 'List items in the shopping cart.',
                func: async () => {
                    try {
                        const items = await listCartItems();
                        return JSON.stringify(items);
                    } catch (error) {
                        return `Error: ${error.message}`;
                    }
                },
            }),
        ];

        globalThis.run = async (input) => {
            try {
                const executor = await initializeAgentExecutorWithOptions(tools, model, { agentType: 'structured-chat-zero-shot-react-description' });
                const result = await executor.call({ input });
                return result.output;
            } catch (error) {
                return `Error: ${error.message}`;
            }
        };
    ");

        try
        {
            var result = await langchainjs.InvokeAsync<string>("run", query);
            return result;
        }
        catch (Exception ex)
        {
            // Handle any exceptions thrown by LangChainJS
            return $"Error processing query: {ex.Message}";
        }
    }

    private async Task<string> listProductsByCategory(string category)
    {
        try
        {
            var products = await _databaseService.GetProductsByCategoryAsync(category);
            return JsonConvert.SerializeObject(products);
        }
        catch (Exception ex)
        {
            // Handle any exceptions thrown by the database service
            return $"Error retrieving products: {ex.Message}";
        }
    }

    private async Task addToCart(string productName, int quantity)
    {
        try
        {
            await _databaseService.AddToCartAsync(productName, quantity);
        }
        catch (Exception ex)
        {
            // Handle any exceptions thrown by the database service
            throw new Exception($"Error adding to cart: {ex.Message}", ex);
        }
    }

    private async Task clearCart()
    {
        try
        {
            await _databaseService.ClearCartAsync();
        }
        catch (Exception ex)
        {
            // Handle any exceptions thrown by the database service
            throw new Exception($"Error clearing cart: {ex.Message}", ex);
        }
    }

    private async Task<string> listCartItems()
    {
        try
        {
            var items = await _databaseService.GetCartItemsAsync();
            return JsonConvert.SerializeObject(items);
        }
        catch (Exception ex)
        {
            // Handle any exceptions thrown by the database service
            return $"Error retrieving cart items: {ex.Message}";
        }
    }
}

}

where ....

namespace ConsoleApp.Data { public class DatabaseService { private readonly string _connectionString;

    public DatabaseService(string dbPath)
    {
        _connectionString = $"Data Source={dbPath}";
        InitializeDatabaseAsync().Wait();
    }

    private async Task InitializeDatabaseAsync()
    {
        using var connection = new SqliteConnection(_connectionString);
        await connection.OpenAsync();

        // Create tables without transaction
        var tableCreationCommands = new[]
        {
            "CREATE TABLE IF NOT EXISTS Product (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Description TEXT, Price REAL, Category TEXT)",
            "CREATE TABLE IF NOT EXISTS ShoppingCartItem (Id INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT, Quantity INTEGER)"
        };

        foreach (var commandText in tableCreationCommands)
        {
            using var command = connection.CreateCommand();
            command.CommandText = commandText;
            await command.ExecuteNonQueryAsync();
        }

        //// Verify tables creation
        //var existingTables = await GetExistingTablesAsync(connection);

        //Console.WriteLine("Existing tables:");
        //foreach (var table in existingTables)
        //{
        //    //Console.WriteLine(table);
        //}

        // Use transaction for product insertion
        //using var transaction = connection.BeginTransaction();

        try
        {
            if (await GetProductsCountAsync() == 0)
            {
                var products = new List<Product>
                {
                    new Product { Id = 1, Name = "Zapatillas de Correr", Description = "Zapatillas cómodas para correr para hombres y mujeres.", Price = 120.00m, Category = "Calzado" },
                    new Product { Id = 2, Name = "Pantalones de Yoga", Description = "Pantalones de yoga elásticos adecuados para todo tipo de ejercicios.", Price = 60.00m, Category = "Ropa" },
                    new Product { Id = 3, Name = "Shorts de Gimnasio", Description = "Shorts transpirables para hombres.", Price = 30.00m, Category = "Ropa" },
                    new Product { Id = 4, Name = "Sujetador Deportivo", Description = "Sujetador deportivo de apoyo para mujeres.", Price = 40.00m, Category = "Ropa" },
                    new Product { Id = 5, Name = "Sudadera", Description = "Sudadera cálida y acogedora.", Price = 80.00m, Category = "Ropa" },
                    new Product { Id = 6, Name = "Chaqueta de Entrenamiento", Description = "Chaqueta ligera para todas las estaciones.", Price = 90.00m, Category = "Ropa" },
                    new Product { Id = 7, Name = "Calcetines de Correr", Description = "Calcetines de alto rendimiento para correr.", Price = 15.00m, Category = "Calzado" },
                    new Product { Id = 8, Name = "Reloj Deportivo", Description = "Rastrea tus objetivos de fitness con este rastreador avanzado.", Price = 150.00m, Category = "Accesorios" },
                    new Product { Id = 9, Name = "Botella de Agua", Description = "Botella de agua duradera para tus sesiones de entrenamiento.", Price = 20.00m, Category = "Accesorios" },
                    new Product { Id = 10, Name = "Bolsa de Gimnasio", Description = "Bolsa de gimnasio espaciosa con múltiples compartimentos.", Price = 70.00m, Category = "Accesorios" },
                    new Product { Id = 11, Name = "Zapatillas de Baloncesto", Description = "Zapatillas de baloncesto de caña alta con excelente soporte para los tobillos.", Price = 130.00m, Category = "Calzado" },
                    new Product { Id = 12, Name = "Shorts de Compresión", Description = "Shorts de compresión para mejorar el rendimiento.", Price = 45.00m, Category = "Ropa" },
                    new Product { Id = 13, Name = "Camiseta de Entrenamiento", Description = "Camiseta de entrenamiento que absorbe la humedad.", Price = 25.00m, Category = "Ropa" },
                    new Product { Id = 14, Name = "Gorra Deportiva", Description = "Gorra deportiva ajustable para protección solar.", Price = 18.00m, Category = "Accesorios" },
                    new Product { Id = 15, Name = "Pantalones de Chándal", Description = "Pantalones de chándal cómodos para uso casual.", Price = 50.00m, Category = "Ropa" },
                    new Product { Id = 16, Name = "Guantes para Levantamiento de Pesas", Description = "Guantes protectores para levantamiento de pesas.", Price = 35.00m, Category = "Accesorios" },
                    new Product { Id = 17, Name = "Gafas de Natación", Description = "Gafas de natación anti-vaho.", Price = 25.00m, Category = "Accesorios" },
                    new Product { Id = 18, Name = "Reloj Deportivo", Description = "Reloj deportivo avanzado con GPS.", Price = 200.00m, Category = "Accesorios" },
                    new Product { Id = 19, Name = "Esterilla de Yoga", Description = "Esterilla de yoga antideslizante para un mejor agarre.", Price = 40.00m, Category = "Accesorios" },
                    new Product { Id = 20, Name = "Guantes de Boxeo", Description = "Guantes de boxeo duraderos para entrenamientos intensos.", Price = 90.00m, Category = "Accesorios" }
                };

                foreach (var product in products)
                {
                    await InsertProductAsync(product);
                }
            }

            //await transaction.CommitAsync();
        }
        catch
        {
            //await transaction.RollbackAsync();
            throw;
        }
    }

    private async Task<List<string>> GetExistingTablesAsync(SqliteConnection connection)
    {
        var tables = new List<string>();

        using var command = connection.CreateCommand();
        command.CommandText = "SELECT name FROM sqlite_master WHERE type='table'";

        using var reader = await command.ExecuteReaderAsync();
        while (await reader.ReadAsync())
        {
            tables.Add(reader.GetString(0));
        }

        return tables;
    }

    private async Task<int> GetProductsCountAsync()
    {
        int ret = 0;

        using (var connection = new SqliteConnection(_connectionString))
        {
            await connection.OpenAsync();

            using var command = connection.CreateCommand();
            command.CommandText = "SELECT COUNT(*) FROM Product";
            ret = (int)(long)await command.ExecuteScalarAsync();
        }

        return ret;

    }

    public async Task<List<Product>> GetProductsByCategoryAsync(string category)
    {
        var products = new List<Product>();

        using (var connection = new SqliteConnection(_connectionString))
        {
            await connection.OpenAsync();

            using var command = connection.CreateCommand();
            command.CommandText = "SELECT * FROM Product WHERE Category = @Category";
            command.Parameters.AddWithValue("@Category", category);

            using var reader = await command.ExecuteReaderAsync();
            while (await reader.ReadAsync())
            {
                products.Add(new Product
                {
                    Id = reader.GetInt32(0),
                    Name = reader.GetString(1),
                    Description = reader.GetString(2),
                    Price = reader.GetDecimal(3),
                    Category = reader.GetString(4)
                });
            }
        }

        return products;
    }

    public async Task<int> AddToCartAsync(string productName, int quantity)
    {
        using (var connection = new SqliteConnection(_connectionString))
        {
            await connection.OpenAsync();

            using var command = connection.CreateCommand();
            command.CommandText = "INSERT INTO ShoppingCartItem (ProductName, Quantity) VALUES (@ProductName, @Quantity)";
            command.Parameters.AddWithValue("@ProductName", productName);
            command.Parameters.AddWithValue("@Quantity", quantity);

            return await command.ExecuteNonQueryAsync();
        }

    }

    public async Task<int> ClearCartAsync()
    {
        using (var connection = new SqliteConnection(_connectionString))
        {
            await connection.OpenAsync();

            using var command = connection.CreateCommand();
            command.CommandText = "DELETE FROM ShoppingCartItem";

            return await command.ExecuteNonQueryAsync();
        }

    }

    public async Task<List<ShoppingCartItem>> GetCartItemsAsync()
    {
        var items = new List<ShoppingCartItem>();

        using (var connection = new SqliteConnection(_connectionString))
        {
            await connection.OpenAsync();

            using var command = connection.CreateCommand();
            command.CommandText = "SELECT * FROM ShoppingCartItem";

            using var reader = await command.ExecuteReaderAsync();
            while (await reader.ReadAsync())
            {
                items.Add(new ShoppingCartItem
                {
                    Id = reader.GetInt32(0),
                    ProductName = reader.GetString(1),
                    Quantity = reader.GetInt32(2)
                });
            }

            return items;
        }

    }

    private async Task InsertProductAsync(Product product)
    {
        int retryCount = 3; // Número de intentos de reintentos
        TimeSpan delay = TimeSpan.FromSeconds(1); // Retraso entre reintentos

        for (int i = 0; i < retryCount; i++)
        {
            try
            {
                using (var connection = new SqliteConnection(_connectionString))
                {
                    await connection.OpenAsync();

                    using var command = connection.CreateCommand();
                    command.CommandText = "INSERT INTO Product (Id, Name, Description, Price, Category) VALUES (@Id, @Name, @Description, @Price, @Category)";
                    command.Parameters.AddWithValue("@Id", product.Id);
                    command.Parameters.AddWithValue("@Name", product.Name);
                    command.Parameters.AddWithValue("@Description", product.Description);
                    command.Parameters.AddWithValue("@Price", product.Price);
                    command.Parameters.AddWithValue("@Category", product.Category);

                    await command.ExecuteNonQueryAsync();
                    break; // Salir del bucle si es exitoso
                }

            }
            catch (SqliteException ex)
            {
                if (ex.SqliteErrorCode == 5) // Código de error para "database is locked"
                {
                    if (i == retryCount - 1) throw; // Volver a lanzar si es el último intento
                    await Task.Delay(delay); // Esperar antes de reintentar
                }
                else
                {
                    throw; // Volver a lanzar otras excepciones
                }
            }
        }
    }
}

 public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

public class ShoppingCartItem
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public int Quantity { get; set; }
}

}.....

And the console program is :

namespace ConsoleApp { class Program { static async Task Main(string[] args) { var dbPath = "products.db"; var apiKey = "my api key og gemini"; var databaseService = new DatabaseService(dbPath); var langChainService = new LangChainService(databaseService, apiKey);

        while (true)
        {
            Console.WriteLine("Introduce tu consulta:");
            var query = Console.ReadLine();

            if (string.IsNullOrEmpty(query))
            {
                break;
            }

            try
            {
                var response = await langChainService.ProcessQueryAsync(query);
                Console.WriteLine("Respuesta: ");
                Console.WriteLine(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error al procesar la consulta: " + ex.Message);
            }
        }
    }
}

}

hernanjls commented 2 months ago

Can you hep me to do work this script? I want try to usage your lib in my apps