Create q5.py
Browse files
q5.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import openai
|
| 2 |
+
|
| 3 |
+
def extract_entities(api_key, text, model="text-davinci-003"):
|
| 4 |
+
"""
|
| 5 |
+
Perform basic entity extraction using LangChain (GPT-3 model).
|
| 6 |
+
|
| 7 |
+
Parameters:
|
| 8 |
+
- api_key (str): Your OpenAI API key.
|
| 9 |
+
- text (str): The text from which entities are to be extracted.
|
| 10 |
+
- model (str): The GPT-3 model to use. Defaults to 'text-davinci-003'.
|
| 11 |
+
|
| 12 |
+
Returns:
|
| 13 |
+
- entities (list): List of entities found in the text.
|
| 14 |
+
"""
|
| 15 |
+
# Set the OpenAI API key
|
| 16 |
+
openai.api_key = api_key
|
| 17 |
+
|
| 18 |
+
# Construct prompt for entity extraction
|
| 19 |
+
prompt = f"Extract entities from the following text:\n{text}\n\nEntities:"
|
| 20 |
+
|
| 21 |
+
# Generate text completion using LangChain
|
| 22 |
+
response = openai.Completion.create(
|
| 23 |
+
engine=model,
|
| 24 |
+
prompt=prompt,
|
| 25 |
+
max_tokens=50, # Adjust max_tokens based on expected entity length
|
| 26 |
+
stop=None # Allow the model to generate until the max_tokens is reached
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Extract and parse entities from the response
|
| 30 |
+
extracted_text = response['choices'][0]['text'].strip()
|
| 31 |
+
entities = extracted_text.split(',')
|
| 32 |
+
|
| 33 |
+
return entities
|
| 34 |
+
|
| 35 |
+
# Example usage:
|
| 36 |
+
def main():
|
| 37 |
+
# Replace 'your_openai_api_key_here' with your actual API key
|
| 38 |
+
api_key = 'your_openai_api_key_here'
|
| 39 |
+
|
| 40 |
+
# Example text
|
| 41 |
+
text = """
|
| 42 |
+
Elon Musk is the CEO of SpaceX and Tesla. He was born in Pretoria, South Africa and went to Stanford University.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
# Extract entities
|
| 46 |
+
entities = extract_entities(api_key, text)
|
| 47 |
+
|
| 48 |
+
# Print extracted entities
|
| 49 |
+
print("Entities Found:")
|
| 50 |
+
for entity in entities:
|
| 51 |
+
print(entity.strip())
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
main()
|