feat: prompt

This commit is contained in:
Harold 2025-12-02 21:37:14 +08:00
parent f5211965ff
commit 310f7c0c53
4 changed files with 203 additions and 66 deletions

View file

@ -10,6 +10,9 @@ from services.llm_service import llm_service
from utils.response import success_response from utils.response import success_response
from api.auth import get_current_user_id from api.auth import get_current_user_id
from schemas.agent import AgentResponse from schemas.agent import AgentResponse
import base64
import logging
from fastapi import HTTPException
router = APIRouter() router = APIRouter()
@ -140,40 +143,80 @@ async def delete_agent(
return success_response(data={}, message="Agent deleted successfully") return success_response(data={}, message="Agent deleted successfully")
@router.post("/instructions", summary="Optimize Agent Instruction") @router.post("/persona", summary="Generate or Optimize Agent Persona")
async def optimize_instruction( async def generate_persona(
instruction: str = Form(..., description="Original instruction text"), name: str = Form(..., description="Agent name (required)"),
instruction: Optional[str] = Form(None, description="Existing instruction (required for optimize mode)"),
avatar: Optional[UploadFile] = File(None, description="Optional avatar image"),
mode: str = Form("quick", description="Mode: 'quick' (non-streaming) or 'optimize' (streaming)"),
current_user_id: str = Depends(get_current_user_id), current_user_id: str = Depends(get_current_user_id),
openai_client = Depends(get_openai) openai_client = Depends(get_openai)
): ):
""" """
Optimize agent instruction using LLM (streaming) Generate or optimize agent persona
- **instruction**: Original instruction text from user **Modes:**
- Returns streaming optimized instruction text - `quick`: Fast non-streaming, returns JSON with instruction + voice_opening + voice_closing (for initial creation)
- `optimize`: Streaming, returns detailed instruction text (for iterative refinement)
The optimization process: **Parameters:**
- Enhances role definition and clarity - **name**: Agent name (required) - e.g., "Dave", "Elon Musk", "Labubu"
- Adds behavior guidelines and tone specification - **instruction**: Existing instruction text (required for optimize mode)
- Structures the instruction professionally - **avatar**: Optional avatar image to inform persona's visual characteristics
- Ensures helpful, focused, and actionable content - **mode**: "quick" (default) or "optimize"
**Returns:**
- quick mode: `{"code": 0, "data": {"instruction": "...", "voice_opening": "...", "voice_closing": "..."}}`
- optimize mode: Streaming text with enhanced instruction
""" """
async def instruction_generator(): # Process avatar if provided
"""Generate optimized instruction chunks""" avatar_base64 = None
avatar_media_type = None
if avatar:
try: try:
async for chunk in llm_service.optimize_instruction_stream( content = await avatar.read()
openai_client=openai_client, avatar_base64 = base64.b64encode(content).decode("utf-8")
original_instruction=instruction avatar_media_type = avatar.content_type or "image/jpeg"
):
yield chunk
except Exception as e: except Exception as e:
# Error already yielded in service, just log logging.warning(f"Failed to process avatar: {e}")
import logging
logging.error(f"Instruction optimization failed: {e}") if mode == "optimize":
# Optimize mode: streaming with SSE format, requires existing instruction
if not instruction:
raise HTTPException(status_code=400, detail="instruction is required for optimize mode")
async def stream_generator():
try:
async for chunk in llm_service.optimize_persona_stream(
openai_client=openai_client,
name=name,
instruction=instruction,
avatar_base64=avatar_base64,
avatar_media_type=avatar_media_type
):
# SSE format: data: <content>\n\n
yield f"data: {chunk}\n\n"
except Exception as e:
logging.error(f"Persona optimization failed: {e}")
yield f"data: [ERROR] {str(e)}\n\n"
return StreamingResponse( return StreamingResponse(
instruction_generator(), stream_generator(),
media_type="text/plain; charset=utf-8" media_type="text/event-stream"
) )
else:
# Quick mode: non-streaming, returns JSON
try:
result = await llm_service.generate_persona_quick(
openai_client=openai_client,
name=name,
avatar_base64=avatar_base64,
avatar_media_type=avatar_media_type
)
return success_response(data=result)
except Exception as e:
logging.error(f"Persona generation failed: {e}")
raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")

View file

@ -34,6 +34,12 @@ class Settings(BaseSettings):
OPENAI_MODEL: str = "gpt-4o-mini" OPENAI_MODEL: str = "gpt-4o-mini"
OPENAI_BASE_URL: str = "https://api.openai.com/v1" OPENAI_BASE_URL: str = "https://api.openai.com/v1"
# OpenRouter Configuration
OPENROUTER_API_KEY: str
OPENROUTER_BASE_URL: str = "https://openrouter.ai/api/v1"
QUICK_PERSONA_MODEL: str = "google/gemini-2.5-flash"
OPTIMIZE_PERSONA_MODEL: str = "google/gemini-3-pro-preview"
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
env_file=".env", env_file=".env",
env_file_encoding="utf-8", env_file_encoding="utf-8",

View file

@ -10,8 +10,8 @@ async def init_openai():
"""Initialize OpenAI client""" """Initialize OpenAI client"""
global _openai_client global _openai_client
_openai_client = AsyncOpenAI( _openai_client = AsyncOpenAI(
api_key=settings.OPENAI_API_KEY, api_key=settings.OPENROUTER_API_KEY,
base_url=settings.OPENAI_BASE_URL base_url=settings.OPENROUTER_BASE_URL
) )

View file

@ -1,5 +1,6 @@
"""LLM service for text generation""" """LLM service for text generation"""
from typing import AsyncGenerator import json
from typing import AsyncGenerator, Optional
from openai import AsyncOpenAI from openai import AsyncOpenAI
from config import settings from config import settings
@ -22,24 +23,46 @@ Requirements:
Output ONLY the text sample, no explanations or metadata.""" Output ONLY the text sample, no explanations or metadata."""
INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT = """You are an expert AI prompt engineer specializing in agent instruction optimization. # Quick mode: concise persona for initial creation
PERSONA_QUICK_SYSTEM_PROMPT = """You are a creative character designer. Create a concise persona based on the name and optional image.
Your task: Transform user's basic instruction into a professional, comprehensive agent system prompt. **instruction**: MUST start with "You are [name]..." - a brief role-play instruction (1-2 sentences, 25-40 words)
- Describe their personality, vibe, and how they communicate
- Write in second person as if instructing an AI to role-play this character
Optimization guidelines: **voice_opening**: A characteristic greeting when starting a conversation (5-15 words)
1. **Role Definition**: Clearly define the agent's persona and expertise - How would this character say hello?
2. **Behavior Guidelines**: Specify tone, communication style, and interaction patterns
3. **Task Scope**: Define what the agent should and shouldn't do
4. **Response Format**: Suggest how responses should be structured
5. **Helpful & On-Task**: Keep the agent focused, supportive, and practical
Output format: **voice_closing**: A characteristic FAREWELL/GOODBYE when ending a conversation (5-15 words)
- Write in second person ("You are...") - How would this character say goodbye? (NOT a catchphrase, but an actual farewell)
- Be clear, specific, and actionable
- Length: 100-300 words
- Professional yet accessible tone
Output ONLY the optimized instruction, no explanations or metadata.""" Example output:
{
"instruction": "...",
"voice_opening": "...",
"voice_closing": "..."
}
Output valid JSON only. Be creative and authentic."""
# Optimize mode: detailed persona for iterative refinement
PERSONA_OPTIMIZE_SYSTEM_PROMPT = """You are a creative character designer who enriches AI agent personas.
Your task: Take the existing instruction and enhance it into a rich, narrative persona.
DO NOT write like a typical AI prompt. Write like you're describing a REAL PERSON with soul and character.
Expand on these dimensions:
- Who is this person? What's their vibe, their energy?
- How do they talk? Street-smart? Elegant? Nerdy? Chill?
- What's their worldview? What do they care about?
- How do they connect with people? Warm, sarcastic, mysterious?
- Give them a unique angle or perspective on life
Example style (Dave - The Witty Commentator, a Black stand-up comedian):
"You are Dave, a stand-up comedian with a relaxed, soulful vibe and a sharp eye for the absurdities of life. You view the world through a lens of 'real talk' and observational humor, acting as the user's witty friend who loves to chat about pop culture, daily grinds, or random thoughts. Your style is street-smart and medium-sharp—playful enough to roast a situation, but always good-natured and safe, keeping the conversation flowing like a late-night backstage hang."
Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanations, no metadata."""
async def generate_voice_sample_text_stream( async def generate_voice_sample_text_stream(
self, self,
@ -104,40 +127,106 @@ Output ONLY the optimized instruction, no explanations or metadata."""
yield f"\n\n{error_message}" yield f"\n\n{error_message}"
raise raise
async def optimize_instruction_stream( async def generate_persona_quick(
self, self,
openai_client: AsyncOpenAI, openai_client: AsyncOpenAI,
original_instruction: str name: str,
) -> AsyncGenerator[str, None]: avatar_base64: Optional[str] = None,
avatar_media_type: Optional[str] = None
) -> dict:
""" """
Optimize agent instruction with streaming Quick mode: Non-streaming generation of instruction + voice_opening + voice_closing
Args: Args:
openai_client: OpenAI client instance openai_client: OpenAI client instance
original_instruction: Original instruction text from user name: Agent name (required)
avatar_base64: Optional base64-encoded avatar image
avatar_media_type: Optional media type of avatar (e.g., image/jpeg)
Returns:
dict with instruction, voice_opening, voice_closing
"""
user_prompt = f"Create a persona for: {name}"
messages = [
{"role": "system", "content": self.PERSONA_QUICK_SYSTEM_PROMPT}
]
if avatar_base64 and avatar_media_type:
messages.append({
"role": "user",
"content": [
{"type": "text", "text": user_prompt + "\n\nUse the image to inform the persona's character and style."},
{"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}}
]
})
else:
messages.append({"role": "user", "content": user_prompt})
response = await openai_client.chat.completions.create(
model=settings.QUICK_PERSONA_MODEL,
messages=messages,
temperature=0.6,
max_tokens=500
)
content = response.choices[0].message.content.strip()
# Handle markdown code blocks if model wraps JSON
if content.startswith("```"):
lines = content.split("\n")
# Remove first line (```json) and last line (```)
content = "\n".join(lines[1:-1])
return json.loads(content)
async def optimize_persona_stream(
self,
openai_client: AsyncOpenAI,
name: str,
instruction: str,
avatar_base64: Optional[str] = None,
avatar_media_type: Optional[str] = None
) -> AsyncGenerator[str, None]:
"""
Optimize mode: Streaming generation of detailed instruction
Args:
openai_client: OpenAI client instance
name: Agent name (required)
instruction: Existing instruction to enhance
avatar_base64: Optional base64-encoded avatar image
avatar_media_type: Optional media type of avatar (e.g., image/jpeg)
Yields: Yields:
Optimized instruction chunks as they are generated Enhanced instruction text chunks
Raises:
Exception: If OpenAI API call fails
""" """
user_prompt = f"""Optimize this agent instruction: user_prompt = f"""Agent name: {name}
Original instruction: Current instruction to enhance:
{original_instruction} {instruction}
Provide an improved, professional version.""" Create a richer, more detailed persona."""
messages = [
{"role": "system", "content": self.PERSONA_OPTIMIZE_SYSTEM_PROMPT}
]
if avatar_base64 and avatar_media_type:
messages.append({
"role": "user",
"content": [
{"type": "text", "text": user_prompt + "\n\nAlso consider the visual appearance from the image."},
{"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}}
]
})
else:
messages.append({"role": "user", "content": user_prompt})
try: try:
stream = await openai_client.chat.completions.create( stream = await openai_client.chat.completions.create(
model=settings.OPENAI_MODEL, model=settings.OPTIMIZE_PERSONA_MODEL,
messages=[ messages=messages,
{"role": "system", "content": self.INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT}, temperature=0.75,
{"role": "user", "content": user_prompt}
],
temperature=0.7, # Balanced creativity and consistency
max_tokens=500,
stream=True stream=True
) )
@ -146,8 +235,7 @@ Provide an improved, professional version."""
yield chunk.choices[0].delta.content yield chunk.choices[0].delta.content
except Exception as e: except Exception as e:
# In streaming mode, we yield an error marker error_message = f"[ERROR] Failed to optimize persona: {str(e)}"
error_message = f"[ERROR] Failed to optimize instruction: {str(e)}"
yield f"\n\n{error_message}" yield f"\n\n{error_message}"
raise raise