from openai import OpenAIfrom math import expimport numpy as npfrom IPython.display import display, HTMLimport osopen_ai_key ="sk-None-BcvcTP9SBTw3yuuBzCE9T3BlbkFJq0ZmKf4zLrW2tpGZKAn5"#open_ai_key = "sk-proj-nfLesDiu6oVaARYzTSOBT3BlbkFJpW0Y8kdWyLMhQKyx86Ip"os.environ["OPENAI_API_KEY"] = open_ai_key client = OpenAI()def get_completion( messages: list[dict[str, str]], model: str="gpt-4o-mini", max_tokens=500, temperature=0, stop=None, seed=123, tools=None, logprobs=None, # whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message.. top_logprobs=None,) ->str: params = {"model": model,"messages": messages,"max_tokens": max_tokens,"temperature": temperature,"stop": stop,"seed": seed,"logprobs": logprobs,"top_logprobs": top_logprobs, }if tools: params["tools"] = tools completion = client.chat.completions.create(**params)return completionCLASSIFICATION_PROMPT ="""You will be given a headline of a news article.Classify the article into one of the following categories: Technology, Politics, Sports, and Art.MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'Article headline: {headline}"""headlines = ["Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.","Local Mayor Launches Initiative to Enhance Urban Public Transport.","Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut",]for headline in headlines:print(f"\nHeadline: {headline}") API_RESPONSE = get_completion( [{"role": "user", "content": CLASSIFICATION_PROMPT.format(headline=headline)}], model="gpt-4", )print(f"Category: {API_RESPONSE.choices[0].message.content}\n")
Headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.
Category: Technology, as it discusses a new smartphone.
Headline: Local Mayor Launches Initiative to Enhance Urban Public Transport.
Category: Politics, discusses a governmental initiative.
Headline: Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut
Category: Art, involves a symphony orchestra.
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.a
a 99.33
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aa
a 98.84
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaa
a 99.2
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaaa
a 99.12
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaaaa
a 99.39
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaaaaa
a 99.14
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaaaaaa
a 98.65
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaaaaaaa
a 98.73
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaaaaaaaa
a 98.86
You will be given a headline of a news article.
Classify the article into one of the following categories: Technology, Politics, Sports, and Art.
MAKE SURE your output is one of the four categories stated. GIve a short explanation (at most a 5 word sentence). Start with the explanation and an 'a'
Article headline: Tech Giant Unveils Latest Smartphone Model with Advanced Photo-Editing Features.aaaaaaaaaa
a 97.59
from openai import OpenAIclient = OpenAI()response = client.chat.completions.create( messages=[{"role": "user","content": "Give a fictional description of a movie in three words.", }], model="gpt-4o-mini", logprobs=True, temperature=0.2,#best_of=10)print(response.choices[0])cum =0for item in response.choices[0].logprobs.content:print(item.token, np.round(np.exp(item.logprob)*100,2) ) cum += item.logprobprint('cum', np.round(np.exp(cum)*100,8))
I 58.33 appreciate 26.26 humans 52.3. 99.78I 50.12 don't 61.71 feel 53.12. 99.99cum 16.42623173import numpy as npcum =0for item in response.choices[0].logprobs.content:print(item.token, np.round(np.exp(item.logprob)*100,2) ) cum += item.logprobprint('cum', np.round(np.exp(cum)*100,8))
I 54.21
appreciate 38.8
humanity 42.7
. 99.75
cum 8.95858825
import numpy as npcum =0for item in response.choices[0].logprobs.content:print(item.token, np.round(np.exp(item.logprob)*100,2) ) cum += item.logprobprint('cum', np.round(np.exp(cum)*100,8))
import networkx as nximport plotly.graph_objects as goimport numpy as np# Sample data: Each path is represented by a list of (token, likelihood) tuples# These are example sequences; replace these with your actual sampled sequences and probabilities.sampled_sequences = [ [("The", 0.9), ("quick", 0.8), ("brown", 0.7)], [("The", 0.9), ("slow", 0.6), ("turtle", 0.5)], [("A", 0.85), ("quick", 0.75), ("fox", 0.65)], [("A", 0.85), ("slow", 0.6), ("brown", 0.4)]]# Initialize the graphG = nx.DiGraph()# Add nodes and edges to the graphfor sequence in sampled_sequences: current_path =""for i, (token, likelihood) inenumerate(sequence): node_label =f"{token} ({likelihood})"# Update path and add node with hover text containing likelihood and sentence current_path +=f" {token}" hover_text =f"Token: {token}<br>Likelihood: {likelihood}<br>Path: {current_path.strip()}"if i ==0: # Add the starting node G.add_node(node_label, hover=hover_text, path=current_path, likelihood=likelihood, pos=(i, len(G.nodes)))else: # Add the edge from previous to current token prev_node_label =f"{sequence[i-1][0]} ({sequence[i-1][1]})" G.add_node(node_label, hover=hover_text, path=current_path, likelihood=likelihood, pos=(i, len(G.nodes))) G.add_edge(prev_node_label, node_label, weight=np.log(likelihood))# Set up left-to-right positions for nodes using their "pos" attributepos = {node: (data["pos"][0], data["pos"][1]) for node, data in G.nodes(data=True)}# Plotting with Plotlyedge_x = []edge_y = []for edge in G.edges(): x0, y0 = pos[edge[0]] x1, y1 = pos[edge[1]] edge_x.extend([x0, x1, None]) edge_y.extend([y0, y1, None])edge_trace = go.Scatter( x=edge_x, y=edge_y, line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines')# Create node traces with hover text for each nodenode_x = []node_y = []node_text = []for node in G.nodes(): x, y = pos[node] node_x.append(x) node_y.append(y) node_text.append(G.nodes[node]['hover'])node_trace = go.Scatter( x=node_x, y=node_y, mode='markers+text', text=[node.split(" ")[0] for node in G.nodes()], # Show token only (without likelihood) for cleanliness textposition="bottom center", marker=dict(size=10, color='#FFA07A'), hoverinfo='text', hovertext=node_text)# Assemble the figure with a left-to-right layoutfig = go.Figure(data=[edge_trace, node_trace], layout=go.Layout( title='Sampled Sequences Visualization (Left-to-Right)', showlegend=False, hovermode='closest', margin=dict(b=0, l=0, r=0, t=50), xaxis=dict(showgrid=False, zeroline=False, visible=False), yaxis=dict(showgrid=False, zeroline=False, visible=False) ))fig.show()
Unable to display output for mime type(s): application/vnd.plotly.v1+json