@cogentic/core
v0.4.1
Published
TypeScript first Agent framework, providing type-safe interactions with models and runtime validation.
Readme
Cogentic AI
A TypeScript-first Agent framework. Stop wrestling with prompt engineering and response parsing – let Cogentic handle the heavy lifting.
Why Cogentic?
- Type-Safe Everything: From prompts to responses, every interaction is fully typed and validated
- Smart Memory Management: Automatically handles conversation history with configurable limits
- Tool Integration Made Easy: Add capabilities to your Agent with type-safe tools and automatic validation
- Cost Control: Track token usage and costs in real-time
- Production Ready: Built for performance, reliability, and maintainability
Quick Start
import { Agent } from "@cogentic/core";
// Create an agent with default settings
const agent = new Agent({
model: "gpt-4o-mini",
systemPrompt: "You are a helpful assistant",
});
// Run the agent and get the full response
const response = await agent.run("Hello!");
console.log("AI Response:", response.content);
console.log("Token Usage:", response.usage);
console.log("Cost:", response.cost.total_cost);
// Or destructure just what you need
const { content, usage } = await agent.run("What's the weather?");
console.log(content); // The AI's responseExamples
Hello World Example
The simplest way to get started is with our hello world example:
# Set your OpenAI API key
export OPENAI_API_KEY='your-api-key-here'
# Run the hello world example
bun examples/hello-world.tsThis will demonstrate a basic interaction with the AI model. The example code can be found in examples/hello-world.ts.
Features
Core Features ( Complete)
- Type-safe Agent implementation
- Runtime validation using Zod
- OpenAI integration with parsed responses
- Cost tracking and metrics
- System prompts
- Message history with configurable truncation
- Error handling and retries
- Comprehensive test suite
- Schema-based response parsing
- Tool integration with type safety
- Memory management with configurable limits
Tool Integration ( Complete)
- Basic tool registration and execution
- Tool call handling with OpenAI
- Tool validation and type safety
- Strict mode for tool execution
- Tool retry mechanisms
- Tool response format validation
- Automatic tool pair tracking
Coming Soon
- Open model support
- Enhanced system prompts with templates
- Dynamic context management
- Provider abstraction layer
- Advanced cost tracking
- Logging system
- Response streaming improvements
Basic Usage
Simple Chat
import { Agent } from "@cogentic/core";
// Create an agent with default settings
const agent = new Agent({
model: "gpt-4o-mini",
systemPrompt: "You are a helpful assistant",
});
// Run the agent and get the full response
const response = await agent.run("Hello!");
console.log("AI Response:", response.content);
console.log("Token Usage:", response.usage);
console.log("Cost:", response.cost.total_cost);
// Or destructure just what you need
const { content, usage } = await agent.run("What's the weather?");
console.log(content); // The AI's responseSchema Validation
Use Zod schemas to ensure type-safe responses with automatic parsing:
import { z } from "zod";
import { Agent } from "@cogentic/core";
// Define your response schema
const UserSchema = z.object({
name: z.string().describe("User's full name"),
age: z.number().min(0).max(120).describe("User's age in years"),
email: z.string().email().describe("User's email address"),
});
// Create an agent with schema validation
const agent = new Agent({
model: "gpt-4o-mini",
systemPrompt: "You are a helpful assistant",
responseSchema: UserSchema,
debug: true, // Enable debug logging
});
// Get a type-safe response that's automatically parsed
const { content: user } = await agent.run("Get info for John Doe");
console.log(user.name); // TypeScript knows this is a string
console.log(user.age); // TypeScript knows this is a number
console.log(user.email); // TypeScript knows this is a stringMemory Management
Configure memory limits and truncation behavior:
import { Agent } from "@cogentic/core";
const agent = new Agent({
model: "gpt-4o-mini",
systemPrompt: "You are a helpful assistant",
maxMemoryMessages: 100, // Keep last 100 messages
});
// First interaction
const { content: color } = await agent.run(
"What is the BEST color? Answer with one word."
);
// Agent remembers previous interaction
const { content: reason } = await agent.run("Why did you choose that color?");
// View full memory
console.log(agent.getMemory());Tool Integration
import { z } from "zod";
import { Agent } from "@cogentic/core";
// Define calculator tool with type-safe parameters
const calculatorTool = {
name: "calculator",
description: "Perform basic arithmetic operations",
parameters: z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
a: z.number(),
b: z.number(),
}),
function: async (args) => {
switch (args.operation) {
case "add":
return args.a + args.b;
case "subtract":
return args.a - args.b;
case "multiply":
return args.a * args.b;
case "divide":
return args.a / args.b;
}
},
};
// Define response schema for calculator results
const responseSchema = z.object({
explanation: z.string(),
result: z.number(),
});
const agent = new Agent({
model: "gpt-4o-mini",
systemPrompt: "You are a helpful math assistant",
tools: [calculatorTool],
responseSchema,
});
const { content } = await agent.run("What is 15 plus 27?");
console.log(`${content.explanation}\nResult: ${content.result}`);Cost Tracking
Track token usage and costs for each interaction:
const { content, usage, cost } = await agent.run("Hello!");
console.log(`Tokens used: ${JSON.stringify(usage)}`);
console.log(`Cost: $${cost.total_cost}`);Error Handling
try {
const result = await agent.run("Hello!");
} catch (error) {
if (error instanceof AgentError) {
console.error("Agent error:", error.message);
if (error.cause) {
console.error("Caused by:", error.cause);
}
}
}License
MIT
