Thanks to visit codestin.com
Credit goes to github.com

Skip to content

AI Agent API built with LangChain, OpenAI, and Redis. Supports tool integration, chat history, RESTful endpoints, and token usage tracking

Notifications You must be signed in to change notification settings

rustammdev/Langchain

Repository files navigation

๐Ÿค– LangChain Agent API

This project is an AI Agent API built using LangChain and OpenAI.
The agent can work with various tools and keeps chat history with users.

โœจ Features

  • ๐Ÿง  Works with OpenAI GPT models
  • ๐Ÿ”ง Tool system โ€“ perform different tasks
  • ๐Ÿ’พ Stores chat history via Redis
  • ๐ŸŒ RESTful API for easy integration
  • ๐Ÿ—๏ธ Clean Architecture โ€“ clear and extensible code
  • ๐Ÿ“Š Token usage tracking โ€“ monitor costs

๐Ÿ› ๏ธ Available Tools

  1. โฐ Time Tool โ€“ get the current time
  2. ๐Ÿ” ChromaDB Search โ€“ semantic search in PDF documents
  3. ๐ŸŒ DuckDuckGo Search โ€“ internet search
  4. ๐Ÿ“š Wikipedia Search โ€“ search on Wikipedia
  5. ๐Ÿ“ก Web Scraper โ€“ fetch data from URLs
  6. ๐Ÿงฎ Calculator โ€“ perform mathematical operations

๐Ÿš€ Installation & Running

Requirements

  • Node.js 18+
  • Redis server
  • OpenAI API key

1. Clone the repository

git clone <repository-url>
cd langchain-agent-api

2. Install dependencies

npm install

3. Configure environment variables

Create a .env file and add the following:

# Basic settings
PORT=3000
NODE_ENV=development

# API keys
OPENAI_API_KEY="your-openai-api-key"

# Redis
REDIS_URL=redis://localhost:6379

# Agent settings
CHAT_HISTORY_TTL=604800
MODEL=gpt-4o-mini-2024-07-18
TEMPERATURE=0.7

4. Start Redis

# With Docker
docker run -d -p 6379:6379 redis:alpine

# Or locally
redis-server

5. Run the project

# Development mode
npm run dev

# Build for production
npm run build

# Start production server
npm start

# Or with production environment
npm run start:prod

๐Ÿณ Docker Deployment

# Build Docker image
docker build -t langchain-agent-api .

# Run with Docker
docker run -p 3000:3000 --env-file .env langchain-agent-api

# Or use Docker Compose
docker-compose up -d

๐Ÿ“‹ API Endpoints

Chat Endpoints

Simple Chat

POST /ai/chat-with-memory/chat
Content-Type: application/json

{
  "userId": "user123",
  "input": "Hello, how can I help you?"
}

Chat with Agent (with Tools)

POST /ai/chat-with-memory/agent
Content-Type: application/json

{
  "userId": "user123",
  "input": "Tell me todayโ€™s weather",
  "agentType": "openai_tools",
  "enabledTools": ["duckduckgo_search", "get_current_time"]
}

Tool Management

List all tools

GET /ai/chat-with-memory/tools

Enable/Disable a tool

PUT /ai/chat-with-memory/tools/duckduckgo_search
Content-Type: application/json

{
  "enabled": true
}

History Management

Clear user history

DELETE /ai/chat-with-memory/history/user123

๐Ÿ—๏ธ Project Structure

src/
โ”œโ”€โ”€ agents/                     # Agents and tools
โ”‚   โ”œโ”€โ”€ tools/                  # Tool system
โ”‚   โ”‚   โ”œโ”€โ”€ base/               # Core interfaces
โ”‚   โ”‚   โ”œโ”€โ”€ implementations/    # Tool implementations
โ”‚   โ”‚   โ””โ”€โ”€ tool-registry.ts    # Tool registry
โ”‚   โ””โ”€โ”€ chat-with-memory/       # Chat agent
โ”‚       โ”œโ”€โ”€ controllers/        # HTTP controllers
โ”‚       โ”œโ”€โ”€ services/           # Business logic
โ”‚       โ”œโ”€โ”€ routes/             # API routes
โ”‚       โ”œโ”€โ”€ dto/                # Data transfer objects
โ”‚       โ””โ”€โ”€ storage/            # Data storage
โ”œโ”€โ”€ common/                     # Common utilities
โ”œโ”€โ”€ config/                     # Configuration
โ”œโ”€โ”€ v1/                         # API version
โ”œโ”€โ”€ app.ts                      # Express application
โ”œโ”€โ”€ server.ts                   # Server entry point
โ””โ”€โ”€ index.ts                    # Main file

๐Ÿ”ง Creating a Tool

To create a new tool:

  1. Create a new file in src/agents/tools/implementations/
  2. Implement the IToolService interface
  3. Register it in ToolRegistry

Example:

import { tool } from "@langchain/core/tools";
import { z } from "zod";
import type { IToolService } from "../base/tool.interface.js";

export class MyCustomToolService implements IToolService {
  readonly name = "my_custom_tool";
  readonly description = "My custom tool";

  createTool() {
    return tool(
      async (input: { param: string }): Promise<string> => {
        // Tool logic
        return `Result: ${input.param}`;
      },
      {
        name: this.name,
        description: this.description,
        schema: z.object({
          param: z.string()
        }),
      }
    );
  }
}

๐Ÿ› Debugging & Monitoring

Logs

The project provides debug information via console logs:

  • ๐Ÿš€ Server status
  • ๐Ÿค– Agent requests
  • ๐Ÿ”ง Tool activity
  • ๐Ÿ“Š Token statistics
  • โŒ Errors

Environment Variables

Extra debugging options:

AGENT_VERBOSE=true          # Agent debug logs
NODE_ENV=development        # Development mode

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/new-feature)
  3. Commit your changes (git commit -am 'Added new feature')
  4. Push the branch (git push origin feature/new-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is distributed under the MIT License.

๐Ÿ†˜ Help

If you have questions or need help:

  1. Create an issue on GitHub
  2. Carefully read the documentation
  3. Check the logs

Happy coding! ๐ŸŽ‰

About

AI Agent API built with LangChain, OpenAI, and Redis. Supports tool integration, chat history, RESTful endpoints, and token usage tracking

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published