xiaohongshu
xiaohongshu
integrate-openai-agents
This skill should be used when integrating OpenAI Agents SDK with FastAPI, building message arrays from database history, running agents with MCP tools, parsing tool calls, executing them, and saving conversations to the database.
Full skill instructions
This skill provides guidance for integrating OpenAI Agents SDK with FastAPI for chatbot functionality.
Build a stateless chat endpoint that:
Use this skill when:
/api/{user_id}/chat
├── Load conversation by ID (or create new)
├── Fetch message history from DB
├── Build message array for agent
├── Run agent with MCP tools
├── Parse tool_calls from agent response
├── Execute each tool call
├── Collect tool results
├── Return final response
└── Save all messages to DB
from openai import OpenAI
from agents import Agent, Runner
@app.post("/api/{user_id}/chat")
async def chat_endpoint(
user_id: str,
request: ChatRequest,
current_user: User = Depends(get_current_user)
):
conversation_id = request.conversation_id or str(uuid.uuid4())
# 1. Load conversation history
messages = await get_conversation_messages(conversation_id)
# 2. Build message array for agent
message_array = build_message_array(messages, request.message)
# 3. Run agent with tools
agent = Agent(
name="TaskAssistant",
model="gpt-4",
tools=[add_task, list_tasks, complete_task, delete_task, update_task]
)
result = Runner.run(agent, message_array)
# 4. Parse and execute tool calls (if any)
tool_outputs = []
for tool_call in result.tool_calls:
output = execute_tool(tool_call, user_id)
tool_outputs.append(output)
# 5. Save conversation to DB
await save_conversation(conversation_id, user_id, [
{"role": "user", "content": request.message},
{"role": "assistant", "content": result.final_output},
*tool_outputs
])
return {"conversation_id": conversation_id, "response": result.final_output}
def build_message_array(messages: list, user_message: str) -> list:
"""Build message array for agent from DB history."""
message_array = []
# Add system prompt
message_array.append({
"role": "system",
"content": "You are a helpful task assistant. Use tools when needed."
})
# Add historical messages
for msg in messages:
message_array.append({
"role": msg.role, # "user" or "assistant"
"content": msg.content
})
# Add current user message
message_array.append({
"role": "user",
"content": user_message
})
return message_array
async def execute_tool(tool_call: ToolCall, user_id: str) -> dict:
"""Execute a tool call and return structured result."""
tool_name = tool_call.name
tool_args = tool_call.arguments
tool_args["user_id"] = user_id # Inject user_id
# Route to appropriate tool
if tool_name == "add_task":
result = await add_task(**tool_args)
elif tool_name == "list_tasks":
result = await list_tasks(**tool_args)
# ... other tools
return {
"role": "assistant",
"content": f"Tool {tool_name} executed: {result}",
"tool_call_id": tool_call.id
}
class Conversation(SQLModel, table=True):
id: str = Field(primary_key=True)
user_id: str
created_at: datetime
updated_at: datetime
class Message(SQLModel, table=True):
id: int = Field(primary_key=True, autoincrement=True)
conversation_id: str = Field(foreign_key="conversation.id")
role: str # "user", "assistant", "tool"
content: str
tool_name: Optional[str] = None
tool_call_id: Optional[str] = None
created_at: datetime
class ChatRequest(BaseModel):
message: str
conversation_id: Optional[str] = None
class ChatResponse(BaseModel):
conversation_id: str
response: str
tool_calls: Optional[list[dict]] = None
openai>=1.0.0
agents>=0.1.0
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience