Overview
The Conversations API enables you to create AI-powered conversations about your codebase. Each conversation can:
Use multiple AI agents specialized for different tasks
Reference multiple projects (codebases)
Stream responses in real-time
Maintain conversation history
Include images and code references
Create Conversation
Create a new conversation to start interacting with your codebase.
curl -X POST https://api.potpie.ai/api/v1/conversations/ \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"user_id": "user_01HQXYZ789",
"title": "Understanding React hooks",
"status": "active",
"project_ids": ["proj_01HQXYZ789ABCDEF"],
"agent_ids": ["codebase_qna_agent"]
}'
Request Body
ID of the user creating the conversation
Conversation title for easy identification
Conversation status: active or archived
Array of project IDs to include in the conversation (minimum 1)
Array of agent IDs to use (minimum 1). Available agents:
codebase_qna_agent: General questions about code
debugging_agent: Debug issues
code_generation_agent: Generate code
blast_radius_agent: Analyze change impact
Query Parameters
Whether to hide this conversation from the web UI
Response
{
"message" : "Conversation created successfully" ,
"conversation_id" : "conv_01HQXYZ789ABCDEF"
}
Post Message
Send a message to an AI agent in a conversation with optional streaming.
cURL (Streaming)
Python (Streaming)
Python (Non-streaming)
TypeScript (Streaming)
curl -X POST https://api.potpie.ai/api/v1/conversations/conv_123/message/ \
-H "Authorization: Bearer YOUR_TOKEN" \
-F "content=How does the authentication system work?" \
--no-buffer
Path Parameters
Unique identifier of the conversation
Query Parameters
Whether to stream the response using Server-Sent Events (SSE)
Session ID for reconnection (optional)
Previous human message ID for deterministic session ID
Stream cursor for replay from specific position
Request Body (multipart/form-data)
Message content to send to the agent (minimum 1 character)
JSON string array of node contexts to reference Example: [{"node_id": "node_123", "name": "AuthService"}]
Optional images to attach (max 10MB per image, up to 10 images)
Streaming Response (SSE)
When stream=true, responses are sent as Server-Sent Events:
data: {"type": "token", "content": "The"}
data: {"type": "token", "content": " authentication"}
data: {"type": "token", "content": " system"}
data: {"type": "citation", "data": {"file": "auth.py", "line": 42}}
data: {"type": "done", "message_id": "msg_123"}
Event Types
token: Incremental text content
citation: Source code reference
tool_call: AI agent using a tool
done: Message complete
error: Error occurred
Non-streaming Response
When stream=false:
{
"id" : "msg_01HQXYZ789ABCDEF" ,
"conversation_id" : "conv_01HQXYZ789ABCDEF" ,
"content" : "The authentication system uses JWT tokens..." ,
"sender_id" : null ,
"type" : "ai" ,
"created_at" : "2024-01-15T10:35:00Z" ,
"status" : "ready" ,
"citations" : [ "src/auth/middleware.py:42" ],
"has_attachments" : false
}
Create Conversation and Message (API v2)
Convenience endpoint that creates a conversation and sends a message in one request. Perfect for quick queries.
curl -X POST https://api.potpie.ai/api/v2/project/proj_123/message/ \
-H "x-api-key: YOUR_API_KEY" \
-H "x-user-id: YOUR_USER_ID" \
-H "Content-Type: application/json" \
-d '{
"content": "Explain the database schema",
"agent_id": "codebase_qna_agent"
}'
Path Parameters
ID of the project to query
Query Parameters
Whether to hide the auto-created conversation from the web UI
Request Body
Message content / question
Specific agent to use (defaults to codebase_qna_agent)
Optional array of code nodes to reference
Using a Custom Agent
Execute a custom agent by passing its ID through the standard v2 conversation flow. Authentication uses an API key via the x-api-key header.
Create a conversation
Initialize a conversation with your custom agent ID and the target project. Endpoint: POST /api/v2/conversations/Headers: x-api-key: your_api_key_here
Request: {
"project_ids" : [ "your_project_id" ],
"agent_ids" : [ "your_custom_agent_id" ]
}
Response: {
"message" : "Conversation created successfully" ,
"conversation_id" : "conv_01HQXYZ789ABCDEF"
}
Send a message
Submit a query to the agent. The agent executes its configured tasks using the assigned tools and returns a response with citations. Endpoint: POST /api/v2/conversations/{conversation_id}/message/Headers: x-api-key: your_api_key_here
Request: {
"content" : "Your query for the custom agent"
}
Query Parameters:
stream (boolean, default: true): Set to false to receive the full response as a single JSON object.
Custom agent IDs are UUIDs returned when the agent is created. To find your agent ID, retrieve the agent from your account settings or the agent management interface.
List Conversations
Get a paginated list of conversations with sorting options.
curl -X GET "https://api.potpie.ai/api/v1/conversations/?start=0&limit=10&sort=updated_at&order=desc" \
-H "Authorization: Bearer YOUR_TOKEN"
Query Parameters
Offset for pagination (0-indexed)
Maximum number of conversations to return (1-100)
sort
string
default: "updated_at"
Field to sort by: updated_at or created_at
Sort direction: asc or desc
Response
[
{
"id" : "conv_01HQXYZ789ABCDEF" ,
"title" : "Understanding React hooks" ,
"status" : "active" ,
"project_ids" : [ "proj_01HQXYZ789ABCDEF" ],
"agent_ids" : [ "codebase_qna_agent" ],
"created_at" : "2024-01-15T10:30:00Z" ,
"updated_at" : "2024-01-15T14:25:00Z" ,
"total_messages" : 12
}
]
Advanced Features
Attaching Images
Send images for visual context (screenshots, diagrams, etc.):
import requests
def post_message_with_image ( conversation_id : str , message : str , image_path : str , token : str ):
url = f "https://api.potpie.ai/api/v1/conversations/ { conversation_id } /message/"
with open (image_path, 'rb' ) as image_file:
files = {
'content' : ( None , message),
'images' : ( 'screenshot.png' , image_file, 'image/png' )
}
response = requests.post(
url,
files = files,
headers = { "Authorization" : f "Bearer { token } " },
params = { "stream" : "false" }
)
return response.json()
Referencing Code Nodes
Reference specific code elements in your message:
import json
node_ids = [
{ "node_id" : "node_auth_123" , "name" : "AuthService" },
{ "node_id" : "node_auth_456" , "name" : "authenticate_user" }
]
files = {
'content' : ( None , 'Explain how these work together' ),
'node_ids' : ( None , json.dumps(node_ids))
}
Session Management
Resume interrupted streaming sessions:
# Initial request
response = requests.post(url, files = files, params = {
"stream" : "true" ,
"prev_human_message_id" : "msg_previous_123"
})
# If connection drops, resume with cursor
response = requests.post(url, files = files, params = {
"stream" : "true" ,
"session_id" : "session_123" ,
"cursor" : "1-0" # Resume from specific position
})
Examples
Complete Conversation Flow
import requests
import json
class PotpieConversation :
def __init__ ( self , token : str ):
self .token = token
self .base_url = "https://api.potpie.ai/api/v1"
def create ( self , project_id : str , title : str , agent_id : str = "codebase_qna_agent" ):
"""Create a new conversation"""
response = requests.post(
f " { self .base_url } /conversations/" ,
headers = {
"Authorization" : f "Bearer { self .token } " ,
"Content-Type" : "application/json"
},
json = {
"user_id" : "user_01HQXYZ789" ,
"title" : title,
"status" : "active" ,
"project_ids" : [project_id],
"agent_ids" : [agent_id]
}
)
data = response.json()
return data[ 'conversation_id' ]
def send_message ( self , conversation_id : str , message : str ):
"""Send a message and get response"""
response = requests.post(
f " { self .base_url } /conversations/ { conversation_id } /message/" ,
files = { 'content' : ( None , message)},
headers = { "Authorization" : f "Bearer { self .token } " },
params = { "stream" : "false" }
)
return response.json()
# Usage
chat = PotpieConversation( "YOUR_TOKEN" )
# Create conversation
conv_id = chat.create( "proj_01HQXYZ789ABCDEF" , "Auth System Q&A" )
# Ask questions
answer1 = chat.send_message(conv_id, "How does login work?" )
print (answer1[ 'content' ])
answer2 = chat.send_message(conv_id, "What about password reset?" )
print (answer2[ 'content' ])
Streaming Chat UI
async function streamingChat ( conversationId : string , message : string , token : string ) {
const formData = new FormData ();
formData . append ( 'content' , message );
const response = await fetch (
`https://api.potpie.ai/api/v1/conversations/ ${ conversationId } /message/?stream=true` ,
{
method: 'POST' ,
headers: { 'Authorization' : `Bearer ${ token } ` },
body: formData
}
);
const reader = response . body ! . getReader ();
const decoder = new TextDecoder ();
let buffer = '' ;
while ( true ) {
const { done , value } = await reader . read ();
if ( done ) break ;
buffer += decoder . decode ( value , { stream: true });
const lines = buffer . split ( ' \n ' );
buffer = lines . pop () || '' ;
for ( const line of lines ) {
if ( line . startsWith ( 'data: ' )) {
const event = JSON . parse ( line . slice ( 6 ));
switch ( event . type ) {
case 'token' :
// Append to UI
appendToUI ( event . content );
break ;
case 'citation' :
// Show citation
showCitation ( event . data );
break ;
case 'done' :
// Finalize
finishMessage ( event . message_id );
break ;
case 'error' :
// Handle error
handleError ( event . data );
break ;
}
}
}
}
}
Error Handling
Common errors and how to handle them:
try :
response = requests.post(url, files = files, headers = headers)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 400 :
# Empty message or invalid parameters
print ( "Invalid message content" )
elif e.response.status_code == 402 :
# Subscription required
print ( "Upgrade subscription to continue" )
elif e.response.status_code == 404 :
# Conversation not found
print ( "Conversation does not exist" )
Best Practices
Use Streaming : Enable streaming for better UX
Reference Code : Include node_ids for context-aware responses
Handle Reconnections : Implement cursor-based resumption
Rate Limiting : Respect rate limits for your plan
Error Recovery : Handle network errors gracefully
Session Management : Use session_id for long conversations