An open API service indexing awesome lists of open source software.

https://github.com/spfunctions/langchain-prediction-markets

LangChain adapter for SimpleFunctions prediction-market context: world state, uncertainty, edges, and market reads.
https://github.com/spfunctions/langchain-prediction-markets

agent-context ai-agents framework-adapter kalshi langchain polymarket prediction-markets

Last synced: 14 days ago
JSON representation

LangChain adapter for SimpleFunctions prediction-market context: world state, uncertainty, edges, and market reads.

Awesome Lists containing this project

README

          

# langchain-prediction-markets

[![npm](https://img.shields.io/npm/v/langchain-prediction-markets)](https://www.npmjs.com/package/langchain-prediction-markets)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

LangChain tools for **real-time prediction market data**. Drop-in tools that give any
LangChain agent (`createReactAgent`, `createOpenAIToolsAgent`, custom chains) world
awareness from the active Kalshi and Polymarket market universe — no auth required.

```ts
import { ChatOpenAI } from '@langchain/openai'
import { createReactAgent } from '@langchain/langgraph/prebuilt'
import { predictionMarketTools } from 'langchain-prediction-markets'

const agent = createReactAgent({
llm: new ChatOpenAI({ model: 'gpt-4o' }),
tools: predictionMarketTools(),
})

const result = await agent.invoke({
messages: [{ role: 'user', content: "What's the highest-conviction trade idea right now?" }],
})
```

---

## Install

```bash
npm install langchain-prediction-markets @langchain/core
```

Peer dep: `@langchain/core >= 0.2.0`. Works with all LangChain JS chat models
(`@langchain/openai`, `@langchain/anthropic`, `@langchain/google-genai`, etc.).

## Tools

All six tools hit the public SimpleFunctions API. **No API key, no rate limit, no
auth.** Every endpoint below is verified live.

| Tool | Endpoint | When to use |
|------|----------|-------------|
| `get_context` | `/api/public/context` | **Start here.** Single bundle: edges, movers, highlights, traditional-market context. |
| `get_world_state` | `/api/agent/world` | ~800-token compressed snapshot of all markets, ideal for system-prompt injection. |
| `get_world_changes` | `/api/agent/world/delta` | ~30-50 token incremental delta — cheap polling loops. |
| `get_market_edges` | `/api/edges` | Raw mispricings (thesis price vs market price) with reasoning. |
| `get_uncertainty_index` | `/api/public/index` | Single numeric pulse: uncertainty, geopolitical risk, momentum, activity. |
| `get_ideas` | `/api/public/ideas` | LLM-generated trade ideas with conviction, catalyst, time horizon. |

## Quick start: ReAct agent

```ts
import { ChatAnthropic } from '@langchain/anthropic'
import { createReactAgent } from '@langchain/langgraph/prebuilt'
import { predictionMarketTools } from 'langchain-prediction-markets'

const agent = createReactAgent({
llm: new ChatAnthropic({ model: 'claude-sonnet-4-5' }),
tools: predictionMarketTools(),
stateModifier:
'You are a market intelligence assistant. Use the tools to ground every claim in real-time prediction-market data. Cite tickers explicitly.',
})

const result = await agent.invoke({
messages: [{ role: 'user', content: 'What changed in markets in the last 6 hours?' }],
})
console.log(result.messages.at(-1)?.content)
```

## Use individual tools in a custom chain

```ts
import { getContext, getMarketEdges } from 'langchain-prediction-markets'
import { ChatOpenAI } from '@langchain/openai'

const llm = new ChatOpenAI({ model: 'gpt-4o' }).bindTools([getContext, getMarketEdges])

const out = await llm.invoke('Show me the open edges right now.')
for (const call of out.tool_calls ?? []) {
if (call.name === 'get_market_edges') {
const edges = await getMarketEdges.invoke(call.args)
console.log(edges)
}
}
```

## Direct invocation (no LangChain agent)

Every tool is a standard LangChain `tool` — you can call `.invoke()` directly:

```ts
import { getUncertaintyIndex, getIdeas } from 'langchain-prediction-markets'

const index = JSON.parse(await getUncertaintyIndex.invoke({}))
console.log(`Uncertainty: ${index.uncertainty}/100`)

const { ideas } = JSON.parse(await getIdeas.invoke({}))
console.log(`Top idea: ${ideas[0].headline}`)
```

## Response shapes

Tools return **JSON-stringified** payloads (LangChain expects string outputs).
`get_world_state` and `get_world_changes` return raw markdown strings.

### `get_context`
```ts
{
edges: Edge[]
movers: Mover[]
highlights: Highlight[]
traditionalMarkets: { [topic: string]: TraditionalMarket[] }
}
```

### `get_uncertainty_index`
```ts
{
uncertainty: number // 0-100
geopolitical: number // 0-100
momentum: number // -1 to +1
activity: number // 0-100
components: { medianSpread: number; avgSpread: number; ... }
timestamp: string
}
```

### `get_market_edges`
```ts
{
edges: {
ticker: string
venue: 'kalshi' | 'polymarket'
title: string
marketPrice: number
thesisPrice: number
executableEdge: number
confidence: number
liquidityScore: 'high' | 'medium' | 'low'
direction: 'yes' | 'no'
reasoning: string
}[]
}
```

### `get_ideas`
```ts
{
generatedAt: string
cached: boolean
ideas: {
headline: string
pitch: string
conviction: 'high' | 'medium' | 'low'
direction: 'buy_yes' | 'buy_no'
markets: { url: string; ticker: string; currentPrice: number; venue: string }[]
catalyst: string
timeHorizon: string
risk: string
}[]
}
```

## Errors

All tools throw `Error("SimpleFunctions API error for ")` on non-2xx
responses. LangChain agents will see the error string in the tool message and can
retry or recover.

## Sister packages

If you're not on LangChain, use the wrapper for your stack:

| Stack | Package |
|-------|---------|
| Vercel AI SDK | [`vercel-ai-prediction-markets`](https://github.com/spfunctions/vercel-ai-prediction-markets) |
| OpenAI Agents SDK / function calling | [`openai-agents-prediction-markets`](https://github.com/spfunctions/openai-agents-prediction-markets) |
| CrewAI (Python) | [`crewai-prediction-markets`](https://github.com/spfunctions/crewai-prediction-markets) |
| MCP / Claude / Cursor | [`simplefunctions-cli`](https://github.com/spfunctions/simplefunctions-cli) |
| Bare Python SDK | [`simplefunctions-python`](https://github.com/spfunctions/simplefunctions-python) |

## Testing

```bash
npm test
```

12 tests, all `fetch`-mocked — no network required.

## License

MIT — built by [SimpleFunctions](https://simplefunctions.dev).