ahuang11 commited on
Commit
c0130f2
1 Parent(s): f473fb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -52
app.py CHANGED
@@ -1,68 +1,74 @@
1
- from context import query
2
- from openai import AsyncOpenAI
3
  import panel as pn
 
 
4
 
5
- # taken from fleet context
6
- SYSTEM_PROMPT = """
7
- You are an expert in Python libraries. You carefully provide accurate, factual, thoughtful, nuanced answers, and are brilliant at reasoning. If you think there might not be a correct answer, you say so.
8
- Each token you produce is another opportunity to use computation, therefore you always spend a few sentences explaining background context, assumptions, and step-by-step thinking BEFORE you try to answer a question.
9
- Your users are experts in AI and ethics, so they already know you're a language model and your capabilities and limitations, so don't remind them of that. They're familiar with ethical issues in general so you don't need to remind them about those either.
10
- Your users are also in a CLI environment. You are capable of writing and running code. DO NOT write hypothetical code. ALWAYS write real code that will execute and run end-to-end.
 
 
11
 
12
- Instructions:
13
- - Be objective, direct. Include literal information from the context, don't add any conclusion or subjective information.
14
- - When writing code, ALWAYS have some sort of output (like a print statement). If you're writing a function, call it at the end. Do not generate the output, because the user can run it themselves.
15
- - ALWAYS cite your sources. Context will be given to you after the text ### Context source_url ### with source_url being the url to the file. For example, ### Context https://example.com/docs/api.html#files ### will have a source_url of https://example.com/docs/api.html#files.
16
- - When you cite your source, please cite it as [num] with `num` starting at 1 and incrementing with each source cited (1, 2, 3, ...). At the bottom, have a newline-separated `num: source_url` at the end of the response. ALWAYS add a new line between sources or else the user won't be able to read it. DO NOT convert links into markdown, EVER! If you do that, the user will not be able to click on the links.
17
- For example:
18
- **Context 1**: https://example.com/docs/api.html#pdfs
19
- I'm a big fan of PDFs.
20
- **Context 2**: https://example.com/docs/api.html#csvs
21
- I'm a big fan of CSVs.
22
- ### Prompt ###
23
- What is this person a big fan of?
24
- ### Response ###
25
- This person is a big fan of PDFs[1] and CSVs[2].
26
- 1: https://example.com/docs/api.html#pdfs
27
- 2: https://example.com/docs/api.html#csvs
28
  """
29
 
30
- pn.extension()
31
 
32
- MODEL = "gpt-3.5-turbo"
 
 
 
 
 
 
 
33
 
34
 
35
- async def answer(contents, user, instance):
36
- # start with system prompt
37
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
38
 
39
- # add context to the user input
40
- context = ""
41
- fleet_responses = query(contents, k=3)
42
- for i, response in enumerate(fleet_responses):
43
- context += f"\n\n**Context {i}**: {response['metadata']['url']}\n{response['metadata']['text']}"
44
- instance.send(context, avatar="🛩️", user="Fleet Context", respond=False)
45
 
46
- # get history of messages (skipping the intro message)
47
- # and serialize fleet context messages as "user" role
48
- messages.extend(
49
- instance.serialize(role_names={"user": ["user", "Fleet Context"]})[1:]
50
  )
51
-
52
- openai_response = await client.chat.completions.create(
53
- model=MODEL, messages=messages, temperature=0.2, stream=True
 
54
  )
55
-
56
  message = ""
57
- async for chunk in openai_response:
58
- token = chunk.choices[0].delta.content
59
- if token:
60
- message += token
61
  yield message
62
 
63
 
64
- client = AsyncOpenAI()
65
- intro_message = pn.chat.ChatMessage("Ask me anything about Python libraries!", user="System")
66
- chat_interface = pn.chat.ChatInterface(intro_message, callback=answer, callback_user="OpenAI")
67
- template = pn.template.FastListTemplate(main=[chat_interface], title="Panel UI of Fleet Context 🛩️")
68
- template.servable()
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
 
2
  import panel as pn
3
+ import requests
4
+ import os
5
 
6
+ pn.extension()
7
+
8
+ # format this URL with query and number of rows
9
+ API_URL = "https://api.crossref.org/works"
10
+ # API_KEY = os.environ["ELSEVIER_API_KEY"]
11
+ # URL_FMT = "https://api.elsevier.com/content/search/scopus"
12
+ DEFAULT_PROMPT_TEMPLATE = """
13
+ Here are the papers related to {query}
14
 
15
+ Help me summarize these into bullet points, readable within 2 minutes.
16
+
17
+ {items}
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  """
19
 
 
20
 
21
+ def get_relevant_papers(query, rows):
22
+ params = {
23
+ "query.bibliographic": query,
24
+ "rows": rows,
25
+ }
26
+ response = requests.get(API_URL, params=params)
27
+ output = response.json()
28
+ return output
29
 
30
 
31
+ def process_inputs(contents, user, instance):
32
+ output = get_relevant_papers(contents, rows_input.value)
33
+ instance.send(pn.pane.JSON(output), respond=False, user="Sources")
34
 
35
+ items = []
36
+ for item in output["message"]["items"]:
37
+ abstract = item.get("abstract", "")
38
+ title = item["title"]
39
+ url = item["URL"]
40
+ items.append(f"{title}({url}): {abstract}")
41
 
42
+ prompt = prompt_template_input.value.format(
43
+ query=contents, items=items
 
 
44
  )
45
+ response = client.chat.completions.create(
46
+ model="gpt-3.5-turbo",
47
+ messages=[{"role": "user", "content": prompt}],
48
+ stream=True,
49
  )
 
50
  message = ""
51
+ for chunk in response:
52
+ part = chunk.choices[0].delta.content
53
+ if part is not None:
54
+ message += part
55
  yield message
56
 
57
 
58
+ client = OpenAI()
59
+
60
+ # define widgets
61
+ prompt_template_input = pn.widgets.TextAreaInput(
62
+ value=DEFAULT_PROMPT_TEMPLATE.strip(), height=500
63
+ )
64
+ rows_input = pn.widgets.IntInput(name="Number of rows", value=2)
65
+ chat_interface = pn.chat.ChatInterface(callback=process_inputs, callback_exception="verbose")
66
+
67
+ # layout
68
+ sidebar = pn.Column(prompt_template_input, rows_input)
69
+ main = pn.Column(chat_interface)
70
+ pn.template.FastListTemplate(
71
+ sidebar=[sidebar],
72
+ main=[main],
73
+ title="Elsevier Summarizer",
74
+ ).show()