Hongtyyuqu commited on
Commit
d79ac7b
·
verified ·
1 Parent(s): 2c436ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -35
app.py CHANGED
@@ -25,28 +25,38 @@ async def search_api(request: ChatRequest, req: Request):
25
  tavily_api_key = os.environ.get("TAVILY_API_KEY", "")
26
  nvidia_api_key = os.environ.get("NVIDIA_API_KEY", "")
27
 
28
- tavily_client = AsyncTavilyClient(api_key=tavily_api_key)
29
- search_res = await tavily_client.search(query=request.query, search_depth="basic", max_results=5)
 
30
 
31
- results = search_res.get("results", [])
32
  sources = []
33
  context_parts = []
34
 
35
- for idx, r in enumerate(results, 1):
36
- url = r.get("url", "")
37
- favicon = get_favicon_url(url)
38
- sources.append({
39
- "title": r.get("title", ""),
40
- "url": url,
41
- "favicon": favicon
42
- })
43
- context_parts.append(f"[{idx}] Title: {r.get('title')}\nURL: {url}\nContent: {r.get('content')}\n")
 
 
 
 
 
 
 
44
 
45
  context_str = "\n".join(context_parts)
46
 
47
  yield f"data: {json.dumps({'type': 'sources', 'content': sources})}\n\n"
48
 
49
- system_prompt = f"Answer the user's question accurately based on the search context below. Use inline citations like [1], [2] corresponding to sources.\nContext:\n{context_str}"
 
 
 
50
 
51
  payload = {
52
  "model": "stepfun-ai/step-3.7-flash",
@@ -66,28 +76,31 @@ async def search_api(request: ChatRequest, req: Request):
66
  "Accept": "text/event-stream"
67
  }
68
 
69
- async with httpx.AsyncClient(timeout=120.0) as client:
70
- async with client.stream("POST", "https://integrate.api.nvidia.com/v1/chat/completions", headers=headers, json=payload) as response:
71
- async for line in response.aiter_lines():
72
- if await req.is_disconnected():
73
- break
74
- if line.startswith("data: ") and line != "data: [DONE]":
75
- data_str = line[6:].strip()
76
- if not data_str:
77
- continue
78
- try:
79
- data = json.loads(data_str)
80
- choices = data.get("choices", [])
81
- if choices:
82
- delta = choices[0].get("delta", {})
83
- reasoning = delta.get("reasoning_content") or delta.get("reasoning")
84
- if reasoning:
85
- yield f"data: {json.dumps({'type': 'reasoning', 'content': reasoning})}\n\n"
86
- content = delta.get("content")
87
- if content:
88
- yield f"data: {json.dumps({'type': 'answer', 'content': content})}\n\n"
89
- except Exception:
90
- continue
 
 
 
91
 
92
  yield "data: [DONE]\n\n"
93
 
 
25
  tavily_api_key = os.environ.get("TAVILY_API_KEY", "")
26
  nvidia_api_key = os.environ.get("NVIDIA_API_KEY", "")
27
 
28
+ search_query = request.query.strip().replace("\n", " ")
29
+ if len(search_query) > 300:
30
+ search_query = search_query[:300]
31
 
 
32
  sources = []
33
  context_parts = []
34
 
35
+ if tavily_api_key and search_query:
36
+ try:
37
+ tavily_client = AsyncTavilyClient(api_key=tavily_api_key)
38
+ search_res = await tavily_client.search(query=search_query, search_depth="basic", max_results=5)
39
+ results = search_res.get("results", [])
40
+ for idx, r in enumerate(results, 1):
41
+ url = r.get("url", "")
42
+ favicon = get_favicon_url(url)
43
+ sources.append({
44
+ "title": r.get("title", ""),
45
+ "url": url,
46
+ "favicon": favicon
47
+ })
48
+ context_parts.append(f"[{idx}] Title: {r.get('title')}\nURL: {url}\nContent: {r.get('content')}\n")
49
+ except Exception:
50
+ pass
51
 
52
  context_str = "\n".join(context_parts)
53
 
54
  yield f"data: {json.dumps({'type': 'sources', 'content': sources})}\n\n"
55
 
56
+ if context_str:
57
+ system_prompt = f"Answer the user's question accurately based on the search context below. Use inline citations like [1], [2] corresponding to sources.\nContext:\n{context_str}"
58
+ else:
59
+ system_prompt = "You are a helpful AI assistant. Answer the user's request accurately."
60
 
61
  payload = {
62
  "model": "stepfun-ai/step-3.7-flash",
 
76
  "Accept": "text/event-stream"
77
  }
78
 
79
+ try:
80
+ async with httpx.AsyncClient(timeout=120.0) as client:
81
+ async with client.stream("POST", "https://integrate.api.nvidia.com/v1/chat/completions", headers=headers, json=payload) as response:
82
+ async for line in response.aiter_lines():
83
+ if await req.is_disconnected():
84
+ break
85
+ if line.startswith("data: ") and line != "data: [DONE]":
86
+ data_str = line[6:].strip()
87
+ if not data_str:
88
+ continue
89
+ try:
90
+ data = json.loads(data_str)
91
+ choices = data.get("choices", [])
92
+ if choices:
93
+ delta = choices[0].get("delta", {})
94
+ reasoning = delta.get("reasoning_content") or delta.get("reasoning")
95
+ if reasoning:
96
+ yield f"data: {json.dumps({'type': 'reasoning', 'content': reasoning})}\n\n"
97
+ content = delta.get("content")
98
+ if content:
99
+ yield f"data: {json.dumps({'type': 'answer', 'content': content})}\n\n"
100
+ except Exception:
101
+ continue
102
+ except Exception:
103
+ pass
104
 
105
  yield "data: [DONE]\n\n"
106