Update main.py
Browse files
main.py
CHANGED
|
@@ -15,25 +15,43 @@ SEARCH_API_URL = "https://rkihacker-brave.hf.space/search"
|
|
| 15 |
MODEL_NAME = "Binglity-Lite"
|
| 16 |
BACKEND_MODEL = "meta-llama/llama-3.1-8b-instruct/fp-8"
|
| 17 |
|
| 18 |
-
# ---
|
| 19 |
SYSTEM_PROMPT = """
|
| 20 |
-
You are "Binglity-Lite", a
|
| 21 |
-
|
| 22 |
-
**
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
"""
|
| 31 |
|
|
|
|
| 32 |
# --- FastAPI App ---
|
| 33 |
app = FastAPI(
|
| 34 |
title="Binglity-Lite API",
|
| 35 |
description="A web search-powered, streaming-capable chat completions API.",
|
| 36 |
-
version="1.
|
| 37 |
)
|
| 38 |
|
| 39 |
# --- Pydantic Models for OpenAI Compatibility ---
|
|
@@ -67,7 +85,7 @@ async def perform_web_search(query: str) -> List[Dict[str, Any]]:
|
|
| 67 |
|
| 68 |
def format_search_results_for_prompt(results: List[Dict[str, Any]]) -> str:
|
| 69 |
if not results:
|
| 70 |
-
return "No relevant search results were found.
|
| 71 |
|
| 72 |
formatted = "### Web Search Results ###\n\n"
|
| 73 |
for i, result in enumerate(results):
|
|
@@ -79,16 +97,11 @@ def format_search_results_for_prompt(results: List[Dict[str, Any]]) -> str:
|
|
| 79 |
|
| 80 |
# --- Streaming Logic ---
|
| 81 |
async def stream_response_generator(payload: Dict[str, Any]) -> AsyncGenerator[str, None]:
|
| 82 |
-
"""
|
| 83 |
-
Yields chunks from the inference API, formatted for OpenAI compatibility.
|
| 84 |
-
"""
|
| 85 |
headers = {
|
| 86 |
"Authorization": f"Bearer {INFERENCE_API_KEY}",
|
| 87 |
"Content-Type": "application/json",
|
| 88 |
"Accept": "text/event-stream"
|
| 89 |
}
|
| 90 |
-
|
| 91 |
-
# Create a unique ID for the response stream
|
| 92 |
response_id = f"chatcmpl-{uuid.uuid4()}"
|
| 93 |
created_time = int(time.time())
|
| 94 |
|
|
@@ -98,33 +111,22 @@ async def stream_response_generator(payload: Dict[str, Any]) -> AsyncGenerator[s
|
|
| 98 |
error_content = await response.aread()
|
| 99 |
raise HTTPException(status_code=response.status_code, detail=f"Error from inference API: {error_content.decode()}")
|
| 100 |
|
| 101 |
-
# Stream the response line by line
|
| 102 |
async for line in response.aiter_lines():
|
| 103 |
if line.startswith("data:"):
|
| 104 |
line_data = line[5:].strip()
|
| 105 |
if line_data == "[DONE]":
|
| 106 |
-
# Send the final data chunk and the done message
|
| 107 |
yield f"data: {json.dumps({'id': response_id, 'model': MODEL_NAME, 'object': 'chat.completion.chunk', 'created': created_time, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\n\n"
|
| 108 |
yield "data: [DONE]\n\n"
|
| 109 |
break
|
| 110 |
|
| 111 |
try:
|
| 112 |
chunk = json.loads(line_data)
|
| 113 |
-
# Reformat the chunk to be OpenAI compliant
|
| 114 |
formatted_chunk = {
|
| 115 |
-
"id": response_id,
|
| 116 |
-
"
|
| 117 |
-
"created": created_time,
|
| 118 |
-
"model": MODEL_NAME,
|
| 119 |
-
"choices": [{
|
| 120 |
-
"index": 0,
|
| 121 |
-
"delta": chunk["choices"][0].get("delta", {}),
|
| 122 |
-
"finish_reason": chunk["choices"][0].get("finish_reason")
|
| 123 |
-
}]
|
| 124 |
}
|
| 125 |
yield f"data: {json.dumps(formatted_chunk)}\n\n"
|
| 126 |
except json.JSONDecodeError:
|
| 127 |
-
print(f"Could not decode JSON from line: {line_data}")
|
| 128 |
continue
|
| 129 |
|
| 130 |
# --- API Endpoint ---
|
|
@@ -137,51 +139,32 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 137 |
if not user_query or request.messages[-1].role.lower() != 'user':
|
| 138 |
raise HTTPException(status_code=400, detail="The last message must be from the 'user' and contain content.")
|
| 139 |
|
| 140 |
-
# 1. Perform Web Search
|
| 141 |
search_results = await perform_web_search(user_query)
|
| 142 |
formatted_results = format_search_results_for_prompt(search_results)
|
| 143 |
|
| 144 |
-
|
| 145 |
-
final_user_prompt = f"User's question: \"{user_query}\"\n\nBased ONLY on the provided search results below, answer the user's question.\n\n{formatted_results}"
|
| 146 |
|
| 147 |
-
# 3. Prepare payload for Inference API
|
| 148 |
payload = {
|
| 149 |
"model": BACKEND_MODEL,
|
| 150 |
"messages": [
|
| 151 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 152 |
{"role": "user", "content": final_user_prompt},
|
| 153 |
],
|
| 154 |
-
"max_tokens": request.max_tokens,
|
| 155 |
-
"temperature": request.temperature,
|
| 156 |
-
"stream": request.stream,
|
| 157 |
}
|
| 158 |
|
| 159 |
-
# 4. Handle streaming or single response
|
| 160 |
if request.stream:
|
| 161 |
return StreamingResponse(stream_response_generator(payload), media_type="text/event-stream")
|
| 162 |
else:
|
| 163 |
-
# Standard non-streaming request
|
| 164 |
headers = {"Authorization": f"Bearer {INFERENCE_API_KEY}"}
|
| 165 |
async with httpx.AsyncClient(timeout=120.0) as client:
|
| 166 |
try:
|
| 167 |
response = await client.post(INFERENCE_API_URL, json=payload, headers=headers)
|
| 168 |
response.raise_for_status()
|
| 169 |
model_response = response.json()
|
| 170 |
-
|
| 171 |
-
# Format response to be OpenAI API compliant
|
| 172 |
return {
|
| 173 |
-
"id": model_response.get("id", f"chatcmpl-{uuid.uuid4()}"),
|
| 174 |
-
"
|
| 175 |
-
"created": model_response.get("created", int(time.time())),
|
| 176 |
-
"model": MODEL_NAME,
|
| 177 |
-
"choices": [{
|
| 178 |
-
"index": 0,
|
| 179 |
-
"message": {
|
| 180 |
-
"role": "assistant",
|
| 181 |
-
"content": model_response["choices"][0]["message"]["content"],
|
| 182 |
-
},
|
| 183 |
-
"finish_reason": "stop",
|
| 184 |
-
}],
|
| 185 |
"usage": model_response.get("usage", {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}),
|
| 186 |
}
|
| 187 |
except httpx.HTTPStatusError as e:
|
|
|
|
| 15 |
MODEL_NAME = "Binglity-Lite"
|
| 16 |
BACKEND_MODEL = "meta-llama/llama-3.1-8b-instruct/fp-8"
|
| 17 |
|
| 18 |
+
# --- Final Advanced System Prompt ---
|
| 19 |
SYSTEM_PROMPT = """
|
| 20 |
+
You are "Binglity-Lite", a highly advanced AI search assistant. Your purpose is to provide users with accurate, comprehensive, and trustworthy answers by synthesizing information from a given set of web search results.
|
| 21 |
+
|
| 22 |
+
**Core Directives:**
|
| 23 |
+
|
| 24 |
+
1. **Answer Directly**: Immediately address the user's question. **Do not** use introductory phrases like "Based on the search results..." or "Here is the information I found...". Your tone should be confident, objective, and encyclopedic.
|
| 25 |
+
|
| 26 |
+
2. **Synthesize, Don't Summarize**: Your primary task is to weave information from multiple sources into a single, cohesive, and well-structured answer. Do not simply describe what each source says one by one.
|
| 27 |
+
|
| 28 |
+
3. **Cite with Inline Markdown Links**: This is your most important instruction. When you present a fact or a piece of information from a source, you **must** cite it immediately using an inline Markdown link.
|
| 29 |
+
* **Format**: The format must be `[phrase or sentence containing the fact](URL)`. The URL must come from the `URL:` field of the provided source.
|
| 30 |
+
* **Example**: If a source with URL `https://example.com/science` says "The Earth is the third planet from the Sun", your output should be: "The Earth is the [third planet from the Sun](https://example.com/science)."
|
| 31 |
+
* **Rule**: Every piece of information in your answer must be attributable to a source via these inline links.
|
| 32 |
+
|
| 33 |
+
4. **Be Fact-Based**: Your entire response must be based **exclusively** on the information provided in the search results. Do not use any outside knowledge.
|
| 34 |
+
|
| 35 |
+
5. **Filter for Relevance**: If a search result is not relevant to the user's query, ignore it completely. Do not mention it in your response.
|
| 36 |
+
|
| 37 |
+
6. **Handle Ambiguity**: If the search results are contradictory or insufficient to answer the question fully, state this clearly in your response, citing the conflicting sources.
|
| 38 |
+
|
| 39 |
+
**Final Output Structure:**
|
| 40 |
+
|
| 41 |
+
Your final response MUST be structured in two parts:
|
| 42 |
+
|
| 43 |
+
1. **The Synthesized Answer**: A well-written response that directly answers the user's query, with facts and statements properly cited using inline Markdown links as described above.
|
| 44 |
+
|
| 45 |
+
2. **Sources Section**: After the answer, add a section header `## Sources`. Under this header, provide a bulleted list of the full titles and URLs of every source you used.
|
| 46 |
+
* **Format**: `- [Title of Source](URL)`
|
| 47 |
"""
|
| 48 |
|
| 49 |
+
|
| 50 |
# --- FastAPI App ---
|
| 51 |
app = FastAPI(
|
| 52 |
title="Binglity-Lite API",
|
| 53 |
description="A web search-powered, streaming-capable chat completions API.",
|
| 54 |
+
version="1.2.0",
|
| 55 |
)
|
| 56 |
|
| 57 |
# --- Pydantic Models for OpenAI Compatibility ---
|
|
|
|
| 85 |
|
| 86 |
def format_search_results_for_prompt(results: List[Dict[str, Any]]) -> str:
|
| 87 |
if not results:
|
| 88 |
+
return "No relevant search results were found. Inform the user that you could not find information on their query."
|
| 89 |
|
| 90 |
formatted = "### Web Search Results ###\n\n"
|
| 91 |
for i, result in enumerate(results):
|
|
|
|
| 97 |
|
| 98 |
# --- Streaming Logic ---
|
| 99 |
async def stream_response_generator(payload: Dict[str, Any]) -> AsyncGenerator[str, None]:
|
|
|
|
|
|
|
|
|
|
| 100 |
headers = {
|
| 101 |
"Authorization": f"Bearer {INFERENCE_API_KEY}",
|
| 102 |
"Content-Type": "application/json",
|
| 103 |
"Accept": "text/event-stream"
|
| 104 |
}
|
|
|
|
|
|
|
| 105 |
response_id = f"chatcmpl-{uuid.uuid4()}"
|
| 106 |
created_time = int(time.time())
|
| 107 |
|
|
|
|
| 111 |
error_content = await response.aread()
|
| 112 |
raise HTTPException(status_code=response.status_code, detail=f"Error from inference API: {error_content.decode()}")
|
| 113 |
|
|
|
|
| 114 |
async for line in response.aiter_lines():
|
| 115 |
if line.startswith("data:"):
|
| 116 |
line_data = line[5:].strip()
|
| 117 |
if line_data == "[DONE]":
|
|
|
|
| 118 |
yield f"data: {json.dumps({'id': response_id, 'model': MODEL_NAME, 'object': 'chat.completion.chunk', 'created': created_time, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\n\n"
|
| 119 |
yield "data: [DONE]\n\n"
|
| 120 |
break
|
| 121 |
|
| 122 |
try:
|
| 123 |
chunk = json.loads(line_data)
|
|
|
|
| 124 |
formatted_chunk = {
|
| 125 |
+
"id": response_id, "object": "chat.completion.chunk", "created": created_time, "model": MODEL_NAME,
|
| 126 |
+
"choices": [{"index": 0, "delta": chunk["choices"][0].get("delta", {}), "finish_reason": chunk["choices"][0].get("finish_reason")}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
}
|
| 128 |
yield f"data: {json.dumps(formatted_chunk)}\n\n"
|
| 129 |
except json.JSONDecodeError:
|
|
|
|
| 130 |
continue
|
| 131 |
|
| 132 |
# --- API Endpoint ---
|
|
|
|
| 139 |
if not user_query or request.messages[-1].role.lower() != 'user':
|
| 140 |
raise HTTPException(status_code=400, detail="The last message must be from the 'user' and contain content.")
|
| 141 |
|
|
|
|
| 142 |
search_results = await perform_web_search(user_query)
|
| 143 |
formatted_results = format_search_results_for_prompt(search_results)
|
| 144 |
|
| 145 |
+
final_user_prompt = f"User's question: \"{user_query}\"\n\nUse the web search results below to answer the user's question. Follow all rules in your system prompt exactly.\n\n{formatted_results}"
|
|
|
|
| 146 |
|
|
|
|
| 147 |
payload = {
|
| 148 |
"model": BACKEND_MODEL,
|
| 149 |
"messages": [
|
| 150 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 151 |
{"role": "user", "content": final_user_prompt},
|
| 152 |
],
|
| 153 |
+
"max_tokens": request.max_tokens, "temperature": request.temperature, "stream": request.stream,
|
|
|
|
|
|
|
| 154 |
}
|
| 155 |
|
|
|
|
| 156 |
if request.stream:
|
| 157 |
return StreamingResponse(stream_response_generator(payload), media_type="text/event-stream")
|
| 158 |
else:
|
|
|
|
| 159 |
headers = {"Authorization": f"Bearer {INFERENCE_API_KEY}"}
|
| 160 |
async with httpx.AsyncClient(timeout=120.0) as client:
|
| 161 |
try:
|
| 162 |
response = await client.post(INFERENCE_API_URL, json=payload, headers=headers)
|
| 163 |
response.raise_for_status()
|
| 164 |
model_response = response.json()
|
|
|
|
|
|
|
| 165 |
return {
|
| 166 |
+
"id": model_response.get("id", f"chatcmpl-{uuid.uuid4()}"), "object": "chat.completion", "created": model_response.get("created", int(time.time())), "model": MODEL_NAME,
|
| 167 |
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": model_response["choices"][0]["message"]["content"],}, "finish_reason": "stop",}],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
"usage": model_response.get("usage", {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}),
|
| 169 |
}
|
| 170 |
except httpx.HTTPStatusError as e:
|