# createAgent

> **Function** in `langchain`

📖 [View in docs](https://reference.langchain.com/javascript/langchain/index/createAgent)

Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools
and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively
work towards solutions.

The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively
work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state
across interactions, and provide auditable decision processes.

## Core Components

### Model
The reasoning engine can be specified as:
- **String identifier**: `"openai:gpt-4o"` for simple setup
- **Model instance**: Configured model object for full control
- **Dynamic function**: Select models at runtime based on state

### Tools
Tools give agents the ability to take actions:
- Pass an array of tools created with the `tool` function
- Or provide a configured `ToolNode` for custom error handling

### Prompt
Shape how your agent approaches tasks:
- String for simple instructions
- SystemMessage for structured prompts
- Function for dynamic prompts based on state

### Middleware
Middleware allows you to extend the agent's behavior:
- Add pre/post-model processing for context injection or validation
- Add dynamic control flows, e.g. terminate invocation or retries
- Add human-in-the-loop capabilities
- Add tool calls to the agent
- Add tool results to the agent

## Advanced Features

- **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses
- **Memory**: Extend the state schema to remember information across interactions
- **Streaming**: Get real-time updates as the agent processes

## Signature

```javascript
createAgent<StructuredResponseFormat extends Record<string, any> = Record<string, any>, TStateSchema extends StateDefinitionInit | undefined = undefined, ContextSchema extends InteropZodObject | AnyAnnotationRoot = AnyAnnotationRoot, TMiddleware extends readonly AgentMiddleware<any, any, any, readonly ClientTool | ServerTool[]>[] = readonly AgentMiddleware<any, any, any, readonly ClientTool | ServerTool[]>[], TTools extends readonly ClientTool | ServerTool[] = readonly ClientTool | ServerTool[], TStreamTransformers extends readonly () => StreamTransformer<any>[] = readonly []>(params: CreateAgentParams<StructuredResponseFormat, TStateSchema, ContextSchema, InteropZodType<StructuredResponseFormat>> & __type): ReactAgent<AgentTypeConfig<StructuredResponseFormat, TStateSchema, ContextSchema, TMiddleware, readonly [TTools, InferMiddlewareToolsArray<TMiddleware>], TStreamTransformers>>
```

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `params` | `CreateAgentParams<StructuredResponseFormat, TStateSchema, ContextSchema, InteropZodType<StructuredResponseFormat>> & __type` | Yes |  |

## Returns

`ReactAgent<AgentTypeConfig<StructuredResponseFormat, TStateSchema, ContextSchema, TMiddleware, readonly [TTools, InferMiddlewareToolsArray<TMiddleware>], TStreamTransformers>>`

A ReactAgent instance with `invoke` and `stream` methods

## Examples

### Example 1

```ts
import { createAgent, tool } from "langchain";
import { z } from "zod";

const search = tool(
  ({ query }) => `Results for: ${query}`,
  {
    name: "search",
    description: "Search for information",
    schema: z.object({
      query: z.string().describe("The search query"),
    })
  }
);

const agent = createAgent({
  llm: "openai:gpt-4o",
  tools: [search],
});

const result = await agent.invoke({
  messages: [{ role: "user", content: "Search for ReAct agents" }],
});
```

### Example 2

```ts
import { createAgent } from "langchain";
import { z } from "zod";

const ContactInfo = z.object({
  name: z.string(),
  email: z.string(),
  phone: z.string(),
});

const agent = createAgent({
  llm: "openai:gpt-4o",
  tools: [],
  responseFormat: ContactInfo,
});

const result = await agent.invoke({
  messages: [{
    role: "user",
    content: "Extract: John Doe, john@example.com, (555) 123-4567"
  }],
});

console.log(result.structuredResponse);
// { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }
```

### Example 3

```ts
const stream = await agent.stream(
  { messages: [{ role: "user", content: "What's the weather?" }] },
  { streamMode: "values" }
);

for await (const chunk of stream) {
  // ...
}
```

### Example 4

```ts
import { createAgent } from "langchain";
import { StateSchema, ReducedValue } from "@langchain/langgraph";
import { z } from "zod";

const AgentState = new StateSchema({
  userId: z.string(),
  count: z.number().default(0),
  history: new ReducedValue(
    z.array(z.string()).default(() => []),
    { inputSchema: z.string(), reducer: (c, n) => [...c, n] }
  ),
});

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [searchTool],
  stateSchema: AgentState,
});
```

---

[View source on GitHub](https://github.com/langchain-ai/langchainjs/blob/0c9440396c725d43b4758eb1b931c955e64ad8ec/libs/langchain/src/agents/index.ts#L172)