Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

Setting Up Your TypeScript Project for LLM Development

Recommended resources

Hello! Welcome to the first lesson of your course on automating social media content.

This first module is all about laying a strong foundation. Today, we'll focus on the technical scaffolding for our project. By the end of this lesson, you will have a fully configured TypeScript project, complete with all the essential libraries we'll need to build our autonomous content agent. This is the first practical step toward your goal of building a system that can generate engaging content from your programming work.

We'll start with a high-level look at the architecture of an LLM agent before diving into the hands-on setup.

The Architecture of an AI Agent

Before we write any code, let's look at the big picture. The system we're building is more than just a simple script that calls an LLM. It's an agent that needs to interact with data sources, use tools, and be monitored.

LLM Agent Architecture with LangChain and Arize
This diagram shows the typical components of an LLM-powered agent. A user query is processed by an agent that uses an LLM and prompt templates. The agent can access external information from a vector store and use tools to perform actions. A monitoring system like LangSmith (similar to Arize shown here) tracks the agent's performance.

Given your background in designing scalable systems, you can think of this as our initial system design diagram. We have:

  • The Agent: The core logic, orchestrated by a framework.
  • The LLM: The "brain" of the operation (we'll use OpenAI's models).
  • Vector Store: A specialized database for storing and retrieving information based on semantic meaning. This will be crucial for identifying trends in Module 3.
  • Tools & Data Loaders: Functions that allow the agent to interact with the outside world, like fetching data from APIs or websites (which we'll build in Module 2).

For our project, we will use a specific set of technologies to implement this architecture. Let's briefly cover what they are and why they're necessary.


Your Core Technology Stack

To build a sophisticated, stateful agent, we need more than just direct calls to an LLM API. We need frameworks that can manage complexity, state, and tool usage.

  • LangChain: This is the foundational library for our AI development. It provides a universal interface to interact with various LLMs, document loaders (for parsing data from sources like RSS feeds or websites), and text splitters. It acts as the "glue" connecting all the different parts of our application.
  • LangGraph: This is an extension of LangChain designed for building complex, cyclical, and stateful agent workflows. A simple chain executes a linear sequence of steps. An agent, however, might need to call a tool, evaluate the result, call another tool, and loop this process until it has enough information. LangGraph allows us to define these workflows as graphs, which is essential for creating the autonomous system you envisioned.
  • Vector Database (Pinecone): To identify trends, our system will need to analyze large volumes of text. A vector database stores text as numerical representations (embeddings) and allows for incredibly fast semantic similarity searches. This enables us to find related articles and cluster emerging topics. We'll install the client library for Pinecone today.
  • LangSmith: In any complex system, observability is key. LangSmith is a platform for debugging, testing, evaluating, and monitoring LLM applications. It gives you a detailed trace of every step your agent takes—which LLMs were called, what tools were used, and what the inputs and outputs were. This is invaluable for troubleshooting the non-deterministic nature of LLM agents.

Now, let's get our hands dirty and set up the project.


Step 1: Project Initialization and TypeScript Configuration

First, create a new directory for your project and initialize it with npm.

mkdir social-media-agent
cd social-media-agent
npm init -y

Next, install TypeScript and create a tsconfig.json file.

npm install typescript @types/node ts-node --save-dev
npx tsc --init

Now, open tsconfig.json. This file controls how the TypeScript compiler behaves. For a robust project, we want to enable strict type-checking. This prevents common errors and improves code maintainability.

Core TypeScript Best Practices
These best practices, such as using strict type-checking and avoiding `any`, are fundamental for building scalable and maintainable TypeScript applications.

In your tsconfig.json, ensure the following options under compilerOptions are set. Most of them are default after tsc --init --strict, but it's good to double-check:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "./dist" // We'll compile our TS files to a 'dist' folder
  },
  "include": ["src/**/*"] // We will place our source code in a 'src' folder
}

This configuration ensures our project adheres to modern standards and catches potential issues early.


Step 2: Installing Core Dependencies

Our agent relies on several packages. Let's install them. The following list is derived from best practices for building agents with LangChain and LangGraph.

For a detailed breakdown of what each of these LangChain-related packages does, you can refer to the "Project Setup" section of the freeCodeCamp article "How to Build an AI Agent with LangChain and LangGraph".

How to Build an AI Agent with LangChain and LangGraph

This article provides a comprehensive list of the necessary packages for building a LangGraph agent. We'll use this as a reference for our dependencies.

Read the 'Project Setup' section, focusing on the list of tools and the explanation for each package like langchain/core, langchain/langgraph, and zod.

Run this command to install all the required production dependencies:

npm install @langchain/core @langchain/openai langchain @langchain/langgraph @pinecone-database/pinecone dotenv zod

Here’s a quick summary of the key players:

  • @langchain/core, langchain: The core LangChain libraries.
  • @langchain/openai: The specific package for interacting with OpenAI models.
  • @langchain/langgraph: For building our agentic workflow graph.
  • @pinecone-database/pinecone: The client for the Pinecone vector database.
  • dotenv: To manage environment variables (like API keys).
  • zod: For robust schema definition and data validation, which is critical when dealing with unpredictable LLM outputs.

Step 3: Setting Up Environment Variables

Your agent will need API keys to communicate with external services. We'll store these securely in an environment file.

Create a new file named .env in the root of your project.

.env

Now, add the following variables to this file. You will need to get these keys from their respective platforms.




# OpenAI API Key
OPENAI_API_KEY="sk-..."




# Pinecone API Key and Environment
PINECONE_API_KEY="..."
PINECONE_ENVIRONMENT="..."




# LangSmith API Key for tracing and observability
LANGCHAIN_TRACING_V2="true"
LANGCHAIN_API_KEY="ls__..."

Where to find these keys:

  1. OpenAI: Log in to your OpenAI account and navigate to the "API keys" section.
  2. Pinecone: Create a Pinecone account. Your API key and environment (e.g., gcp-starter) are available in your dashboard.
  3. LangSmith: Sign up for a free LangSmith account. Create a new project and generate an API key.

To see a visual walkthrough of finding and setting up these keys, you can refer to the following video.

Full Stack AI Semantic Search with Next.js, Pinecone, Langchain, & ChatGPT - Full TypeScript Course

This video provides a clear, practical demonstration of creating a project and setting up environment variables for OpenAI and Pinecone.

Watch from 05:07 to 06:51. This segment shows exactly where to find the API keys on the OpenAI and Pinecone websites and how to add them to your .env.local file (we're using .env).

Setting up LangSmith from the start will make debugging much easier later on, a practice you'll appreciate from your experience building and maintaining complex systems.


Step 4: Recommended Project Structure

A well-organized project is easier to maintain and scale. Based on official LangChain documentation and common TypeScript practices, I recommend the following structure.

social-media-agent/
├── src/
│   ├── index.ts        # Main entry point of the application
│   ├── agents/         # Logic for different content agents (e.g., LinkedIn, X)
│   ├── tools/          # Custom tools for the agent (e.g., web scraper)
│   └── utils/          # Utility functions
├── .env                # Environment variables
├── package.json
├── tsconfig.json

Create the src directory now and place an index.ts file inside it.
mkdir src && touch src/index.ts


Step 5: Verify Your Setup

Let's write a minimal script in src/index.ts to ensure everything is connected correctly. This script will load the environment variables and initialize the OpenAI client.

// src/index.ts

import { config } from 'dotenv';
import { ChatOpenAI } from '@langchain/openai';

// Load environment variables from .env file
config();

async function main() {
  console.log("Verifying project setup...");

  try {
    const model = new ChatOpenAI({
      model: "gpt-4o",
      // The API key is automatically read from the OPENAI_API_KEY environment variable
    });
    
    console.log("✅ OpenAI client initialized successfully.");

    // A simple test to confirm API connectivity
    const response = await model.invoke("Hello, world!");
    console.log("✅ Received response from OpenAI API.");
    console.log("Response:", response.content);

    console.log("\nProject setup is complete and working correctly!");

  } catch (error) {
    console.error("❌ An error occurred during verification:", error);
    if (error.message.includes('Incorrect API key')) {
      console.error("Please check if your OPENAI_API_KEY in the .env file is correct.");
    }
  }
}

main();

To run this file, you can use ts-node:

npx ts-node src/index.ts

If everything is configured correctly, you should see a series of success messages and a simple "Hello, world!" response from the AI.


Conclusion

Congratulations on completing the first lesson! You have successfully:

  • Outlined the high-level architecture for your content automation agent.
  • Initialized a professional TypeScript project with strict type-checking.
  • Installed the core dependencies, including LangChain, LangGraph, and the Pinecone client.
  • Configured your environment with the necessary API keys for OpenAI, Pinecone, and LangSmith.
  • Verified that your setup can successfully connect to the OpenAI API.

This technical foundation is the launchpad for everything we will build in the coming weeks.

Preview of the next lesson:
Now that our workshop is set up, our next step is to define the blueprint. In Lesson 2, we will shift our focus from code to strategy. We'll analyze examples of high-quality tech thought-leadership content to define the key characteristics of what we want our agent to produce. This will help us create a "brand voice" guide and establish clear, strategic goals for each social media platform.