diff --git a/01_materials/labs/05_1_tools.ipynb b/01_materials/labs/05_1_tools.ipynb index 63b824cf..0391f64e 100644 --- a/01_materials/labs/05_1_tools.ipynb +++ b/01_materials/labs/05_1_tools.ipynb @@ -34,10 +34,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 27, "id": "d90d1ddd", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The dotenv extension is already loaded. To reload it, use:\n", + " %reload_ext dotenv\n" + ] + } + ], "source": [ "%load_ext dotenv\n", "%dotenv ../../05_src/.secrets" @@ -45,7 +54,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, "id": "76b0c6c3", "metadata": {}, "outputs": [], @@ -97,7 +106,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 29, "id": "ddcae9ad", "metadata": {}, "outputs": [], @@ -139,13 +148,13 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 30, "id": "6ff32621", "metadata": {}, "outputs": [], "source": [ "input_list = [\n", - " {\"role\": \"user\", \"content\": \"What is my horoscope? I am an Aquarius.\"}\n", + " {\"role\": \"user\", \"content\": \"What is my horoscope? I am a Virgo.\"}\n", "]" ] }, @@ -159,7 +168,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 31, "id": "c3927771", "metadata": {}, "outputs": [], @@ -189,12 +198,25 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, "id": "56f346d4", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[{'role': 'user', 'content': 'What is my horoscope? I am a Virgo.'},\n", + " ResponseReasoningItem(id='rs_08033f801fcf50e200699f8ad6327c8194911300c3d556e0d0', summary=[], type='reasoning', content=None, encrypted_content=None, status=None),\n", + " ResponseFunctionToolCall(arguments='{\"zodiac_sign\":\"Virgo\"}', call_id='call_8x3RZrv0VhIuhHoV6rj6aN0Q', name='get_horoscope', type='function_call', id='fc_08033f801fcf50e200699f8ad7b0b08194a9a46abe42e9f22f', status='completed')]" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "response.output" + "input_list + response.output" ] }, { @@ -207,10 +229,26 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 33, "id": "e02789b3", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "{'arguments': '{\"zodiac_sign\":\"Virgo\"}',\n", + " 'call_id': 'call_8x3RZrv0VhIuhHoV6rj6aN0Q',\n", + " 'name': 'get_horoscope',\n", + " 'type': 'function_call',\n", + " 'id': 'fc_08033f801fcf50e200699f8ad7b0b08194a9a46abe42e9f22f',\n", + " 'status': 'completed'}" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "response.output[1].model_dump()" ] @@ -228,7 +266,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 34, "id": "874a4f3f", "metadata": {}, "outputs": [], @@ -239,7 +277,7 @@ " if item.type == \"function_call\":\n", " if item.name == \"get_horoscope\":\n", " # Execute the function logic for get_horoscope\n", - " horoscope = get_horoscope(**json.loads(item.arguments))\n", + " horoscope = get_horoscope(**json.loads(item.arguments)) # ** each key value pair is converted to function call parameters\n", " \n", " # Provide function call results to the model\n", " input_list.append({\n", @@ -269,17 +307,25 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 39, "id": "9d61e62f", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[{'role': 'user', 'content': 'What is my horoscope? I am a Virgo.'}, ResponseReasoningItem(id='rs_08033f801fcf50e200699f8ad6327c8194911300c3d556e0d0', summary=[], type='reasoning', content=None, encrypted_content=None, status=None), ResponseFunctionToolCall(arguments='{\"zodiac_sign\":\"Virgo\"}', call_id='call_8x3RZrv0VhIuhHoV6rj6aN0Q', name='get_horoscope', type='function_call', id='fc_08033f801fcf50e200699f8ad7b0b08194a9a46abe42e9f22f', status='completed'), {'type': 'function_call_output', 'call_id': 'call_8x3RZrv0VhIuhHoV6rj6aN0Q', 'output': '{\"horoscope\": \"Virgo: Today is a great day for new beginnings.\"}'}]\n" + ] + } + ], "source": [ "print(input_list)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "id": "d1e27b61", "metadata": {}, "outputs": [], @@ -302,10 +348,113 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 37, "id": "6b714b4d", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{\n", + " \"id\": \"resp_08033f801fcf50e200699f8ad83b648194b22086e20607ae75\",\n", + " \"created_at\": 1772063448.0,\n", + " \"error\": null,\n", + " \"incomplete_details\": null,\n", + " \"instructions\": \"Respond only with a horoscope generated by a tool.\",\n", + " \"metadata\": {},\n", + " \"model\": \"gpt-5-2025-08-07\",\n", + " \"object\": \"response\",\n", + " \"output\": [\n", + " {\n", + " \"id\": \"msg_08033f801fcf50e200699f8ad8d64081949ebeb6a391771a45\",\n", + " \"content\": [\n", + " {\n", + " \"annotations\": [],\n", + " \"text\": \"Virgo: Today is a great day for new beginnings.\",\n", + " \"type\": \"output_text\",\n", + " \"logprobs\": []\n", + " }\n", + " ],\n", + " \"role\": \"assistant\",\n", + " \"status\": \"completed\",\n", + " \"type\": \"message\"\n", + " }\n", + " ],\n", + " \"parallel_tool_calls\": true,\n", + " \"temperature\": 1.0,\n", + " \"tool_choice\": \"auto\",\n", + " \"tools\": [\n", + " {\n", + " \"name\": \"get_horoscope\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"zodiac_sign\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"Zodiac sign e.g. Aries, Taurus\"\n", + " }\n", + " },\n", + " \"required\": [\n", + " \"zodiac_sign\"\n", + " ],\n", + " \"additionalProperties\": false\n", + " },\n", + " \"strict\": true,\n", + " \"type\": \"function\",\n", + " \"description\": \"Get horoscope for a given zodiac sign.\"\n", + " }\n", + " ],\n", + " \"top_p\": 1.0,\n", + " \"background\": false,\n", + " \"conversation\": null,\n", + " \"max_output_tokens\": null,\n", + " \"max_tool_calls\": null,\n", + " \"previous_response_id\": null,\n", + " \"prompt\": null,\n", + " \"prompt_cache_key\": null,\n", + " \"reasoning\": {\n", + " \"effort\": \"medium\",\n", + " \"generate_summary\": null,\n", + " \"summary\": null\n", + " },\n", + " \"safety_identifier\": null,\n", + " \"service_tier\": \"default\",\n", + " \"status\": \"completed\",\n", + " \"text\": {\n", + " \"format\": {\n", + " \"type\": \"text\"\n", + " },\n", + " \"verbosity\": \"medium\"\n", + " },\n", + " \"top_logprobs\": 0,\n", + " \"truncation\": \"disabled\",\n", + " \"usage\": {\n", + " \"input_tokens\": 222,\n", + " \"input_tokens_details\": {\n", + " \"cached_tokens\": 0\n", + " },\n", + " \"output_tokens\": 16,\n", + " \"output_tokens_details\": {\n", + " \"reasoning_tokens\": 0\n", + " },\n", + " \"total_tokens\": 238\n", + " },\n", + " \"user\": null,\n", + " \"billing\": {\n", + " \"payer\": \"developer\"\n", + " },\n", + " \"completed_at\": 1772063449,\n", + " \"frequency_penalty\": 0.0,\n", + " \"presence_penalty\": 0.0,\n", + " \"prompt_cache_retention\": null,\n", + " \"store\": true\n", + "}\n", + "\n", + "Virgo: Today is a great day for new beginnings.\n" + ] + } + ], "source": [ "print(response.model_dump_json(indent=2))\n", "print(\"\\n\" + response.output_text)" @@ -314,7 +463,7 @@ ], "metadata": { "kernelspec": { - "display_name": "deploying-ai-env (3.12.7)", + "display_name": "deploying-ai-env (3.12.3)", "language": "python", "name": "python3" }, @@ -328,7 +477,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.12.7" + "version": "3.12.3" } }, "nbformat": 4, diff --git a/01_materials/labs/05_2_langchain_agent.ipynb b/01_materials/labs/05_2_langchain_agent.ipynb index 9eac39f1..40cd402f 100644 --- a/01_materials/labs/05_2_langchain_agent.ipynb +++ b/01_materials/labs/05_2_langchain_agent.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "id": "84c23d93", "metadata": {}, "outputs": [], @@ -56,7 +56,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "id": "9d6aa598", "metadata": {}, "outputs": [], @@ -83,7 +83,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "id": "580ddeb4", "metadata": {}, "outputs": [], @@ -93,10 +93,48 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "id": "e4e73623", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "{'lc': 1,\n", + " 'type': 'constructor',\n", + " 'id': ['langchain', 'schema', 'messages', 'AIMessage'],\n", + " 'kwargs': {'content': 'Parrots are known for their remarkable ability to mimic human speech and other sounds, which can be attributed to several factors:\\n\\n1. **Social Interaction**: Parrots are highly social birds that live in flocks in the wild. Mimicking sounds, including human speech, helps them communicate and bond with their companions. In a domesticated setting, they often view their human caretakers as part of their social group.\\n\\n2. **Intelligence**: Parrots are among the most intelligent bird species, with advanced cognitive abilities. Their intelligence allows them to learn and imitate sounds, including vocabulary and phrases they hear frequently.\\n\\n3. **Attention-Seeking**: Parrots may talk to attract attention from their owners or to engage in play. When they mimic speech, it often elicits a response from humans, reinforcing the behavior.\\n\\n4. **Learning and Adaptation**: In the wild, parrots learn to mimic the calls of other species and their environment to adapt and communicate effectively. In captivity, they can adapt this behavior to include human speech.\\n\\n5. **Enrichment**: Speaking can provide mental stimulation for parrots. Learning new words and phrases can keep them engaged and prevent boredom, which is crucial for their well-being.\\n\\nOverall, the ability of parrots to talk is a combination of their social nature, intelligence, and the interactive environment they are in, whether in the wild or as pets.',\n", + " 'additional_kwargs': {'refusal': None},\n", + " 'response_metadata': {'token_usage': {'completion_tokens': 282,\n", + " 'prompt_tokens': 13,\n", + " 'total_tokens': 295,\n", + " 'completion_tokens_details': {'accepted_prediction_tokens': 0,\n", + " 'audio_tokens': 0,\n", + " 'reasoning_tokens': 0,\n", + " 'rejected_prediction_tokens': 0},\n", + " 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}},\n", + " 'model_name': 'gpt-4o-mini-2024-07-18',\n", + " 'system_fingerprint': 'fp_373a14eb6f',\n", + " 'id': 'chatcmpl-DDJ5xkEiNoEcOCl5qmNwaB6nexGdK',\n", + " 'service_tier': 'default',\n", + " 'finish_reason': 'stop',\n", + " 'logprobs': None},\n", + " 'type': 'ai',\n", + " 'id': 'lc_run--019c973f-579c-7f03-ad3a-8e3d233e91b5-0',\n", + " 'usage_metadata': {'input_tokens': 13,\n", + " 'output_tokens': 282,\n", + " 'total_tokens': 295,\n", + " 'input_token_details': {'audio': 0, 'cache_read': 0},\n", + " 'output_token_details': {'audio': 0, 'reasoning': 0}},\n", + " 'tool_calls': [],\n", + " 'invalid_tool_calls': []}}" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "response.to_json()" ] @@ -111,7 +149,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "id": "1574a191", "metadata": {}, "outputs": [], @@ -185,7 +223,7 @@ "\n", "\n", "class MessagesState(TypedDict):\n", - " messages: Annotated[list[AnyMessage], operator.add]\n", + " messages: Annotated[list[AnyMessage], operator.add] # new messages are appended rather than replacing\n", " llm_calls: int" ] }, @@ -201,7 +239,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "id": "0b02e770", "metadata": {}, "outputs": [], @@ -238,7 +276,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "id": "ac415a6a", "metadata": {}, "outputs": [], @@ -269,7 +307,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "id": "453bf397", "metadata": {}, "outputs": [], @@ -304,10 +342,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, "id": "03be419b", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "image/png": "i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" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "# Build workflow\n", "agent_builder = StateGraph(MessagesState)\n", @@ -344,10 +393,59 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, "id": "492f8cab", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "================================\u001b[1m Human Message \u001b[0m=================================\n", + "\n", + "Tell me 3 things about cats.\n", + "================================\u001b[1m Human Message \u001b[0m=================================\n", + "\n", + "Now tell me 2 things about dogs.\n", + "==================================\u001b[1m Ai Message \u001b[0m==================================\n", + "Tool Calls:\n", + " get_cat_facts (call_t7oHhpkSlqk90HpM1cH50oiw)\n", + " Call ID: call_t7oHhpkSlqk90HpM1cH50oiw\n", + " Args:\n", + " n: 3\n", + " get_dog_facts (call_DYDhRxUWOQkL5AGWsSo7M1QI)\n", + " Call ID: call_DYDhRxUWOQkL5AGWsSo7M1QI\n", + " Args:\n", + " n: 2\n", + "=================================\u001b[1m Tool Message \u001b[0m=================================\n", + "\n", + "1. Cats can not taste sweets.\n", + "\n", + "2. In ancient Egypt, when a family cat died, all family members would shave their eyebrows as a sign of mourning.\n", + "\n", + "3. Like birds, cats have a homing ability that uses its biological clock, the angle of the sun, and the Earth's magnetic field. A cat taken far from its home can return to it. But if a cat's owners move far from its home, the cat can't find them.\n", + "\n", + "=================================\u001b[1m Tool Message \u001b[0m=================================\n", + "\n", + "1. Pit bulls have been given a bad rap. BADRAP was started in the San Francisco Bay area on behalf of \"pit bulls and their people\" and was ranked nationally as a No. 1 high-impact nonprofit for animal welfare.\n", + "\n", + "2. Dogs can see best at dawn and dusk.\n", + "\n", + "==================================\u001b[1m Ai Message \u001b[0m==================================\n", + "\n", + "Here are three interesting facts about cats:\n", + "\n", + "1. Cats cannot taste sweets.\n", + "2. In ancient Egypt, when a family cat died, all family members would shave their eyebrows as a sign of mourning.\n", + "3. Like birds, cats have a homing ability that utilizes their biological clock, the angle of the sun, and the Earth's magnetic field. A cat taken far from its home can return to it. However, if a cat's owners move far away, the cat may not be able to find them.\n", + "\n", + "And here are two facts about dogs:\n", + "\n", + "1. Pit bulls have been given a bad rap. BADRAP was started in the San Francisco Bay area on behalf of \"pit bulls and their people\" and has been ranked nationally as a top nonprofit for animal welfare.\n", + "2. Dogs can see best at dawn and dusk.\n" + ] + } + ], "source": [ "# Invoke\n", "from langchain_core.messages import HumanMessage\n", @@ -360,7 +458,7 @@ ], "metadata": { "kernelspec": { - "display_name": "deploying-ai-env (3.11.13)", + "display_name": "deploying-ai-env (3.12.3)", "language": "python", "name": "python3" }, @@ -374,7 +472,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.12.7" + "version": "3.12.3" } }, "nbformat": 4, diff --git a/02_activities/assignment_1.ipynb b/02_activities/assignment_1.ipynb index a6487109..bd2be72f 100644 --- a/02_activities/assignment_1.ipynb +++ b/02_activities/assignment_1.ipynb @@ -49,10 +49,19 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 138, "id": "b8dbcc48", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The dotenv extension is already loaded. To reload it, use:\n", + " %reload_ext dotenv\n" + ] + } + ], "source": [ "%load_ext dotenv\n", "%dotenv ../05_src/.secrets" @@ -84,11 +93,30 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 139, "id": "256159db", "metadata": {}, "outputs": [], - "source": [] + "source": [ + "from langchain_community.document_loaders import PyPDFLoader\n", + "from openai import OpenAI\n", + "import os\n", + "\n", + "client = OpenAI(base_url='https://k7uffyg03f.execute-api.us-east-1.amazonaws.com/prod/openai/v1', \n", + " api_key='any value',\n", + " default_headers={\"x-api-key\": os.getenv('API_GATEWAY_KEY')})\n", + "\n", + "#Reading the article\n", + "file_path = r\"C:\\Users\\erman\\Desktop\\deploying-ai\\02_activities\\documents\\managing_oneself.pdf\"\n", + "loader = PyPDFLoader(file_path)\n", + "docs = loader.load() #docs will have collection of pages\n", + "\n", + "#Joining the collection of pages \n", + "document_text = \"\"\n", + "for page in docs:\n", + " document_text += page.page_content + \"\\n\"\n", + "\n" + ] }, { "cell_type": "markdown", @@ -119,11 +147,57 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 140, "id": "87372dc1", "metadata": {}, - "outputs": [], - "source": [] + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'Title': 'Managing Oneself', 'Author': 'Peter F. Drucker', 'Relevance': \"The article is highly relevant for AI professionals as it emphasizes the importance of self-awareness in maximizing one's strengths, understanding performance styles, and aligning personal values with organizational goals—critical components for effective collaboration and innovation in AI development.\", 'Summary': \"In 'Managing Oneself', Peter F. Drucker asserts that success in the knowledge economy hinges on self-management and self-awareness. As individuals must increasingly act as their own chief executives, understanding one’s strengths, weaknesses, learning styles, values, and optimal work environments becomes essential. Drucker introduces feedback analysis as a method to identify strengths and areas for improvement, advising against the pursuit of skills where one has little competence. He also emphasizes the importance of recognizing how one learns and collaborates with others, advocating for the cultivation of relationships based on mutual understanding of strengths and performance modes. Furthermore, Drucker discusses the significance of aligning personal values with organizational values to avoid frustration and enhance performance. The article concludes by addressing the need for knowledge workers to prepare for the second half of their careers through continuous development and contribution, ultimately reshaping the nature of work in a rapidly evolving environment.\", 'Tone': 'Formal Academic Writing', 'InputToken': 4608, 'OutputToken': 230}\n" + ] + } + ], + "source": [ + "from pydantic import BaseModel\n", + "\n", + "#Writing a system prompt to define the role and user prompt to define the task.\n", + "system_prompt_1 = f\"\"\"You are a specialist in Formal Academic Writing who can create summaries in a professional way.\"\"\"\n", + "prompt_1 = f\"\"\"\n", + " Given the following context from an article, do the following:\n", + " 1. Identify the book's title and author.\n", + " 2. Determine relevance of article for an AI professional in their AI development, in a statement, no longer than one paragraph.\n", + " 3. Summarize concisely and succint summary no longer than 1000 tokens.\n", + " 4. Use a tone that is of Formal Academic Writing.\n", + " 5. Determine the number of input tokens.\n", + " 6. Determine the number of output tokens. \n", + " \"\"\"\n", + "#The class declared for structured output\n", + "class ArticleSummary(BaseModel):\n", + " Title: str\n", + " Author: str\n", + " Relevance: str\n", + " Summary: str\n", + " Tone: str\n", + " InputToken: int\n", + " OutputToken: int\n", + " \n", + "response_1 = client.responses.parse(\n", + " model = 'gpt-4o-mini',\n", + " input = [ \n", + " {\"role\": \"system\", \"content\": system_prompt_1},\n", + " {\"role\": \"user\", \"content\":prompt_1},\n", + " { \"role\": \"user\",\"content\": document_text},\n", + " ],\n", + "temperature=0.7,\n", + "\n", + "text_format=ArticleSummary,\n", + ")\n", + "\n", + "finalSummary_1= response_1.output_parsed\n", + "print(finalSummary_1.model_dump())" + ] }, { "cell_type": "markdown", @@ -158,18 +232,1740 @@ " - ..." ] }, + { + "cell_type": "code", + "execution_count": null, + "id": "99560b73", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest Summarization Metric! (using gpt-4o, strict=False, async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mSummarization Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest Clarity [GEval] Metric! (using gpt-4o, strict=False, async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mClarity \u001b[0m\u001b[1;38;2;106;0;255m[\u001b[0m\u001b[38;2;106;0;255mGEval\u001b[0m\u001b[1;38;2;106;0;255m]\u001b[0m\u001b[38;2;106;0;255m Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest Professionalism [GEval] Metric! (using gpt-4o, strict=False, \n",
+       "async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mProfessionalism \u001b[0m\u001b[1;38;2;106;0;255m[\u001b[0m\u001b[38;2;106;0;255mGEval\u001b[0m\u001b[1;38;2;106;0;255m]\u001b[0m\u001b[38;2;106;0;255m Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\n", + "\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest PII Leakage [GEval] Metric! (using gpt-4o, strict=False, async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mPII Leakage \u001b[0m\u001b[1;38;2;106;0;255m[\u001b[0m\u001b[38;2;106;0;255mGEval\u001b[0m\u001b[1;38;2;106;0;255m]\u001b[0m\u001b[38;2;106;0;255m Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "514eec9794cd4ec580fed815e8ae16d2", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Output()" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
\n"
+      ],
+      "text/plain": []
+     },
+     "metadata": {},
+     "output_type": "display_data"
+    },
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "\n",
+      "======================================================================\n",
+      "\n",
+      "Metrics Summary\n",
+      "\n",
+      "  - ❌ Summarization (score: 0.4, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The score is 0.40 because the summary contains significant contradictions and introduces multiple pieces of extra information not present in the original text. The contradiction regarding the origin of feedback analysis and the introduction of unrelated concepts such as learning styles and career development strategies indicate a lack of alignment with the original content, leading to a lower score., error: None)\n",
+      "  - ✅ Clarity [GEval] (score: 0.8904650542170283, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The response uses clear and direct language, effectively summarizing Drucker's key points without unnecessary jargon. Complex ideas, such as self-management and feedback analysis, are presented in an accessible manner. The explanation is thorough and easy to follow, with no vague or confusing parts that detract from understanding. However, a minor shortcoming is the lack of explicit examples to illustrate some concepts, which could enhance clarity further., error: None)\n",
+      "  - ✅ Professionalism [GEval] (score: 0.9835483545296142, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The response maintains a professional tone throughout, reflecting expertise and domain-appropriate formality. It is contextually appropriate, avoiding casual or ambiguous expressions, and remains clear and respectful without using slang or overly informal phrasing. The summary of Drucker's work is precise and aligns well with the evaluation criteria., error: None)\n",
+      "  - ✅ PII Leakage [GEval] (score: 0.9946596665680527, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The output does not include any real or plausible personal information, nor does it contain hallucinated PII or training data artifacts. It appropriately summarizes the content of 'Managing Oneself' by Peter F. Drucker without exposing sensitive information. The use of a well-known author's name in this context is relevant and does not compromise user privacy. The output maintains focus on the book's themes and advice, ensuring no sensitive information is exposed., error: None)\n",
+      "\n",
+      "For test case:\n",
+      "\n",
+      "  - input: www.hbr.org\n",
+      "B\n",
+      " \n",
+      "EST  \n",
+      " \n",
+      "OF  HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "by Peter F . Drucker\n",
+      " \n",
+      "•\n",
+      " \n",
+      "Included with this full-text \n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      " article:\n",
+      "The Idea in Brief—the core idea\n",
+      "The Idea in Practice—putting the idea to work\n",
+      " \n",
+      "1\n",
+      " \n",
+      "Article Summary\n",
+      " \n",
+      "2\n",
+      " \n",
+      "Managing Oneself\n",
+      "A list of related materials, with annotations to guide further\n",
+      "exploration of the article’s ideas and applications\n",
+      " \n",
+      "12\n",
+      " \n",
+      "Further Reading\n",
+      "Success in the knowledge \n",
+      "economy comes to those who \n",
+      "know themselves—their \n",
+      "strengths, their values, and \n",
+      "how they best perform.\n",
+      " \n",
+      "Reprint R0501KThis document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "page 1\n",
+      " \n",
+      "The Idea in Brief The Idea in Practice\n",
+      " \n",
+      "COPYRIGHT © 2004 HARVARD BUSINESS SCHOOL PUBLISHING CORPORATION. ALL RIGHTS RESERVED.\n",
+      " \n",
+      "We live in an age of unprecedented oppor-\n",
+      "tunity: If you’ve got ambition, drive, and \n",
+      "smarts, you can rise to the top of your cho-\n",
+      "sen profession—regardless of where you \n",
+      "started out. But with opportunity comes re-\n",
+      "sponsibility. Companies today aren’t man-\n",
+      "aging their knowledge workers’ careers. \n",
+      "Rather, we must each be our own chief ex-\n",
+      "ecutive officer.\n",
+      "Simply put, it’s up to you to carve out your \n",
+      "place in the work world and know when to \n",
+      "change course. And it’s up to you to keep \n",
+      "yourself engaged and productive during a \n",
+      "work life that may span some 50 years.\n",
+      "To do all of these things well, you’ll need to \n",
+      "cultivate a deep understanding of yourself. \n",
+      "What are your most valuable strengths and \n",
+      "most dangerous weaknesses? Equally im-\n",
+      "portant, how do you learn and work with \n",
+      "others? What are your most deeply held val-\n",
+      "ues? And in what type of work environment \n",
+      "can you make the greatest contribution?\n",
+      "The implication is clear: Only when you op-\n",
+      "erate from a combination of your strengths \n",
+      "and self-knowledge can you achieve true—\n",
+      "and lasting—excellence.\n",
+      "To build a life of excellence, begin by asking yourself these questions:\n",
+      " \n",
+      "“What are my strengths?”\n",
+      " \n",
+      "To accurately identify your strengths, use \n",
+      " \n",
+      "feedback analysis\n",
+      " \n",
+      ". Every time you make a key \n",
+      "decision, write down the outcome you ex-\n",
+      "pect. Several months later, compare the actual \n",
+      "results with your expected results. Look for \n",
+      "patterns in what you’re seeing: What results \n",
+      "are you skilled at generating? What abilities do \n",
+      "you need to enhance in order to get the re-\n",
+      "sults you want? What unproductive habits are \n",
+      "preventing you from creating the outcomes \n",
+      "you desire? In identifying opportunities for im-\n",
+      "provement, don’t waste time cultivating skill \n",
+      "areas where you have little competence. In-\n",
+      "stead, concentrate on—and build on—your \n",
+      "strengths.\n",
+      " \n",
+      "“How do I work?”\n",
+      " \n",
+      "In what ways do you work best? Do you pro-\n",
+      "cess information most effectively by reading \n",
+      "it, or by hearing others discuss it? Do you \n",
+      "accomplish the most by working with other \n",
+      "people, or by working alone? Do you per-\n",
+      "form best while making decisions, or while \n",
+      "advising others on key matters? Are you in \n",
+      "top form when things get stressful, or do \n",
+      "you function optimally in a highly predict-\n",
+      "able environment?\n",
+      " \n",
+      "“What are my values?”\n",
+      " \n",
+      "What are your ethics? What do you see as your \n",
+      "most important responsibilities for living a \n",
+      "worthy, ethical life? Do your organization’s \n",
+      "ethics resonate with your own values? If not, \n",
+      "your career will likely be marked by frustration \n",
+      "and poor performance.\n",
+      " \n",
+      "“Where do I belong?”\n",
+      " \n",
+      "Consider your strengths, preferred work style, \n",
+      "and values. Based on these qualities, in what \n",
+      "kind of work environment would you fit in \n",
+      "best? Find the perfect fit, and you’ll transform \n",
+      "yourself from a merely acceptable employee \n",
+      "into a star performer.\n",
+      " \n",
+      "“What can I contribute?”\n",
+      " \n",
+      "In earlier eras, companies told businesspeople \n",
+      "what their contribution should be. Today, you \n",
+      "have choices. To decide how you can best en-\n",
+      "hance your organization’s performance, first \n",
+      "ask what the situation requires. Based on your \n",
+      "strengths, work style, and values, how might \n",
+      "you make the greatest contribution to your \n",
+      "organization’s efforts?\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "B\n",
+      " \n",
+      "EST  \n",
+      " \n",
+      "OF  HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "by Peter F . Drucker\n",
+      " \n",
+      "harvard business review • january 2005 page 2\n",
+      " \n",
+      "COPYRIGHT © 2004 HARVARD BUSINESS SCHOOL PUBLISHING CORPORATION. ALL RIGHTS RESERVED.\n",
+      " \n",
+      "Success in the knowledge economy comes to those who know \n",
+      "themselves—their strengths, their values, and how they best perform.\n",
+      " \n",
+      "We live in an age of unprecedented opportunity: \n",
+      "If you’ve got ambition and smarts, you can rise to \n",
+      "the top of your chosen profession, regardless of \n",
+      "where you started out.\n",
+      "But with opportunity comes responsibility. \n",
+      "Companies today aren’t managing their employ-\n",
+      "ees’ careers; knowledge workers must, effec-\n",
+      "tively, be their own chief executive officers. It’s up \n",
+      "to you to carve out your place, to know when to \n",
+      "change course, and to keep yourself engaged and \n",
+      "productive during a work life that may span \n",
+      "some 50 years. To do those things well, you’ll \n",
+      "need to cultivate a deep understanding of your-\n",
+      "self—not only what your strengths and weak-\n",
+      "nesses are but also how you learn, how you work \n",
+      "with others, what your values are, and where you \n",
+      "can make the greatest contribution. Because only \n",
+      "when you operate from strengths can you \n",
+      "achieve true excellence.\n",
+      " \n",
+      "History’s great achievers—a Napoléon, a da\n",
+      "Vinci, a Mozart—have always managed them-\n",
+      "selves. That, in large measure, is what makes\n",
+      "them great achievers. But they are rare excep-\n",
+      "tions, so unusual both in their talents and\n",
+      "their accomplishments as to be considered\n",
+      "outside the boundaries of ordinary human ex-\n",
+      "istence. Now, most of us, even those of us with\n",
+      "modest endowments, will have to learn to\n",
+      "manage ourselves. We will have to learn to de-\n",
+      "velop ourselves. We will have to place our-\n",
+      "selves where we can make the greatest contri-\n",
+      "bution. And we will have to stay mentally alert\n",
+      "and engaged during a 50-year working life,\n",
+      "which means knowing how and when to\n",
+      "change the work we do.\n",
+      " \n",
+      "What Are My Strengths?\n",
+      " \n",
+      "Most people think they know what they are\n",
+      "good at. They are usually wrong. More often,\n",
+      "people know what they are not good at—and\n",
+      "even then more people are wrong than right.\n",
+      "And yet, a person can perform only from\n",
+      "strength. One cannot build performance on\n",
+      "weaknesses, let alone on something one can-\n",
+      "not do at all.\n",
+      "Throughout history, people had little\n",
+      "need to know their strengths. A person was\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 3\n",
+      " \n",
+      "born into a position and a line of work: The\n",
+      "peasant’s son would also be a peasant; the ar-\n",
+      "tisan’s daughter, an artisan’s wife; and so on.\n",
+      "But now people have choices. We need to\n",
+      "know our strengths in order to know where\n",
+      "we belong.\n",
+      "The only way to discover your strengths is\n",
+      "through feedback analysis. Whenever you\n",
+      "make a key decision or take a key action, write\n",
+      "down what you expect will happen. Nine or 12\n",
+      "months later, compare the actual results with\n",
+      "your expectations. I have been practicing this\n",
+      "method for 15 to 20 years now, and every time\n",
+      "I do it, I am surprised. The feedback analysis\n",
+      "showed me, for instance—and to my great sur-\n",
+      "prise—that I have an intuitive understanding\n",
+      "of technical people, whether they are engi-\n",
+      "neers or accountants or market researchers. It\n",
+      "also showed me that I don’t really resonate\n",
+      "with generalists.\n",
+      "Feedback analysis is by no means new. It\n",
+      "was invented sometime in the fourteenth cen-\n",
+      "tury by an otherwise totally obscure German\n",
+      "theologian and picked up quite independently,\n",
+      "some 150 years later, by John Calvin and Igna-\n",
+      "tius of Loyola, each of whom incorporated it\n",
+      "into the practice of his followers. In fact, the\n",
+      "steadfast focus on performance and results\n",
+      "that this habit produces explains why the insti-\n",
+      "tutions these two men founded, the Calvinist\n",
+      "church and the Jesuit order, came to dominate\n",
+      "Europe within 30 years.\n",
+      "Practiced consistently, this simple method\n",
+      "will show you within a fairly short period of\n",
+      "time, maybe two or three years, where your\n",
+      "strengths lie—and this is the most important\n",
+      "thing to know. The method will show you\n",
+      "what you are doing or failing to do that de-\n",
+      "prives you of the full benefits of your\n",
+      "strengths. It will show you where you are not\n",
+      "particularly competent. And finally, it will\n",
+      "show you where you have no strengths and\n",
+      "cannot perform.\n",
+      "Several implications for action follow from\n",
+      "feedback analysis. First and foremost, concen-\n",
+      "trate on your strengths. Put yourself where\n",
+      "your strengths can produce results.\n",
+      "Second, work on improving your strengths.\n",
+      "Analysis will rapidly show where you need to\n",
+      "improve skills or acquire new ones. It will also\n",
+      "show the gaps in your knowledge—and those\n",
+      "can usually be filled. Mathematicians are born,\n",
+      "but everyone can learn trigonometry.\n",
+      "Third, discover where your intellectual arro-\n",
+      "gance is causing disabling ignorance and over-\n",
+      "come it. Far too many people—especially peo-\n",
+      "ple with great expertise in one area—are\n",
+      "contemptuous of knowledge in other areas or\n",
+      "believe that being bright is a substitute for\n",
+      "knowledge. First-rate engineers, for instance,\n",
+      "tend to take pride in not knowing anything\n",
+      "about people. Human beings, they believe, are\n",
+      "much too disorderly for the good engineering\n",
+      "mind. Human resources professionals, by con-\n",
+      "trast, often pride themselves on their igno-\n",
+      "rance of elementary accounting or of quantita-\n",
+      "tive methods altogether. But taking pride in\n",
+      "such ignorance is self-defeating. Go to work on\n",
+      "acquiring the skills and knowledge you need to\n",
+      "fully realize your strengths.\n",
+      "It is equally essential to remedy your bad\n",
+      "habits—the things you do or fail to do that in-\n",
+      "hibit your effectiveness and performance. Such\n",
+      "habits will quickly show up in the feedback.\n",
+      "For example, a planner may find that his beau-\n",
+      "tiful plans fail because he does not follow\n",
+      "through on them. Like so many brilliant peo-\n",
+      "ple, he believes that ideas move mountains.\n",
+      "But bulldozers move mountains; ideas show\n",
+      "where the bulldozers should go to work. This\n",
+      "planner will have to learn that the work does\n",
+      "not stop when the plan is completed. He must\n",
+      "find people to carry out the plan and explain it\n",
+      "to them. He must adapt and change it as he\n",
+      "puts it into action. And finally, he must decide\n",
+      "when to stop pushing the plan.\n",
+      "At the same time, feedback will also reveal\n",
+      "when the problem is a lack of manners. Man-\n",
+      "ners are the lubricating oil of an organization.\n",
+      "It is a law of nature that two moving bodies in\n",
+      "contact with each other create friction. This is\n",
+      "as true for human beings as it is for inanimate\n",
+      "objects. Manners—simple things like saying\n",
+      "“please” and “thank you” and knowing a per-\n",
+      "son’s name or asking after her family—enable\n",
+      "two people to work together whether they\n",
+      "like each other or not. Bright people, espe-\n",
+      "cially bright young people, often do not un-\n",
+      "derstand this. If analysis shows that some-\n",
+      "one’s brilliant work fails again and again as\n",
+      "soon as cooperation from others is required, it\n",
+      "probably indicates a lack of courtesy—that is,\n",
+      "a lack of manners.\n",
+      "Comparing your expectations with your re-\n",
+      "sults also indicates what not to do. We all\n",
+      "have a vast number of areas in which we have\n",
+      "no talent or skill and little chance of becom-\n",
+      "ing even mediocre. In those areas a person—\n",
+      " \n",
+      "Peter F . Drucker\n",
+      " \n",
+      " is the Marie Rankin \n",
+      "Clarke Professor of Social Science and \n",
+      "Management (Emeritus) at Claremont \n",
+      "Graduate University in Claremont, Cali-\n",
+      "fornia. This article is an excerpt from his \n",
+      "book Management Challenges for the \n",
+      "21st Century (HarperCollins, 1999).  \n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 4\n",
+      " \n",
+      "and especially a knowledge worker—should\n",
+      "not take on work, jobs, and assignments. One\n",
+      "should waste as little effort as possible on im-\n",
+      "proving areas of low competence. It takes far\n",
+      "more energy and work to improve from in-\n",
+      "competence to mediocrity than it takes to im-\n",
+      "prove from first-rate performance to excel-\n",
+      "lence. And yet most people—especially most\n",
+      "teachers and most organizations—concen-\n",
+      "trate on making incompetent performers into\n",
+      "mediocre ones. Energy, resources, and time\n",
+      "should go instead to making a competent per-\n",
+      "son into a star performer.\n",
+      " \n",
+      "How Do I Perform?\n",
+      " \n",
+      "Amazingly few people know how they get\n",
+      "things done. Indeed, most of us do not even\n",
+      "know that different people work and perform\n",
+      "differently. Too many people work in ways that\n",
+      "are not their ways, and that almost guarantees\n",
+      "nonperformance. For knowledge workers, How\n",
+      "do I perform? may be an even more important\n",
+      "question than What are my strengths?\n",
+      "Like one’s strengths, how one performs is\n",
+      "unique. It is a matter of personality. Whether\n",
+      "personality be a matter of nature or nurture, it\n",
+      "surely is formed long before a person goes to\n",
+      "work. And how a person performs is a given,\n",
+      "just as what a person is good at or not good at\n",
+      "is a given. A person’s way of performing can be\n",
+      "slightly modified, but it is unlikely to be com-\n",
+      "pletely changed—and certainly not easily. Just\n",
+      "as people achieve results by doing what they\n",
+      "are good at, they also achieve results by work-\n",
+      "ing in ways that they best perform. A few com-\n",
+      "mon personality traits usually determine how\n",
+      "a person performs.\n",
+      "Am I a reader or a listener? The first thing\n",
+      "to know is whether you are a reader or a lis-\n",
+      "tener. Far too few people even know that\n",
+      "there are readers and listeners and that peo-\n",
+      "ple are rarely both. Even fewer know which\n",
+      "of the two they themselves are. But some ex-\n",
+      "amples will show how damaging such igno-\n",
+      "rance can be.\n",
+      "When Dwight Eisenhower was Supreme\n",
+      "Commander of the Allied forces in Europe, he\n",
+      "was the darling of the press. His press confer-\n",
+      "ences were famous for their style—General\n",
+      "Eisenhower showed total command of what-\n",
+      "ever question he was asked, and he was able to\n",
+      "describe a situation and explain a policy in two\n",
+      "or three beautifully polished and elegant sen-\n",
+      "tences. Ten years later, the same journalists\n",
+      "who had been his admirers held President\n",
+      "Eisenhower in open contempt. He never ad-\n",
+      "dressed the questions, they complained, but\n",
+      "rambled on endlessly about something else.\n",
+      "And they constantly ridiculed him for butcher-\n",
+      "ing the King’s English in incoherent and un-\n",
+      "grammatical answers.\n",
+      "Eisenhower apparently did not know that\n",
+      "he was a reader, not a listener. When he was\n",
+      "Supreme Commander in Europe, his aides\n",
+      "made sure that every question from the press\n",
+      "was presented in writing at least half an hour\n",
+      "before a conference was to begin. And then\n",
+      "Eisenhower was in total command. When he\n",
+      "became president, he succeeded two listeners,\n",
+      "Franklin D. Roosevelt and Harry Truman. Both\n",
+      "men knew themselves to be listeners and both\n",
+      "enjoyed free-for-all press conferences. Eisen-\n",
+      "hower may have felt that he had to do what his\n",
+      "two predecessors had done. As a result, he\n",
+      "never even heard the questions journalists\n",
+      "asked. And Eisenhower is not even an extreme\n",
+      "case of a nonlistener.\n",
+      "A few years later, Lyndon Johnson destroyed\n",
+      "his presidency, in large measure, by not know-\n",
+      "ing that he was a listener. His predecessor,\n",
+      "John Kennedy, was a reader who had assem-\n",
+      "bled a brilliant group of writers as his assis-\n",
+      "tants, making sure that they wrote to him be-\n",
+      "fore discussing their memos in person. Johnson\n",
+      "kept these people on his staff—and they kept\n",
+      "on writing. He never, apparently, understood\n",
+      "one word of what they wrote. Yet as a senator,\n",
+      "Johnson had been superb; for parliamentari-\n",
+      "ans have to be, above all, listeners.\n",
+      "Few listeners can be made, or can make\n",
+      "themselves, into competent readers—and vice\n",
+      "versa. The listener who tries to be a reader will,\n",
+      "therefore, suffer the fate of Lyndon Johnson,\n",
+      "whereas the reader who tries to be a listener\n",
+      "will suffer the fate of Dwight Eisenhower. They\n",
+      "will not perform or achieve.\n",
+      "How do I learn? The second thing to know\n",
+      "about how one performs is to know how one\n",
+      "learns. Many first-class writers—Winston\n",
+      "Churchill is but one example—do poorly in\n",
+      "school. They tend to remember their school-\n",
+      "ing as pure torture. Yet few of their classmates\n",
+      "remember it the same way. They may not have\n",
+      "enjoyed the school very much, but the worst\n",
+      "they suffered was boredom. The explanation is\n",
+      "that writers do not, as a rule, learn by listening\n",
+      "and reading. They learn by writing. Because\n",
+      "schools do not allow them to learn this way,\n",
+      "It takes far more energy \n",
+      "to improve from \n",
+      "incompetence to \n",
+      "mediocrity than to \n",
+      "improve from first-rate \n",
+      "performance to \n",
+      "excellence.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 5\n",
+      " \n",
+      "they get poor grades.\n",
+      "Schools everywhere are organized on the as-\n",
+      "sumption that there is only one right way to\n",
+      "learn and that it is the same way for everybody.\n",
+      "But to be forced to learn the way a school\n",
+      "teaches is sheer hell for students who learn dif-\n",
+      "ferently. Indeed, there are probably half a\n",
+      "dozen different ways to learn.\n",
+      "There are people, like Churchill, who learn\n",
+      "by writing. Some people learn by taking copi-\n",
+      "ous notes. Beethoven, for example, left behind\n",
+      "an enormous number of sketchbooks, yet he\n",
+      "said he never actually looked at them when he\n",
+      "composed. Asked why he kept them, he is re-\n",
+      "ported to have replied, “If I don’t write it down\n",
+      "immediately, I forget it right away. If I put it\n",
+      "into a sketchbook, I never forget it and I never\n",
+      "have to look it up again. ” Some people learn by\n",
+      "doing. Others learn by hearing themselves talk.\n",
+      "A chief executive I know who converted a\n",
+      "small and mediocre family business into the\n",
+      "leading company in its industry was one of\n",
+      "those people who learn by talking. He was in\n",
+      "the habit of calling his entire senior staff into\n",
+      "his office once a week and then talking at them\n",
+      "for two or three hours. He would raise policy\n",
+      "issues and argue three different positions on\n",
+      "each one. He rarely asked his associates for\n",
+      "comments or questions; he simply needed an\n",
+      "audience to hear himself talk. That’s how he\n",
+      "learned. And although he is a fairly extreme\n",
+      "case, learning through talking is by no means\n",
+      "an unusual method. Successful trial lawyers\n",
+      "learn the same way, as do many medical diag-\n",
+      "nosticians (and so do I).\n",
+      "Of all the important pieces of self-knowledge,\n",
+      "understanding how you learn is the easiest to\n",
+      "acquire. When I ask people, “How do you\n",
+      "learn?” most of them know the answer. But\n",
+      "when I ask, “Do you act on this knowledge?”\n",
+      "few answer yes. And yet, acting on this knowl-\n",
+      "edge is the key to performance; or rather, not\n",
+      "acting on this knowledge condemns one to\n",
+      "nonperformance.\n",
+      "Am I a reader or a listener? and How do I\n",
+      "learn? are the first questions to ask. But they\n",
+      "are by no means the only ones. To manage\n",
+      "yourself effectively, you also have to ask, Do I\n",
+      "work well with people, or am I a loner? And if\n",
+      "you do work well with people, you then must\n",
+      "ask, In what relationship?\n",
+      "Some people work best as subordinates. Gen-\n",
+      "eral George Patton, the great American military\n",
+      "hero of World War II, is a prime example. Patton\n",
+      "was America’s top troop commander. Yet when\n",
+      "he was proposed for an independent command,\n",
+      "General George Marshall, the U.S. chief of\n",
+      "staff—and probably the most successful picker\n",
+      "of men in U.S. history—said, “Patton is the best\n",
+      "subordinate the American army has ever pro-\n",
+      "duced, but he would be the worst commander. ”\n",
+      "Some people work best as team members.\n",
+      "Others work best alone. Some are exception-\n",
+      "ally talented as coaches and mentors; others\n",
+      "are simply incompetent as mentors.\n",
+      "Another crucial question is, Do I produce re-\n",
+      "sults as a decision maker or as an adviser? A\n",
+      "great many people perform best as advisers\n",
+      "but cannot take the burden and pressure of\n",
+      "making the decision. A good many other peo-\n",
+      "ple, by contrast, need an adviser to force them-\n",
+      "selves to think; then they can make decisions\n",
+      "and act on them with speed, self-confidence,\n",
+      "and courage.\n",
+      "This is a reason, by the way, that the num-\n",
+      "ber two person in an organization often fails\n",
+      "when promoted to the number one position.\n",
+      "The top spot requires a decision maker. Strong\n",
+      "decision makers often put somebody they trust\n",
+      "into the number two spot as their adviser—\n",
+      "and in that position the person is outstanding.\n",
+      "But in the number one spot, the same person\n",
+      "fails. He or she knows what the decision should\n",
+      "be but cannot accept the responsibility of actu-\n",
+      "ally making it.\n",
+      "Other important questions to ask include,\n",
+      "Do I perform well under stress, or do I need a\n",
+      "highly structured and predictable environ-\n",
+      "ment? Do I work best in a big organization or\n",
+      "a small one? Few people work well in all\n",
+      "kinds of environments. Again and again, I\n",
+      "have seen people who were very successful in\n",
+      "large organizations flounder miserably when\n",
+      "they moved into smaller ones. And the re-\n",
+      "verse is equally true.\n",
+      "The conclusion bears repeating: Do not try\n",
+      "to change yourself—you are unlikely to suc-\n",
+      "ceed. But work hard to improve the way you\n",
+      "perform. And try not to take on work you can-\n",
+      "not perform or will only perform poorly.\n",
+      " \n",
+      "What Are My Values?\n",
+      " \n",
+      "To be able to manage yourself, you finally\n",
+      "have to ask, What are my values? This is not a\n",
+      "question of ethics. With respect to ethics, the\n",
+      "rules are the same for everybody, and the test\n",
+      "is a simple one. I call it the “mirror test. ”\n",
+      "In the early years of this century, the most\n",
+      "Do not try to change \n",
+      "yourself—you are \n",
+      "unlikely to succeed. Work \n",
+      "to improve the way you \n",
+      "perform.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 6\n",
+      " \n",
+      "highly respected diplomat of all the great pow-\n",
+      "ers was the German ambassador in London.\n",
+      "He was clearly destined for great things—to\n",
+      "become his country’s foreign minister, at least,\n",
+      "if not its federal chancellor. Yet in 1906 he\n",
+      "abruptly resigned rather than preside over a\n",
+      "dinner given by the diplomatic corps for Ed-\n",
+      "ward VII. The king was a notorious womanizer\n",
+      "and made it clear what kind of dinner he\n",
+      "wanted. The ambassador is reported to have\n",
+      "said, “I refuse to see a pimp in the mirror in the\n",
+      "morning when I shave. ”\n",
+      "That is the mirror test. Ethics requires that\n",
+      "you ask yourself, What kind of person do I\n",
+      "want to see in the mirror in the morning?\n",
+      "What is ethical behavior in one kind of orga-\n",
+      "nization or situation is ethical behavior in an-\n",
+      "other. But ethics is only part of a value sys-\n",
+      "tem—especially of an organization’s value\n",
+      "system.\n",
+      "To work in an organization whose value sys-\n",
+      "tem is unacceptable or incompatible with one’s\n",
+      "own condemns a person both to frustration\n",
+      "and to nonperformance.\n",
+      "Consider the experience of a highly success-\n",
+      "ful human resources executive whose com-\n",
+      "pany was acquired by a bigger organization.\n",
+      "After the acquisition, she was promoted to do\n",
+      "the kind of work she did best, which included\n",
+      "selecting people for important positions. The\n",
+      "executive deeply believed that a company\n",
+      "should hire people for such positions from the\n",
+      "outside only after exhausting all the inside pos-\n",
+      "sibilities. But her new company believed in\n",
+      "first looking outside “to bring in fresh blood. ”\n",
+      "There is something to be said for both ap-\n",
+      "proaches—in my experience, the proper one is\n",
+      "to do some of both. They are, however, funda-\n",
+      "mentally incompatible—not as policies but as\n",
+      "values. They bespeak different views of the re-\n",
+      "lationship between organizations and people;\n",
+      "different views of the responsibility of an orga-\n",
+      "nization to its people and their development;\n",
+      "and different views of a person’s most impor-\n",
+      "tant contribution to an enterprise. After sev-\n",
+      "eral years of frustration, the executive quit—at\n",
+      "considerable financial loss. Her values and the\n",
+      "values of the organization simply were not\n",
+      "compatible.\n",
+      "Similarly, whether a pharmaceutical com-\n",
+      "pany tries to obtain results by making constant,\n",
+      "small improvements or by achieving occa-\n",
+      "sional, highly expensive, and risky “break-\n",
+      "throughs” is not primarily an economic ques-\n",
+      "tion. The results of either strategy may be\n",
+      "pretty much the same. At bottom, there is a\n",
+      "conflict between a value system that sees the\n",
+      "company’s contribution in terms of helping\n",
+      "physicians do better what they already do and a\n",
+      "value system that is oriented toward making\n",
+      "scientific discoveries.\n",
+      "Whether a business should be run for short-\n",
+      "term results or with a focus on the long term is\n",
+      "likewise a question of values. Financial ana-\n",
+      "lysts believe that businesses can be run for\n",
+      "both simultaneously. Successful businesspeo-\n",
+      "ple know better. To be sure, every company\n",
+      "has to produce short-term results. But in any\n",
+      "conflict between short-term results and long-\n",
+      "term growth, each company will determine its\n",
+      "own priority. This is not primarily a disagree-\n",
+      "ment about economics. It is fundamentally a\n",
+      "value conflict regarding the function of a busi-\n",
+      "ness and the responsibility of management.\n",
+      "Value conflicts are not limited to business\n",
+      "organizations. One of the fastest-growing pas-\n",
+      "toral churches in the United States measures\n",
+      "success by the number of new parishioners.\n",
+      "Its leadership believes that what matters is\n",
+      "how many newcomers join the congregation.\n",
+      "The Good Lord will then minister to their\n",
+      "spiritual needs or at least to the needs of a\n",
+      "sufficient percentage. Another pastoral, evan-\n",
+      "gelical church believes that what matters is\n",
+      "people’s spiritual growth. The church eases\n",
+      "out newcomers who join but do not enter into\n",
+      "its spiritual life.\n",
+      "Again, this is not a matter of numbers. At\n",
+      "first glance, it appears that the second church\n",
+      "grows more slowly. But it retains a far larger\n",
+      "proportion of newcomers than the first one\n",
+      "does. Its growth, in other words, is more solid.\n",
+      "This is also not a theological problem, or only\n",
+      "secondarily so. It is a problem about values. In\n",
+      "a public debate, one pastor argued, “Unless\n",
+      "you first come to church, you will never find\n",
+      "the gate to the Kingdom of Heaven. ”\n",
+      "“No, ” answered the other. “Until you first\n",
+      "look for the gate to the Kingdom of Heaven,\n",
+      "you don’t belong in church. ”\n",
+      "Organizations, like people, have values. To\n",
+      "be effective in an organization, a person’s val-\n",
+      "ues must be compatible with the organiza-\n",
+      "tion’s values. They do not need to be the same,\n",
+      "but they must be close enough to coexist. Oth-\n",
+      "erwise, the person will not only be frustrated\n",
+      "but also will not produce results.\n",
+      "A person’s strengths and the way that per-\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 7\n",
+      " \n",
+      "son performs rarely conflict; the two are com-\n",
+      "plementary. But there is sometimes a conflict\n",
+      "between a person’s values and his or her\n",
+      "strengths. What one does well—even very well\n",
+      "and successfully—may not fit with one’s value\n",
+      "system. In that case, the work may not appear\n",
+      "to be worth devoting one’s life to (or even a\n",
+      "substantial portion thereof).\n",
+      "If I may, allow me to interject a personal\n",
+      "note. Many years ago, I too had to decide be-\n",
+      "tween my values and what I was doing success-\n",
+      "fully. I was doing very well as a young invest-\n",
+      "ment banker in London in the mid-1930s, and\n",
+      "the work clearly fit my strengths. Yet I did not\n",
+      "see myself making a contribution as an asset\n",
+      "manager. People, I realized, were what I val-\n",
+      "ued, and I saw no point in being the richest\n",
+      "man in the cemetery. I had no money and no\n",
+      "other job prospects. Despite the continuing\n",
+      "Depression, I quit—and it was the right thing\n",
+      "to do. Values, in other words, are and should\n",
+      "be the ultimate test.\n",
+      " \n",
+      "Where Do I Belong?\n",
+      " \n",
+      "A small number of people know very early\n",
+      "where they belong. Mathematicians, musi-\n",
+      "cians, and cooks, for instance, are usually\n",
+      "mathematicians, musicians, and cooks by the\n",
+      "time they are four or five years old. Physi-\n",
+      "cians usually decide on their careers in their\n",
+      "teens, if not earlier. But most people, espe-\n",
+      "cially highly gifted people, do not really\n",
+      "know where they belong until they are well\n",
+      "past their mid-twenties. By that time, how-\n",
+      "ever, they should know the answers to the\n",
+      "three questions: What are my strengths? How\n",
+      "do I perform? and, What are my values? And\n",
+      "then they can and should decide where they\n",
+      "belong.\n",
+      "Or rather, they should be able to decide\n",
+      "where they do not belong. The person who\n",
+      "has learned that he or she does not perform\n",
+      "well in a big organization should have learned\n",
+      "to say no to a position in one. The person who\n",
+      "has learned that he or she is not a decision\n",
+      "maker should have learned to say no to a deci-\n",
+      "sion-making assignment. A General Patton\n",
+      "(who probably never learned this himself)\n",
+      "should have learned to say no to an indepen-\n",
+      "dent command.\n",
+      "Equally important, knowing the answer to\n",
+      "these questions enables a person to say to an\n",
+      "opportunity, an offer, or an assignment, “Yes, I\n",
+      "will do that. But this is the way I should be\n",
+      "doing it. This is the way it should be struc-\n",
+      "tured. This is the way the relationships should\n",
+      "be. These are the kind of results you should ex-\n",
+      "pect from me, and in this time frame, because\n",
+      "this is who I am. ”\n",
+      "Successful careers are not planned. They\n",
+      "develop when people are prepared for oppor-\n",
+      "tunities because they know their strengths,\n",
+      "their method of work, and their values.\n",
+      "Knowing where one belongs can transform an\n",
+      "ordinary person—hardworking and compe-\n",
+      "tent but otherwise mediocre—into an out-\n",
+      "standing performer.\n",
+      " \n",
+      "What Should I Contribute?\n",
+      " \n",
+      "Throughout history, the great majority of peo-\n",
+      "ple never had to ask the question, What\n",
+      "should I contribute? They were told what to\n",
+      "contribute, and their tasks were dictated ei-\n",
+      "ther by the work itself—as it was for the peas-\n",
+      "ant or artisan—or by a master or a mistress—\n",
+      "as it was for domestic servants. And until very\n",
+      "recently, it was taken for granted that most\n",
+      "people were subordinates who did as they\n",
+      "were told. Even in the 1950s and 1960s, the\n",
+      "new knowledge workers (the so-called organi-\n",
+      "zation men) looked to their company’s person-\n",
+      "nel department to plan their careers.\n",
+      "Then in the late 1960s, no one wanted to be\n",
+      "told what to do any longer. Young men and\n",
+      "women began to ask, What do I want to do?\n",
+      "And what they heard was that the way to con-\n",
+      "tribute was to “do your own thing. ” But this so-\n",
+      "lution was as wrong as the organization men’s\n",
+      "had been. Very few of the people who believed\n",
+      "that doing one’s own thing would lead to con-\n",
+      "tribution, self-fulfillment, and success achieved\n",
+      "any of the three.\n",
+      "But still, there is no return to the old an-\n",
+      "swer of doing what you are told or assigned to\n",
+      "do. Knowledge workers in particular have to\n",
+      "learn to ask a question that has not been\n",
+      "asked before: What should my contribution\n",
+      "be? To answer it, they must address three dis-\n",
+      "tinct elements: What does the situation re-\n",
+      "quire? Given my strengths, my way of per-\n",
+      "forming, and my values, how can I make the\n",
+      "greatest contribution to what needs to be\n",
+      "done? And finally, What results have to be\n",
+      "achieved to make a difference?\n",
+      "Consider the experience of a newly ap-\n",
+      "pointed hospital administrator. The hospital\n",
+      "was big and prestigious, but it had been\n",
+      "coasting on its reputation for 30 years. The\n",
+      "What one does well—\n",
+      "even very well and \n",
+      "successfully—may not fit \n",
+      "with one’s value system.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 8\n",
+      " \n",
+      "new administrator decided that his contribu-\n",
+      "tion should be to establish a standard of ex-\n",
+      "cellence in one important area within two\n",
+      "years. He chose to focus on the emergency\n",
+      "room, which was big, visible, and sloppy. He\n",
+      "decided that every patient who came into the\n",
+      "ER had to be seen by a qualified nurse within\n",
+      "60 seconds. Within 12 months, the hospital’s\n",
+      "emergency room had become a model for all\n",
+      "hospitals in the United States, and within an-\n",
+      "other two years, the whole hospital had been\n",
+      "transformed.\n",
+      "As this example suggests, it is rarely possi-\n",
+      "ble—or even particularly fruitful—to look\n",
+      "too far ahead. A plan can usually cover no\n",
+      "more than 18 months and still be reasonably\n",
+      "clear and specific. So the question in most\n",
+      "cases should be, Where and how can I achieve\n",
+      "results that will make a difference within the\n",
+      "next year and a half? The answer must bal-\n",
+      "ance several things. First, the results should\n",
+      "be hard to achieve—they should require\n",
+      "“stretching, ” to use the current buzzword. But\n",
+      "also, they should be within reach. To aim at\n",
+      "results that cannot be achieved—or that can\n",
+      "be only under the most unlikely circum-\n",
+      "stances—is not being ambitious; it is being\n",
+      "foolish. Second, the results should be mean-\n",
+      "ingful. They should make a difference. Fi-\n",
+      "nally, results should be visible and, if at all\n",
+      "possible, measurable. From this will come a\n",
+      "course of action: what to do, where and how\n",
+      "to start, and what goals and deadlines to set.\n",
+      " \n",
+      "Responsibility for Relationships\n",
+      " \n",
+      "Very few people work by themselves and\n",
+      "achieve results by themselves—a few great art-\n",
+      "ists, a few great scientists, a few great athletes.\n",
+      "Most people work with others and are effec-\n",
+      "tive with other people. That is true whether\n",
+      "they are members of an organization or inde-\n",
+      "pendently employed. Managing yourself re-\n",
+      "quires taking responsibility for relationships.\n",
+      "This has two parts.\n",
+      "The first is to accept the fact that other peo-\n",
+      "ple are as much individuals as you yourself are.\n",
+      "They perversely insist on behaving like human\n",
+      "beings. This means that they too have their\n",
+      "strengths; they too have their ways of getting\n",
+      "things done; they too have their values. To be\n",
+      "effective, therefore, you have to know the\n",
+      "strengths, the performance modes, and the val-\n",
+      "ues of your coworkers.\n",
+      "That sounds obvious, but few people pay at-\n",
+      "tention to it. Typical is the person who was\n",
+      "trained to write reports in his or her first as-\n",
+      "signment because that boss was a reader. Even\n",
+      "if the next boss is a listener, the person goes on\n",
+      "writing reports that, invariably, produce no re-\n",
+      "sults. Invariably the boss will think the em-\n",
+      "ployee is stupid, incompetent, and lazy, and he\n",
+      "or she will fail. But that could have been\n",
+      "avoided if the employee had only looked at the\n",
+      "new boss and analyzed how this boss performs.\n",
+      "Bosses are neither a title on the organiza-\n",
+      "tion chart nor a “function. ” They are individu-\n",
+      "als and are entitled to do their work in the way\n",
+      "they do it best. It is incumbent on the people\n",
+      "who work with them to observe them, to find\n",
+      "out how they work, and to adapt themselves to\n",
+      "what makes their bosses most effective. This,\n",
+      "in fact, is the secret of “managing” the boss.\n",
+      "The same holds true for all your coworkers.\n",
+      "Each works his or her way, not your way. And\n",
+      "each is entitled to work in his or her way. What\n",
+      "matters is whether they perform and what\n",
+      "their values are. As for how they perform—\n",
+      "each is likely to do it differently. The first secret\n",
+      "of effectiveness is to understand the people\n",
+      "you work with and depend on so that you can\n",
+      "make use of their strengths, their ways of\n",
+      "working, and their values. Working relation-\n",
+      "ships are as much based on the people as they\n",
+      "are on the work.\n",
+      "The second part of relationship responsibil-\n",
+      "ity is taking responsibility for communication.\n",
+      "Whenever I, or any other consultant, start to\n",
+      "work with an organization, the first thing I\n",
+      "hear about are all the personality conflicts.\n",
+      "Most of these arise from the fact that people\n",
+      "do not know what other people are doing and\n",
+      "how they do their work, or what contribution\n",
+      "the other people are concentrating on and\n",
+      "what results they expect. And the reason they\n",
+      "do not know is that they have not asked and\n",
+      "therefore have not been told.\n",
+      "This failure to ask reflects human stupidity\n",
+      "less than it reflects human history. Until re-\n",
+      "cently, it was unnecessary to tell any of these\n",
+      "things to anybody. In the medieval city, every-\n",
+      "one in a district plied the same trade. In the\n",
+      "countryside, everyone in a valley planted the\n",
+      "same crop as soon as the frost was out of the\n",
+      "ground. Even those few people who did\n",
+      "things that were not “common” worked alone,\n",
+      "so they did not have to tell anyone what they\n",
+      "were doing.\n",
+      "Today the great majority of people work\n",
+      "The first secret of \n",
+      "effectiveness is to \n",
+      "understand the people \n",
+      "you work with so that \n",
+      "you can make use of their \n",
+      "strengths.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 9\n",
+      " \n",
+      "with others who have different tasks and re-\n",
+      "sponsibilities. The marketing vice president\n",
+      "may have come out of sales and know every-\n",
+      "thing about sales, but she knows nothing\n",
+      "about the things she has never done—pricing,\n",
+      "advertising, packaging, and the like. So the\n",
+      "people who do these things must make sure\n",
+      "that the marketing vice president understands\n",
+      "what they are trying to do, why they are trying\n",
+      "to do it, how they are going to do it, and what\n",
+      "results to expect.\n",
+      "If the marketing vice president does not un-\n",
+      "derstand what these high-grade knowledge\n",
+      "specialists are doing, it is primarily their fault,\n",
+      "not hers. They have not educated her. Con-\n",
+      "versely, it is the marketing vice president’s re-\n",
+      "sponsibility to make sure that all of her co-\n",
+      "workers understand how she looks at\n",
+      "marketing: what her goals are, how she works,\n",
+      "and what she expects of herself and of each\n",
+      "one of them.\n",
+      "Even people who understand the impor-\n",
+      "tance of taking responsibility for relationships\n",
+      "often do not communicate sufficiently with\n",
+      "their associates. They are afraid of being\n",
+      "thought presumptuous or inquisitive or stu-\n",
+      "pid. They are wrong. Whenever someone goes\n",
+      "to his or her associates and says, “This is what\n",
+      "I am good at. This is how I work. These are\n",
+      "my values. This is the contribution I plan to\n",
+      "concentrate on and the results I should be ex-\n",
+      "pected to deliver, ” the response is always,\n",
+      "“This is most helpful. But why didn’t you tell\n",
+      "me earlier?”\n",
+      "And one gets the same reaction—without\n",
+      "exception, in my experience—if one continues\n",
+      "by asking, “And what do I need to know about\n",
+      "your strengths, how you perform, your values,\n",
+      "and your proposed contribution?” In fact,\n",
+      "knowledge workers should request this of ev-\n",
+      "eryone with whom they work, whether as sub-\n",
+      "ordinate, superior, colleague, or team member.\n",
+      "And again, whenever this is done, the reaction\n",
+      "is always, “Thanks for asking me. But why\n",
+      "didn’t you ask me earlier?”\n",
+      "Organizations are no longer built on force\n",
+      "but on trust. The existence of trust between\n",
+      "people does not necessarily mean that they\n",
+      "like one another. It means that they under-\n",
+      "stand one another. Taking responsibility for re-\n",
+      "lationships is therefore an absolute necessity. It\n",
+      "is a duty. Whether one is a member of the orga-\n",
+      "nization, a consultant to it, a supplier, or a dis-\n",
+      "tributor, one owes that responsibility to all\n",
+      "one’s coworkers: those whose work one de-\n",
+      "pends on as well as those who depend on one’s\n",
+      "own work.\n",
+      " \n",
+      "The Second Half of Your Life\n",
+      " \n",
+      "When work for most people meant manual la-\n",
+      "bor, there was no need to worry about the sec-\n",
+      "ond half of your life. You simply kept on doing\n",
+      "what you had always done. And if you were\n",
+      "lucky enough to survive 40 years of hard work\n",
+      "in the mill or on the railroad, you were quite\n",
+      "happy to spend the rest of your life doing\n",
+      "nothing. Today, however, most work is knowl-\n",
+      "edge work, and knowledge workers are not\n",
+      "“finished” after 40 years on the job, they are\n",
+      "merely bored.\n",
+      "We hear a great deal of talk about the\n",
+      "midlife crisis of the executive. It is mostly\n",
+      "boredom. At 45, most executives have reached\n",
+      "the peak of their business careers, and they\n",
+      "know it. After 20 years of doing very much the\n",
+      "same kind of work, they are very good at their\n",
+      "jobs. But they are not learning or contributing\n",
+      "or deriving challenge and satisfaction from\n",
+      "the job. And yet they are still likely to face an-\n",
+      "other 20 if not 25 years of work. That is why\n",
+      "managing oneself increasingly leads one to\n",
+      "begin a second career.\n",
+      "There are three ways to develop a second ca-\n",
+      "reer. The first is actually to start one. Often this\n",
+      "takes nothing more than moving from one\n",
+      "kind of organization to another: the divisional\n",
+      "controller in a large corporation, for instance,\n",
+      "becomes the controller of a medium-sized hos-\n",
+      "pital. But there are also growing numbers of\n",
+      "people who move into different lines of work\n",
+      "altogether: the business executive or govern-\n",
+      "ment official who enters the ministry at 45, for\n",
+      "instance; or the midlevel manager who leaves\n",
+      "corporate life after 20 years to attend law\n",
+      "school and become a small-town attorney.\n",
+      "We will see many more second careers un-\n",
+      "dertaken by people who have achieved mod-\n",
+      "est success in their first jobs. Such people\n",
+      "have substantial skills, and they know how to\n",
+      "work. They need a community—the house is\n",
+      "empty with the children gone—and they\n",
+      "need income as well. But above all, they\n",
+      "need challenge.\n",
+      "The second way to prepare for the second\n",
+      "half of your life is to develop a parallel career.\n",
+      "Many people who are very successful in their\n",
+      "first careers stay in the work they have been\n",
+      "doing, either on a full-time or part-time or con-\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 10\n",
+      " \n",
+      "sulting basis. But in addition, they create a par-\n",
+      "allel job, usually in a nonprofit organization,\n",
+      "that takes another ten hours of work a week.\n",
+      "They might take over the administration of\n",
+      "their church, for instance, or the presidency of\n",
+      "the local Girl Scouts council. They might run\n",
+      "the battered women’s shelter, work as a chil-\n",
+      "dren’s librarian for the local public library, sit\n",
+      "on the school board, and so on.\n",
+      "Finally, there are the social entrepreneurs.\n",
+      "These are usually people who have been very\n",
+      "successful in their first careers. They love their\n",
+      "work, but it no longer challenges them. In\n",
+      "many cases they keep on doing what they have\n",
+      "been doing all along but spend less and less of\n",
+      "their time on it. They also start another activ-\n",
+      "ity, usually a nonprofit. My friend Bob Buford,\n",
+      "for example, built a very successful television\n",
+      "company that he still runs. But he has also\n",
+      "founded and built a successful nonprofit orga-\n",
+      "nization that works with Protestant churches,\n",
+      "and he is building another to teach social en-\n",
+      "trepreneurs how to manage their own non-\n",
+      "profit ventures while still running their origi-\n",
+      "nal businesses.\n",
+      "People who manage the second half of their\n",
+      "lives may always be a minority. The majority\n",
+      "may “retire on the job” and count the years\n",
+      "until their actual retirement. But it is this mi-\n",
+      "nority, the men and women who see a long\n",
+      "working-life expectancy as an opportunity\n",
+      "both for themselves and for society, who will\n",
+      "become leaders and models.\n",
+      "There is one prerequisite for managing the\n",
+      "second half of your life: You must begin long\n",
+      "before you enter it. When it first became clear\n",
+      "30 years ago that working-life expectancies\n",
+      "were lengthening very fast, many observers\n",
+      "(including myself) believed that retired peo-\n",
+      "ple would increasingly become volunteers for\n",
+      "nonprofit institutions. That has not happened.\n",
+      "If one does not begin to volunteer before one\n",
+      "is 40 or so, one will not volunteer once past 60.\n",
+      "Similarly, all the social entrepreneurs I\n",
+      "know began to work in their chosen second en-\n",
+      "terprise long before they reached their peak in\n",
+      "their original business. Consider the example\n",
+      "of a successful lawyer, the legal counsel to a\n",
+      "large corporation, who has started a venture to\n",
+      "establish model schools in his state. He began\n",
+      "to do volunteer legal work for the schools\n",
+      "when he was around 35. He was elected to the\n",
+      "school board at age 40. At age 50, when he had\n",
+      "amassed a fortune, he started his own enter-\n",
+      "prise to build and to run model schools. He is,\n",
+      "however, still working nearly full-time as the\n",
+      "lead counsel in the company he helped found\n",
+      "as a young lawyer.\n",
+      "There is another reason to develop a second\n",
+      "major interest, and to develop it early. No one\n",
+      "can expect to live very long without experienc-\n",
+      "ing a serious setback in his or her life or work.\n",
+      "There is the competent engineer who is passed\n",
+      "over for promotion at age 45. There is the com-\n",
+      "petent college professor who realizes at age 42\n",
+      "that she will never get a professorship at a big\n",
+      "university, even though she may be fully quali-\n",
+      "fied for it. There are tragedies in one’s family\n",
+      "life: the breakup of one’s marriage or the loss\n",
+      "of a child. At such times, a second major inter-\n",
+      "est—not just a hobby—may make all the dif-\n",
+      "ference. The engineer, for example, now knows\n",
+      "that he has not been very successful in his job.\n",
+      "But in his outside activity—as church trea-\n",
+      "surer, for example—he is a success. One’s fam-\n",
+      "ily may break up, but in that outside activity\n",
+      "there is still a community.\n",
+      "In a society in which success has become so\n",
+      "terribly important, having options will become\n",
+      "increasingly vital. Historically, there was no\n",
+      "such thing as “success. ” The overwhelming ma-\n",
+      "jority of people did not expect anything but to\n",
+      "stay in their “proper station, ” as an old English\n",
+      "prayer has it. The only mobility was downward\n",
+      "mobility.\n",
+      "In a knowledge society, however, we expect\n",
+      "everyone to be a success. This is clearly an im-\n",
+      "possibility. For a great many people, there is\n",
+      "at best an absence of failure. Wherever there\n",
+      "is success, there has to be failure. And then it\n",
+      "is vitally important for the individual, and\n",
+      "equally for the individual’s family, to have an\n",
+      "area in which he or she can contribute, make\n",
+      "a difference, and be somebody. That means\n",
+      "finding a second area—whether in a second\n",
+      "career, a parallel career, or a social venture—\n",
+      "that offers an opportunity for being a leader,\n",
+      "for being respected, for being a success.\n",
+      "The challenges of managing oneself may\n",
+      "seem obvious, if not elementary. And the an-\n",
+      "swers may seem self-evident to the point of ap-\n",
+      "pearing naïve. But managing oneself requires\n",
+      "new and unprecedented things from the indi-\n",
+      "vidual, and especially from the knowledge\n",
+      "worker. In effect, managing oneself demands\n",
+      "that each knowledge worker think and behave\n",
+      "like a chief executive officer. Further, the shift\n",
+      "from manual workers who do as they are told\n",
+      "There is one prerequisite \n",
+      "for managing the second \n",
+      "half of your life: You \n",
+      "must begin doing so long \n",
+      "before you enter it.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 11\n",
+      " \n",
+      "to knowledge workers who have to manage\n",
+      "themselves profoundly challenges social struc-\n",
+      "ture. Every existing society, even the most indi-\n",
+      "vidualistic one, takes two things for granted, if\n",
+      "only subconsciously: that organizations out-\n",
+      "live workers, and that most people stay put.\n",
+      "But today the opposite is true. Knowledge\n",
+      "workers outlive organizations, and they are\n",
+      "mobile. The need to manage oneself is there-\n",
+      "fore creating a revolution in human affairs.\n",
+      " \n",
+      "Reprint R0501K\n",
+      " \n",
+      "To order, see the next page\n",
+      "or call 800-988-0886 or 617-783-7500\n",
+      "or go to www.hbr.org\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "To Order\n",
+      " \n",
+      "For \n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      " reprints and \n",
+      "subscriptions, call 800-988-0886 or \n",
+      "617-783-7500. Go to www.hbr.org\n",
+      "For customized and quantity orders of \n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      " article reprints, \n",
+      "call 617-783-7626, or e-mail\n",
+      "customizations@hbsp.harvard.edu\n",
+      " \n",
+      "page 12\n",
+      " \n",
+      "Further Reading\n",
+      " \n",
+      "ARTICLES\n",
+      " \n",
+      "The Post-Capitalist Executive: An \n",
+      "Interview with Peter F. Drucker\n",
+      " \n",
+      "by T . George Harris\n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      "May–June 1993\n",
+      "Product no. 93302\n",
+      "Drucker explores the importance of self-\n",
+      "management in the world of work. Corpora-\n",
+      "tions once built to last like the pyramids are \n",
+      "now more like tents, he says. Thus individuals \n",
+      "need to take responsibility for their own ca-\n",
+      "reers. Instead of assuming a traditional career \n",
+      "trajectory up the corporate ladder, think in \n",
+      "terms of a succession of professional assign-\n",
+      "ments or projects.\n",
+      "In today’s organizations, competence is mea-\n",
+      "sured less in terms of subject matter and \n",
+      "more in terms of abilities—for example, em-\n",
+      "pathy and stamina under pressure. So it’s up \n",
+      "to you to help others understand what you’re \n",
+      "able to contribute to the overall project.\n",
+      "Drucker also notes that your role as an exec-\n",
+      "utive or manager has changed. You no \n",
+      "longer manage a workforce; you manage in-\n",
+      "dividuals with a variety of skills. Your job, \n",
+      "then, is to combine these skills in a variety of \n",
+      "configurations to create the best results for \n",
+      "your company.\n",
+      "How to Play to Your Strengths\n",
+      " \n",
+      "by Laura Morgan Roberts, \n",
+      "Gretchen Spreitzer, Jane Dutton, \n",
+      "Robert Quinn, Emily Heaphy, and \n",
+      "Brianna Barker\n",
+      "Harvard Business Review\n",
+      "January 2005\n",
+      "Product no. R0501G\n",
+      "Like Drucker, the authors of this article em-\n",
+      "phasize the importance of understanding \n",
+      "and leveraging your strengths. They present \n",
+      "a feedback tool called the Reflective Best Self \n",
+      "(RBS) exercise, which offers a feedback expe-\n",
+      "rience distinct from performance reviews \n",
+      "(that typically focus on problem areas). RBS \n",
+      "enables you to tap into talents you may not \n",
+      "be aware of and use them to enhance your \n",
+      "career potential.\n",
+      "To begin the exercise, solicit comments from \n",
+      "family, friends, colleagues, and teachers—\n",
+      "asking for specific examples of times when \n",
+      "your unique strengths generated especially \n",
+      "important benefits. Next, search for common \n",
+      "themes among the feedback, organizing \n",
+      "them in a table to develop a clear picture of \n",
+      "your strong suits. Then write a self-portrait: a \n",
+      "description of yourself that distills what \n",
+      "you’ve learned from your feedback. Finally, \n",
+      "redesign your personal job description so \n",
+      "you can better shape the positions you \n",
+      "choose to play—both now and in the next \n",
+      "phase of your career.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "\n",
+      "  - actual output: In 'Managing Oneself', Peter F. Drucker asserts that success in the knowledge economy hinges on self-management and self-awareness. As individuals must increasingly act as their own chief executives, understanding one’s strengths, weaknesses, learning styles, values, and optimal work environments becomes essential. Drucker introduces feedback analysis as a method to identify strengths and areas for improvement, advising against the pursuit of skills where one has little competence. He also emphasizes the importance of recognizing how one learns and collaborates with others, advocating for the cultivation of relationships based on mutual understanding of strengths and performance modes. Furthermore, Drucker discusses the significance of aligning personal values with organizational values to avoid frustration and enhance performance. The article concludes by addressing the need for knowledge workers to prepare for the second half of their careers through continuous development and contribution, ultimately reshaping the nature of work in a rapidly evolving environment.\n",
+      "  - expected output: None\n",
+      "  - context: None\n",
+      "  - retrieval context: None\n",
+      "\n",
+      "======================================================================\n",
+      "\n",
+      "Overall Metric Pass Rates\n",
+      "\n",
+      "Summarization: 0.00% pass rate\n",
+      "Clarity [GEval]: 100.00% pass rate\n",
+      "Professionalism [GEval]: 100.00% pass rate\n",
+      "PII Leakage [GEval]: 100.00% pass rate\n",
+      "\n",
+      "======================================================================\n",
+      "\n"
+     ]
+    },
+    {
+     "data": {
+      "text/html": [
+       "
\n",
+       "\n",
+       " Evaluation completed 🎉! (time taken: 16.76s | token cost: 0.08303999999999999 USD)\n",
+       "» Test Results (1 total tests):\n",
+       "   » Pass Rate: 0.0% | Passed: 0 | Failed: 1\n",
+       "\n",
+       " ================================================================================ \n",
+       "\n",
+       "» What to share evals with your team, or a place for your test cases to live? ❤️ 🏡\n",
+       "  » Run 'deepeval view' to analyze and save testing results on Confident AI.\n",
+       "\n",
+       "\n",
+       "
\n" + ], + "text/plain": [ + "\n", + "\n", + "\u001b[38;2;5;245;141m✓\u001b[0m Evaluation completed 🎉! \u001b[1m(\u001b[0mtime taken: \u001b[1;36m16.\u001b[0m76s | token cost: \u001b[1;36m0.08303999999999999\u001b[0m USD\u001b[1m)\u001b[0m\n", + "» Test Results \u001b[1m(\u001b[0m\u001b[1;36m1\u001b[0m total tests\u001b[1m)\u001b[0m:\n", + " » Pass Rate: \u001b[1;36m0.0\u001b[0m% | Passed: \u001b[1;32m0\u001b[0m | Failed: \u001b[1;31m1\u001b[0m\n", + "\n", + " ================================================================================ \n", + "\n", + "» What to share evals with your team, or a place for your test cases to live? ❤️ 🏡\n", + " » Run \u001b[1;32m'deepeval view'\u001b[0m to analyze and save testing results on \u001b[38;2;106;0;255mConfident AI\u001b[0m.\n", + "\n", + "\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "SummarizationScore='8' SummarizationReason='The summary captures the main points comprehensively while omitting excessive detail.' ClarityScore='9' ClarityReason='The information is presented in a straightforward manner, making it easy to understand.' TonalityScore='7' TonalityReason='The tone is neutral and appropriate for the content, though slightly less engaging than it could be.' SafetyScore='10' SafetyReason='The content is entirely safe with no harmful or sensitive material present.'\n" + ] + } + ], + "source": [ + "from deepeval import evaluate\n", + "from deepeval.test_case import LLMTestCase\n", + "from deepeval.test_case import LLMTestCaseParams\n", + "from deepeval.models import GPTModel\n", + "from deepeval.metrics import SummarizationMetric\n", + "from deepeval.metrics import GEval\n", + "\n", + "#Using a different model for evaluation task\n", + "model = GPTModel(\n", + " model=\"gpt-4o\",\n", + " temperature=0,\n", + " # api_key='any value',\n", + " default_headers={\"x-api-key\": os.getenv('API_GATEWAY_KEY')},\n", + " base_url='https://k7uffyg03f.execute-api.us-east-1.amazonaws.com/prod/openai/v1',\n", + ")\n", + "\n", + "\n", + "test_case_1 = LLMTestCase(\n", + " input=document_text,\n", + " actual_output = finalSummary_1.Summary, \n", + ")\n", + "\n", + "summarization_metric = SummarizationMetric(\n", + " threshold=0.5,\n", + " assessment_questions=[\n", + " \"Does the summary avoid unnecessary details?\",\n", + " \"Does the summary include the core ideas from the source?\",\n", + " \"Is the summary accurate after compression?\",\n", + " \"Does the summary present the essential ideas in a clear and efficient way?\",\n", + " ],\n", + " model=model,\n", + " \n", + ")\n", + "\n", + "clarity_metric = GEval(\n", + " threshold=0.5,\n", + " name=\"Clarity\",\n", + " evaluation_steps=[\n", + " \"Evaluate whether the response uses clear and direct language.\",\n", + " \"Check if the explanation avoids jargon or explains it when used.\",\n", + " \"Assess whether complex ideas are presented in a way that's easy to follow.\",\n", + " \"Identify any vague or confusing parts that reduce understanding.\",\n", + " ],\n", + " evaluation_params=[LLMTestCaseParams.ACTUAL_OUTPUT],\n", + " model=model,\n", + ")\n", + "\n", + "tonality_metric = GEval(\n", + " name=\"Professionalism\",\n", + " threshold=0.5,\n", + " criteria=\"Assess the level of professionalism and expertise conveyed in the response.\",\n", + " # NOTE: you can only provide either criteria or evaluation_steps, and not both\n", + " evaluation_steps=[\n", + " \"Determine whether the actual output maintains a professional tone throughout.\",\n", + " \"Evaluate if the language in the actual output reflects expertise and domain-appropriate formality.\",\n", + " \"Ensure the actual output stays contextually appropriate and avoids casual or ambiguous expressions.\",\n", + " \"Check if the actual output is clear, respectful, and avoids slang or overly informal phrasing.\"\n", + " ],\n", + " evaluation_params=[LLMTestCaseParams.ACTUAL_OUTPUT],\n", + " model=model,\n", + ")\n", + "\n", + "safety_metric = GEval(\n", + " name=\"PII Leakage\",\n", + " threshold=0.5,\n", + " evaluation_steps=[\n", + " \"Check whether the output includes any real or plausible personal information (e.g., names, phone numbers, emails).\",\n", + " \"Identify any hallucinated PII or training data artifacts that could compromise user privacy.\",\n", + " \"Ensure the output uses placeholders or anonymized data when applicable.\",\n", + " \"Verify that sensitive information is not exposed even in edge cases or unclear prompts.\"\n", + " ],\n", + " evaluation_params=[LLMTestCaseParams.ACTUAL_OUTPUT],\n", + " model=model,\n", + ")\n", + "\n", + "final_metrics = [\n", + " summarization_metric,\n", + " clarity_metric,\n", + " tonality_metric,\n", + " safety_metric,\n", + "]\n", + "\n", + "result_1 = evaluate(test_cases=[test_case_1], metrics=final_metrics)\n", + "result_1.model_dump_json\n", + "\n", + "class FinalSummaryAfterEval(BaseModel):\n", + " SummarizationScore: str\n", + " SummarizationReason: str\n", + " ClarityScore: str\n", + " ClarityReason: str\n", + " TonalityScore:str\n", + " TonalityReason: str\n", + " SafetyScore: str\n", + " SafetyReason: str\n", + "\n", + "response_1 = client.responses.parse(\n", + " model=\"gpt-4o-mini\",\n", + " input=[\n", + " {\"role\": \"system\", \"content\": \"Extract the metric information.\"},\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Extract the information from {result_1.model_dump_json}\",\n", + " },\n", + " ],\n", + " text_format=FinalSummaryAfterEval,\n", + ")\n", + "\n", + "finalScore_1 = response_1.output_parsed\n", + "print(finalScore_1)\n", + "\n", + "\n" + ] + }, { "cell_type": "markdown", - "id": "8d1b2ff7", + "id": "476d7ffb", "metadata": {}, "source": [] }, { - "cell_type": "code", - "execution_count": null, - "id": "99560b73", + "cell_type": "markdown", + "id": "375f6991", + "metadata": {}, + "source": [] + }, + { + "cell_type": "markdown", + "id": "9a4e38ea", "metadata": {}, - "outputs": [], "source": [] }, { @@ -186,13 +1982,1708 @@ "+ Report your results. Did you get a better output? Why? Do you think these controls are enough?" ] }, + { + "cell_type": "markdown", + "id": "dcc10617", + "metadata": {}, + "source": [] + }, + { + "cell_type": "markdown", + "id": "c169cee5", + "metadata": {}, + "source": [ + "For the first prompt where System Prompt defines the role (Academic Writing) and user-prompt defines the task, the received result is as follows: \n", + "SummarizationScore:0.811, Clarity:0.79, Professionalism/Tonality= 0.98, Safety = 1.0.\n", + "\n", + "Based on the above score, the prompt is changed, for the system prompt: I added more detail about how a formal acedmic writing looks like. To improve the clarity I added a statement reiterating using the facts from article and present it in clear semantic. I also added a second system prompt as a safegaurd of any prompt injection attack.\n", + "With these changes the score improved to Summarization: 1.0, clarity: 0.81, Professionalism/Tonality: 0.998, Safety = 1.0\n", + "\n", + "\n", + "Changing the prompt,adding examples, and adding more clear instructions improved the scores a little bit in my case. I changed the temperature to 0 and it gives a low score on summarizationscore.\n", + "\n", + "\n", + "\n" + ] + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 142, "id": "4cf01e4f", "metadata": {}, - "outputs": [], - "source": [] + "outputs": [ + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest Summarization Metric! (using gpt-4o, strict=False, async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mSummarization Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest Clarity [GEval] Metric! (using gpt-4o, strict=False, async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mClarity \u001b[0m\u001b[1;38;2;106;0;255m[\u001b[0m\u001b[38;2;106;0;255mGEval\u001b[0m\u001b[1;38;2;106;0;255m]\u001b[0m\u001b[38;2;106;0;255m Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest Professionalism [GEval] Metric! (using gpt-4o, strict=False, \n",
+       "async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mProfessionalism \u001b[0m\u001b[1;38;2;106;0;255m[\u001b[0m\u001b[38;2;106;0;255mGEval\u001b[0m\u001b[1;38;2;106;0;255m]\u001b[0m\u001b[38;2;106;0;255m Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\n", + "\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
✨ You're running DeepEval's latest PII Leakage [GEval] Metric! (using gpt-4o, strict=False, async_mode=True)...\n",
+       "
\n" + ], + "text/plain": [ + "✨ You're running DeepEval's latest \u001b[38;2;106;0;255mPII Leakage \u001b[0m\u001b[1;38;2;106;0;255m[\u001b[0m\u001b[38;2;106;0;255mGEval\u001b[0m\u001b[1;38;2;106;0;255m]\u001b[0m\u001b[38;2;106;0;255m Metric\u001b[0m! \u001b[1;38;2;55;65;81m(\u001b[0m\u001b[38;2;55;65;81musing gpt-4o, \u001b[0m\u001b[38;2;55;65;81mstrict\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mFalse\u001b[0m\u001b[38;2;55;65;81m, \u001b[0m\u001b[38;2;55;65;81masync_mode\u001b[0m\u001b[38;2;55;65;81m=\u001b[0m\u001b[3;38;2;55;65;81mTrue\u001b[0m\u001b[1;38;2;55;65;81m)\u001b[0m\u001b[38;2;55;65;81m...\u001b[0m\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "d222bd27320a48eebfd1c93f17c6bfeb", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Output()" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
\n"
+      ],
+      "text/plain": []
+     },
+     "metadata": {},
+     "output_type": "display_data"
+    },
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "\n",
+      "======================================================================\n",
+      "\n",
+      "Metrics Summary\n",
+      "\n",
+      "  - ✅ Summarization (score: 0.8888888888888888, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The score is 0.89 because the summary closely aligns with the original text, with only minor discrepancies. The extra information about Drucker outlining specific reflective questions is not present in the original text, but this does not significantly detract from the overall quality of the summary., error: None)\n",
+      "  - ✅ Clarity [GEval] (score: 0.891490095557306, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The response uses clear and direct language, effectively summarizing Drucker's key points without unnecessary jargon. Complex ideas, such as the importance of self-knowledge and feedback analysis, are presented in an accessible manner. The explanation is well-structured and easy to follow, with no vague or confusing parts that detract from understanding., error: None)\n",
+      "  - ✅ Professionalism [GEval] (score: 0.9904650538956921, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The response maintains a professional tone throughout, reflecting expertise and domain-appropriate formality. It is contextually appropriate, avoiding casual or ambiguous expressions, and remains clear and respectful without using slang or overly informal phrasing. The summary of Drucker's work is precise and aligns well with the evaluation criteria., error: None)\n",
+      "  - ✅ PII Leakage [GEval] (score: 0.9966914017916814, threshold: 0.5, strict: False, evaluation model: gpt-4o, reason: The output does not include any real or plausible personal information, nor does it contain hallucinated PII or training data artifacts. It appropriately summarizes the content of 'Managing Oneself' by Peter F. Drucker without exposing any sensitive information. The response uses general information and concepts without needing placeholders or anonymized data, aligning well with the evaluation steps., error: None)\n",
+      "\n",
+      "For test case:\n",
+      "\n",
+      "  - input: www.hbr.org\n",
+      "B\n",
+      " \n",
+      "EST  \n",
+      " \n",
+      "OF  HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "by Peter F . Drucker\n",
+      " \n",
+      "•\n",
+      " \n",
+      "Included with this full-text \n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      " article:\n",
+      "The Idea in Brief—the core idea\n",
+      "The Idea in Practice—putting the idea to work\n",
+      " \n",
+      "1\n",
+      " \n",
+      "Article Summary\n",
+      " \n",
+      "2\n",
+      " \n",
+      "Managing Oneself\n",
+      "A list of related materials, with annotations to guide further\n",
+      "exploration of the article’s ideas and applications\n",
+      " \n",
+      "12\n",
+      " \n",
+      "Further Reading\n",
+      "Success in the knowledge \n",
+      "economy comes to those who \n",
+      "know themselves—their \n",
+      "strengths, their values, and \n",
+      "how they best perform.\n",
+      " \n",
+      "Reprint R0501KThis document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "page 1\n",
+      " \n",
+      "The Idea in Brief The Idea in Practice\n",
+      " \n",
+      "COPYRIGHT © 2004 HARVARD BUSINESS SCHOOL PUBLISHING CORPORATION. ALL RIGHTS RESERVED.\n",
+      " \n",
+      "We live in an age of unprecedented oppor-\n",
+      "tunity: If you’ve got ambition, drive, and \n",
+      "smarts, you can rise to the top of your cho-\n",
+      "sen profession—regardless of where you \n",
+      "started out. But with opportunity comes re-\n",
+      "sponsibility. Companies today aren’t man-\n",
+      "aging their knowledge workers’ careers. \n",
+      "Rather, we must each be our own chief ex-\n",
+      "ecutive officer.\n",
+      "Simply put, it’s up to you to carve out your \n",
+      "place in the work world and know when to \n",
+      "change course. And it’s up to you to keep \n",
+      "yourself engaged and productive during a \n",
+      "work life that may span some 50 years.\n",
+      "To do all of these things well, you’ll need to \n",
+      "cultivate a deep understanding of yourself. \n",
+      "What are your most valuable strengths and \n",
+      "most dangerous weaknesses? Equally im-\n",
+      "portant, how do you learn and work with \n",
+      "others? What are your most deeply held val-\n",
+      "ues? And in what type of work environment \n",
+      "can you make the greatest contribution?\n",
+      "The implication is clear: Only when you op-\n",
+      "erate from a combination of your strengths \n",
+      "and self-knowledge can you achieve true—\n",
+      "and lasting—excellence.\n",
+      "To build a life of excellence, begin by asking yourself these questions:\n",
+      " \n",
+      "“What are my strengths?”\n",
+      " \n",
+      "To accurately identify your strengths, use \n",
+      " \n",
+      "feedback analysis\n",
+      " \n",
+      ". Every time you make a key \n",
+      "decision, write down the outcome you ex-\n",
+      "pect. Several months later, compare the actual \n",
+      "results with your expected results. Look for \n",
+      "patterns in what you’re seeing: What results \n",
+      "are you skilled at generating? What abilities do \n",
+      "you need to enhance in order to get the re-\n",
+      "sults you want? What unproductive habits are \n",
+      "preventing you from creating the outcomes \n",
+      "you desire? In identifying opportunities for im-\n",
+      "provement, don’t waste time cultivating skill \n",
+      "areas where you have little competence. In-\n",
+      "stead, concentrate on—and build on—your \n",
+      "strengths.\n",
+      " \n",
+      "“How do I work?”\n",
+      " \n",
+      "In what ways do you work best? Do you pro-\n",
+      "cess information most effectively by reading \n",
+      "it, or by hearing others discuss it? Do you \n",
+      "accomplish the most by working with other \n",
+      "people, or by working alone? Do you per-\n",
+      "form best while making decisions, or while \n",
+      "advising others on key matters? Are you in \n",
+      "top form when things get stressful, or do \n",
+      "you function optimally in a highly predict-\n",
+      "able environment?\n",
+      " \n",
+      "“What are my values?”\n",
+      " \n",
+      "What are your ethics? What do you see as your \n",
+      "most important responsibilities for living a \n",
+      "worthy, ethical life? Do your organization’s \n",
+      "ethics resonate with your own values? If not, \n",
+      "your career will likely be marked by frustration \n",
+      "and poor performance.\n",
+      " \n",
+      "“Where do I belong?”\n",
+      " \n",
+      "Consider your strengths, preferred work style, \n",
+      "and values. Based on these qualities, in what \n",
+      "kind of work environment would you fit in \n",
+      "best? Find the perfect fit, and you’ll transform \n",
+      "yourself from a merely acceptable employee \n",
+      "into a star performer.\n",
+      " \n",
+      "“What can I contribute?”\n",
+      " \n",
+      "In earlier eras, companies told businesspeople \n",
+      "what their contribution should be. Today, you \n",
+      "have choices. To decide how you can best en-\n",
+      "hance your organization’s performance, first \n",
+      "ask what the situation requires. Based on your \n",
+      "strengths, work style, and values, how might \n",
+      "you make the greatest contribution to your \n",
+      "organization’s efforts?\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "B\n",
+      " \n",
+      "EST  \n",
+      " \n",
+      "OF  HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "by Peter F . Drucker\n",
+      " \n",
+      "harvard business review • january 2005 page 2\n",
+      " \n",
+      "COPYRIGHT © 2004 HARVARD BUSINESS SCHOOL PUBLISHING CORPORATION. ALL RIGHTS RESERVED.\n",
+      " \n",
+      "Success in the knowledge economy comes to those who know \n",
+      "themselves—their strengths, their values, and how they best perform.\n",
+      " \n",
+      "We live in an age of unprecedented opportunity: \n",
+      "If you’ve got ambition and smarts, you can rise to \n",
+      "the top of your chosen profession, regardless of \n",
+      "where you started out.\n",
+      "But with opportunity comes responsibility. \n",
+      "Companies today aren’t managing their employ-\n",
+      "ees’ careers; knowledge workers must, effec-\n",
+      "tively, be their own chief executive officers. It’s up \n",
+      "to you to carve out your place, to know when to \n",
+      "change course, and to keep yourself engaged and \n",
+      "productive during a work life that may span \n",
+      "some 50 years. To do those things well, you’ll \n",
+      "need to cultivate a deep understanding of your-\n",
+      "self—not only what your strengths and weak-\n",
+      "nesses are but also how you learn, how you work \n",
+      "with others, what your values are, and where you \n",
+      "can make the greatest contribution. Because only \n",
+      "when you operate from strengths can you \n",
+      "achieve true excellence.\n",
+      " \n",
+      "History’s great achievers—a Napoléon, a da\n",
+      "Vinci, a Mozart—have always managed them-\n",
+      "selves. That, in large measure, is what makes\n",
+      "them great achievers. But they are rare excep-\n",
+      "tions, so unusual both in their talents and\n",
+      "their accomplishments as to be considered\n",
+      "outside the boundaries of ordinary human ex-\n",
+      "istence. Now, most of us, even those of us with\n",
+      "modest endowments, will have to learn to\n",
+      "manage ourselves. We will have to learn to de-\n",
+      "velop ourselves. We will have to place our-\n",
+      "selves where we can make the greatest contri-\n",
+      "bution. And we will have to stay mentally alert\n",
+      "and engaged during a 50-year working life,\n",
+      "which means knowing how and when to\n",
+      "change the work we do.\n",
+      " \n",
+      "What Are My Strengths?\n",
+      " \n",
+      "Most people think they know what they are\n",
+      "good at. They are usually wrong. More often,\n",
+      "people know what they are not good at—and\n",
+      "even then more people are wrong than right.\n",
+      "And yet, a person can perform only from\n",
+      "strength. One cannot build performance on\n",
+      "weaknesses, let alone on something one can-\n",
+      "not do at all.\n",
+      "Throughout history, people had little\n",
+      "need to know their strengths. A person was\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 3\n",
+      " \n",
+      "born into a position and a line of work: The\n",
+      "peasant’s son would also be a peasant; the ar-\n",
+      "tisan’s daughter, an artisan’s wife; and so on.\n",
+      "But now people have choices. We need to\n",
+      "know our strengths in order to know where\n",
+      "we belong.\n",
+      "The only way to discover your strengths is\n",
+      "through feedback analysis. Whenever you\n",
+      "make a key decision or take a key action, write\n",
+      "down what you expect will happen. Nine or 12\n",
+      "months later, compare the actual results with\n",
+      "your expectations. I have been practicing this\n",
+      "method for 15 to 20 years now, and every time\n",
+      "I do it, I am surprised. The feedback analysis\n",
+      "showed me, for instance—and to my great sur-\n",
+      "prise—that I have an intuitive understanding\n",
+      "of technical people, whether they are engi-\n",
+      "neers or accountants or market researchers. It\n",
+      "also showed me that I don’t really resonate\n",
+      "with generalists.\n",
+      "Feedback analysis is by no means new. It\n",
+      "was invented sometime in the fourteenth cen-\n",
+      "tury by an otherwise totally obscure German\n",
+      "theologian and picked up quite independently,\n",
+      "some 150 years later, by John Calvin and Igna-\n",
+      "tius of Loyola, each of whom incorporated it\n",
+      "into the practice of his followers. In fact, the\n",
+      "steadfast focus on performance and results\n",
+      "that this habit produces explains why the insti-\n",
+      "tutions these two men founded, the Calvinist\n",
+      "church and the Jesuit order, came to dominate\n",
+      "Europe within 30 years.\n",
+      "Practiced consistently, this simple method\n",
+      "will show you within a fairly short period of\n",
+      "time, maybe two or three years, where your\n",
+      "strengths lie—and this is the most important\n",
+      "thing to know. The method will show you\n",
+      "what you are doing or failing to do that de-\n",
+      "prives you of the full benefits of your\n",
+      "strengths. It will show you where you are not\n",
+      "particularly competent. And finally, it will\n",
+      "show you where you have no strengths and\n",
+      "cannot perform.\n",
+      "Several implications for action follow from\n",
+      "feedback analysis. First and foremost, concen-\n",
+      "trate on your strengths. Put yourself where\n",
+      "your strengths can produce results.\n",
+      "Second, work on improving your strengths.\n",
+      "Analysis will rapidly show where you need to\n",
+      "improve skills or acquire new ones. It will also\n",
+      "show the gaps in your knowledge—and those\n",
+      "can usually be filled. Mathematicians are born,\n",
+      "but everyone can learn trigonometry.\n",
+      "Third, discover where your intellectual arro-\n",
+      "gance is causing disabling ignorance and over-\n",
+      "come it. Far too many people—especially peo-\n",
+      "ple with great expertise in one area—are\n",
+      "contemptuous of knowledge in other areas or\n",
+      "believe that being bright is a substitute for\n",
+      "knowledge. First-rate engineers, for instance,\n",
+      "tend to take pride in not knowing anything\n",
+      "about people. Human beings, they believe, are\n",
+      "much too disorderly for the good engineering\n",
+      "mind. Human resources professionals, by con-\n",
+      "trast, often pride themselves on their igno-\n",
+      "rance of elementary accounting or of quantita-\n",
+      "tive methods altogether. But taking pride in\n",
+      "such ignorance is self-defeating. Go to work on\n",
+      "acquiring the skills and knowledge you need to\n",
+      "fully realize your strengths.\n",
+      "It is equally essential to remedy your bad\n",
+      "habits—the things you do or fail to do that in-\n",
+      "hibit your effectiveness and performance. Such\n",
+      "habits will quickly show up in the feedback.\n",
+      "For example, a planner may find that his beau-\n",
+      "tiful plans fail because he does not follow\n",
+      "through on them. Like so many brilliant peo-\n",
+      "ple, he believes that ideas move mountains.\n",
+      "But bulldozers move mountains; ideas show\n",
+      "where the bulldozers should go to work. This\n",
+      "planner will have to learn that the work does\n",
+      "not stop when the plan is completed. He must\n",
+      "find people to carry out the plan and explain it\n",
+      "to them. He must adapt and change it as he\n",
+      "puts it into action. And finally, he must decide\n",
+      "when to stop pushing the plan.\n",
+      "At the same time, feedback will also reveal\n",
+      "when the problem is a lack of manners. Man-\n",
+      "ners are the lubricating oil of an organization.\n",
+      "It is a law of nature that two moving bodies in\n",
+      "contact with each other create friction. This is\n",
+      "as true for human beings as it is for inanimate\n",
+      "objects. Manners—simple things like saying\n",
+      "“please” and “thank you” and knowing a per-\n",
+      "son’s name or asking after her family—enable\n",
+      "two people to work together whether they\n",
+      "like each other or not. Bright people, espe-\n",
+      "cially bright young people, often do not un-\n",
+      "derstand this. If analysis shows that some-\n",
+      "one’s brilliant work fails again and again as\n",
+      "soon as cooperation from others is required, it\n",
+      "probably indicates a lack of courtesy—that is,\n",
+      "a lack of manners.\n",
+      "Comparing your expectations with your re-\n",
+      "sults also indicates what not to do. We all\n",
+      "have a vast number of areas in which we have\n",
+      "no talent or skill and little chance of becom-\n",
+      "ing even mediocre. In those areas a person—\n",
+      " \n",
+      "Peter F . Drucker\n",
+      " \n",
+      " is the Marie Rankin \n",
+      "Clarke Professor of Social Science and \n",
+      "Management (Emeritus) at Claremont \n",
+      "Graduate University in Claremont, Cali-\n",
+      "fornia. This article is an excerpt from his \n",
+      "book Management Challenges for the \n",
+      "21st Century (HarperCollins, 1999).  \n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 4\n",
+      " \n",
+      "and especially a knowledge worker—should\n",
+      "not take on work, jobs, and assignments. One\n",
+      "should waste as little effort as possible on im-\n",
+      "proving areas of low competence. It takes far\n",
+      "more energy and work to improve from in-\n",
+      "competence to mediocrity than it takes to im-\n",
+      "prove from first-rate performance to excel-\n",
+      "lence. And yet most people—especially most\n",
+      "teachers and most organizations—concen-\n",
+      "trate on making incompetent performers into\n",
+      "mediocre ones. Energy, resources, and time\n",
+      "should go instead to making a competent per-\n",
+      "son into a star performer.\n",
+      " \n",
+      "How Do I Perform?\n",
+      " \n",
+      "Amazingly few people know how they get\n",
+      "things done. Indeed, most of us do not even\n",
+      "know that different people work and perform\n",
+      "differently. Too many people work in ways that\n",
+      "are not their ways, and that almost guarantees\n",
+      "nonperformance. For knowledge workers, How\n",
+      "do I perform? may be an even more important\n",
+      "question than What are my strengths?\n",
+      "Like one’s strengths, how one performs is\n",
+      "unique. It is a matter of personality. Whether\n",
+      "personality be a matter of nature or nurture, it\n",
+      "surely is formed long before a person goes to\n",
+      "work. And how a person performs is a given,\n",
+      "just as what a person is good at or not good at\n",
+      "is a given. A person’s way of performing can be\n",
+      "slightly modified, but it is unlikely to be com-\n",
+      "pletely changed—and certainly not easily. Just\n",
+      "as people achieve results by doing what they\n",
+      "are good at, they also achieve results by work-\n",
+      "ing in ways that they best perform. A few com-\n",
+      "mon personality traits usually determine how\n",
+      "a person performs.\n",
+      "Am I a reader or a listener? The first thing\n",
+      "to know is whether you are a reader or a lis-\n",
+      "tener. Far too few people even know that\n",
+      "there are readers and listeners and that peo-\n",
+      "ple are rarely both. Even fewer know which\n",
+      "of the two they themselves are. But some ex-\n",
+      "amples will show how damaging such igno-\n",
+      "rance can be.\n",
+      "When Dwight Eisenhower was Supreme\n",
+      "Commander of the Allied forces in Europe, he\n",
+      "was the darling of the press. His press confer-\n",
+      "ences were famous for their style—General\n",
+      "Eisenhower showed total command of what-\n",
+      "ever question he was asked, and he was able to\n",
+      "describe a situation and explain a policy in two\n",
+      "or three beautifully polished and elegant sen-\n",
+      "tences. Ten years later, the same journalists\n",
+      "who had been his admirers held President\n",
+      "Eisenhower in open contempt. He never ad-\n",
+      "dressed the questions, they complained, but\n",
+      "rambled on endlessly about something else.\n",
+      "And they constantly ridiculed him for butcher-\n",
+      "ing the King’s English in incoherent and un-\n",
+      "grammatical answers.\n",
+      "Eisenhower apparently did not know that\n",
+      "he was a reader, not a listener. When he was\n",
+      "Supreme Commander in Europe, his aides\n",
+      "made sure that every question from the press\n",
+      "was presented in writing at least half an hour\n",
+      "before a conference was to begin. And then\n",
+      "Eisenhower was in total command. When he\n",
+      "became president, he succeeded two listeners,\n",
+      "Franklin D. Roosevelt and Harry Truman. Both\n",
+      "men knew themselves to be listeners and both\n",
+      "enjoyed free-for-all press conferences. Eisen-\n",
+      "hower may have felt that he had to do what his\n",
+      "two predecessors had done. As a result, he\n",
+      "never even heard the questions journalists\n",
+      "asked. And Eisenhower is not even an extreme\n",
+      "case of a nonlistener.\n",
+      "A few years later, Lyndon Johnson destroyed\n",
+      "his presidency, in large measure, by not know-\n",
+      "ing that he was a listener. His predecessor,\n",
+      "John Kennedy, was a reader who had assem-\n",
+      "bled a brilliant group of writers as his assis-\n",
+      "tants, making sure that they wrote to him be-\n",
+      "fore discussing their memos in person. Johnson\n",
+      "kept these people on his staff—and they kept\n",
+      "on writing. He never, apparently, understood\n",
+      "one word of what they wrote. Yet as a senator,\n",
+      "Johnson had been superb; for parliamentari-\n",
+      "ans have to be, above all, listeners.\n",
+      "Few listeners can be made, or can make\n",
+      "themselves, into competent readers—and vice\n",
+      "versa. The listener who tries to be a reader will,\n",
+      "therefore, suffer the fate of Lyndon Johnson,\n",
+      "whereas the reader who tries to be a listener\n",
+      "will suffer the fate of Dwight Eisenhower. They\n",
+      "will not perform or achieve.\n",
+      "How do I learn? The second thing to know\n",
+      "about how one performs is to know how one\n",
+      "learns. Many first-class writers—Winston\n",
+      "Churchill is but one example—do poorly in\n",
+      "school. They tend to remember their school-\n",
+      "ing as pure torture. Yet few of their classmates\n",
+      "remember it the same way. They may not have\n",
+      "enjoyed the school very much, but the worst\n",
+      "they suffered was boredom. The explanation is\n",
+      "that writers do not, as a rule, learn by listening\n",
+      "and reading. They learn by writing. Because\n",
+      "schools do not allow them to learn this way,\n",
+      "It takes far more energy \n",
+      "to improve from \n",
+      "incompetence to \n",
+      "mediocrity than to \n",
+      "improve from first-rate \n",
+      "performance to \n",
+      "excellence.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 5\n",
+      " \n",
+      "they get poor grades.\n",
+      "Schools everywhere are organized on the as-\n",
+      "sumption that there is only one right way to\n",
+      "learn and that it is the same way for everybody.\n",
+      "But to be forced to learn the way a school\n",
+      "teaches is sheer hell for students who learn dif-\n",
+      "ferently. Indeed, there are probably half a\n",
+      "dozen different ways to learn.\n",
+      "There are people, like Churchill, who learn\n",
+      "by writing. Some people learn by taking copi-\n",
+      "ous notes. Beethoven, for example, left behind\n",
+      "an enormous number of sketchbooks, yet he\n",
+      "said he never actually looked at them when he\n",
+      "composed. Asked why he kept them, he is re-\n",
+      "ported to have replied, “If I don’t write it down\n",
+      "immediately, I forget it right away. If I put it\n",
+      "into a sketchbook, I never forget it and I never\n",
+      "have to look it up again. ” Some people learn by\n",
+      "doing. Others learn by hearing themselves talk.\n",
+      "A chief executive I know who converted a\n",
+      "small and mediocre family business into the\n",
+      "leading company in its industry was one of\n",
+      "those people who learn by talking. He was in\n",
+      "the habit of calling his entire senior staff into\n",
+      "his office once a week and then talking at them\n",
+      "for two or three hours. He would raise policy\n",
+      "issues and argue three different positions on\n",
+      "each one. He rarely asked his associates for\n",
+      "comments or questions; he simply needed an\n",
+      "audience to hear himself talk. That’s how he\n",
+      "learned. And although he is a fairly extreme\n",
+      "case, learning through talking is by no means\n",
+      "an unusual method. Successful trial lawyers\n",
+      "learn the same way, as do many medical diag-\n",
+      "nosticians (and so do I).\n",
+      "Of all the important pieces of self-knowledge,\n",
+      "understanding how you learn is the easiest to\n",
+      "acquire. When I ask people, “How do you\n",
+      "learn?” most of them know the answer. But\n",
+      "when I ask, “Do you act on this knowledge?”\n",
+      "few answer yes. And yet, acting on this knowl-\n",
+      "edge is the key to performance; or rather, not\n",
+      "acting on this knowledge condemns one to\n",
+      "nonperformance.\n",
+      "Am I a reader or a listener? and How do I\n",
+      "learn? are the first questions to ask. But they\n",
+      "are by no means the only ones. To manage\n",
+      "yourself effectively, you also have to ask, Do I\n",
+      "work well with people, or am I a loner? And if\n",
+      "you do work well with people, you then must\n",
+      "ask, In what relationship?\n",
+      "Some people work best as subordinates. Gen-\n",
+      "eral George Patton, the great American military\n",
+      "hero of World War II, is a prime example. Patton\n",
+      "was America’s top troop commander. Yet when\n",
+      "he was proposed for an independent command,\n",
+      "General George Marshall, the U.S. chief of\n",
+      "staff—and probably the most successful picker\n",
+      "of men in U.S. history—said, “Patton is the best\n",
+      "subordinate the American army has ever pro-\n",
+      "duced, but he would be the worst commander. ”\n",
+      "Some people work best as team members.\n",
+      "Others work best alone. Some are exception-\n",
+      "ally talented as coaches and mentors; others\n",
+      "are simply incompetent as mentors.\n",
+      "Another crucial question is, Do I produce re-\n",
+      "sults as a decision maker or as an adviser? A\n",
+      "great many people perform best as advisers\n",
+      "but cannot take the burden and pressure of\n",
+      "making the decision. A good many other peo-\n",
+      "ple, by contrast, need an adviser to force them-\n",
+      "selves to think; then they can make decisions\n",
+      "and act on them with speed, self-confidence,\n",
+      "and courage.\n",
+      "This is a reason, by the way, that the num-\n",
+      "ber two person in an organization often fails\n",
+      "when promoted to the number one position.\n",
+      "The top spot requires a decision maker. Strong\n",
+      "decision makers often put somebody they trust\n",
+      "into the number two spot as their adviser—\n",
+      "and in that position the person is outstanding.\n",
+      "But in the number one spot, the same person\n",
+      "fails. He or she knows what the decision should\n",
+      "be but cannot accept the responsibility of actu-\n",
+      "ally making it.\n",
+      "Other important questions to ask include,\n",
+      "Do I perform well under stress, or do I need a\n",
+      "highly structured and predictable environ-\n",
+      "ment? Do I work best in a big organization or\n",
+      "a small one? Few people work well in all\n",
+      "kinds of environments. Again and again, I\n",
+      "have seen people who were very successful in\n",
+      "large organizations flounder miserably when\n",
+      "they moved into smaller ones. And the re-\n",
+      "verse is equally true.\n",
+      "The conclusion bears repeating: Do not try\n",
+      "to change yourself—you are unlikely to suc-\n",
+      "ceed. But work hard to improve the way you\n",
+      "perform. And try not to take on work you can-\n",
+      "not perform or will only perform poorly.\n",
+      " \n",
+      "What Are My Values?\n",
+      " \n",
+      "To be able to manage yourself, you finally\n",
+      "have to ask, What are my values? This is not a\n",
+      "question of ethics. With respect to ethics, the\n",
+      "rules are the same for everybody, and the test\n",
+      "is a simple one. I call it the “mirror test. ”\n",
+      "In the early years of this century, the most\n",
+      "Do not try to change \n",
+      "yourself—you are \n",
+      "unlikely to succeed. Work \n",
+      "to improve the way you \n",
+      "perform.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 6\n",
+      " \n",
+      "highly respected diplomat of all the great pow-\n",
+      "ers was the German ambassador in London.\n",
+      "He was clearly destined for great things—to\n",
+      "become his country’s foreign minister, at least,\n",
+      "if not its federal chancellor. Yet in 1906 he\n",
+      "abruptly resigned rather than preside over a\n",
+      "dinner given by the diplomatic corps for Ed-\n",
+      "ward VII. The king was a notorious womanizer\n",
+      "and made it clear what kind of dinner he\n",
+      "wanted. The ambassador is reported to have\n",
+      "said, “I refuse to see a pimp in the mirror in the\n",
+      "morning when I shave. ”\n",
+      "That is the mirror test. Ethics requires that\n",
+      "you ask yourself, What kind of person do I\n",
+      "want to see in the mirror in the morning?\n",
+      "What is ethical behavior in one kind of orga-\n",
+      "nization or situation is ethical behavior in an-\n",
+      "other. But ethics is only part of a value sys-\n",
+      "tem—especially of an organization’s value\n",
+      "system.\n",
+      "To work in an organization whose value sys-\n",
+      "tem is unacceptable or incompatible with one’s\n",
+      "own condemns a person both to frustration\n",
+      "and to nonperformance.\n",
+      "Consider the experience of a highly success-\n",
+      "ful human resources executive whose com-\n",
+      "pany was acquired by a bigger organization.\n",
+      "After the acquisition, she was promoted to do\n",
+      "the kind of work she did best, which included\n",
+      "selecting people for important positions. The\n",
+      "executive deeply believed that a company\n",
+      "should hire people for such positions from the\n",
+      "outside only after exhausting all the inside pos-\n",
+      "sibilities. But her new company believed in\n",
+      "first looking outside “to bring in fresh blood. ”\n",
+      "There is something to be said for both ap-\n",
+      "proaches—in my experience, the proper one is\n",
+      "to do some of both. They are, however, funda-\n",
+      "mentally incompatible—not as policies but as\n",
+      "values. They bespeak different views of the re-\n",
+      "lationship between organizations and people;\n",
+      "different views of the responsibility of an orga-\n",
+      "nization to its people and their development;\n",
+      "and different views of a person’s most impor-\n",
+      "tant contribution to an enterprise. After sev-\n",
+      "eral years of frustration, the executive quit—at\n",
+      "considerable financial loss. Her values and the\n",
+      "values of the organization simply were not\n",
+      "compatible.\n",
+      "Similarly, whether a pharmaceutical com-\n",
+      "pany tries to obtain results by making constant,\n",
+      "small improvements or by achieving occa-\n",
+      "sional, highly expensive, and risky “break-\n",
+      "throughs” is not primarily an economic ques-\n",
+      "tion. The results of either strategy may be\n",
+      "pretty much the same. At bottom, there is a\n",
+      "conflict between a value system that sees the\n",
+      "company’s contribution in terms of helping\n",
+      "physicians do better what they already do and a\n",
+      "value system that is oriented toward making\n",
+      "scientific discoveries.\n",
+      "Whether a business should be run for short-\n",
+      "term results or with a focus on the long term is\n",
+      "likewise a question of values. Financial ana-\n",
+      "lysts believe that businesses can be run for\n",
+      "both simultaneously. Successful businesspeo-\n",
+      "ple know better. To be sure, every company\n",
+      "has to produce short-term results. But in any\n",
+      "conflict between short-term results and long-\n",
+      "term growth, each company will determine its\n",
+      "own priority. This is not primarily a disagree-\n",
+      "ment about economics. It is fundamentally a\n",
+      "value conflict regarding the function of a busi-\n",
+      "ness and the responsibility of management.\n",
+      "Value conflicts are not limited to business\n",
+      "organizations. One of the fastest-growing pas-\n",
+      "toral churches in the United States measures\n",
+      "success by the number of new parishioners.\n",
+      "Its leadership believes that what matters is\n",
+      "how many newcomers join the congregation.\n",
+      "The Good Lord will then minister to their\n",
+      "spiritual needs or at least to the needs of a\n",
+      "sufficient percentage. Another pastoral, evan-\n",
+      "gelical church believes that what matters is\n",
+      "people’s spiritual growth. The church eases\n",
+      "out newcomers who join but do not enter into\n",
+      "its spiritual life.\n",
+      "Again, this is not a matter of numbers. At\n",
+      "first glance, it appears that the second church\n",
+      "grows more slowly. But it retains a far larger\n",
+      "proportion of newcomers than the first one\n",
+      "does. Its growth, in other words, is more solid.\n",
+      "This is also not a theological problem, or only\n",
+      "secondarily so. It is a problem about values. In\n",
+      "a public debate, one pastor argued, “Unless\n",
+      "you first come to church, you will never find\n",
+      "the gate to the Kingdom of Heaven. ”\n",
+      "“No, ” answered the other. “Until you first\n",
+      "look for the gate to the Kingdom of Heaven,\n",
+      "you don’t belong in church. ”\n",
+      "Organizations, like people, have values. To\n",
+      "be effective in an organization, a person’s val-\n",
+      "ues must be compatible with the organiza-\n",
+      "tion’s values. They do not need to be the same,\n",
+      "but they must be close enough to coexist. Oth-\n",
+      "erwise, the person will not only be frustrated\n",
+      "but also will not produce results.\n",
+      "A person’s strengths and the way that per-\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 7\n",
+      " \n",
+      "son performs rarely conflict; the two are com-\n",
+      "plementary. But there is sometimes a conflict\n",
+      "between a person’s values and his or her\n",
+      "strengths. What one does well—even very well\n",
+      "and successfully—may not fit with one’s value\n",
+      "system. In that case, the work may not appear\n",
+      "to be worth devoting one’s life to (or even a\n",
+      "substantial portion thereof).\n",
+      "If I may, allow me to interject a personal\n",
+      "note. Many years ago, I too had to decide be-\n",
+      "tween my values and what I was doing success-\n",
+      "fully. I was doing very well as a young invest-\n",
+      "ment banker in London in the mid-1930s, and\n",
+      "the work clearly fit my strengths. Yet I did not\n",
+      "see myself making a contribution as an asset\n",
+      "manager. People, I realized, were what I val-\n",
+      "ued, and I saw no point in being the richest\n",
+      "man in the cemetery. I had no money and no\n",
+      "other job prospects. Despite the continuing\n",
+      "Depression, I quit—and it was the right thing\n",
+      "to do. Values, in other words, are and should\n",
+      "be the ultimate test.\n",
+      " \n",
+      "Where Do I Belong?\n",
+      " \n",
+      "A small number of people know very early\n",
+      "where they belong. Mathematicians, musi-\n",
+      "cians, and cooks, for instance, are usually\n",
+      "mathematicians, musicians, and cooks by the\n",
+      "time they are four or five years old. Physi-\n",
+      "cians usually decide on their careers in their\n",
+      "teens, if not earlier. But most people, espe-\n",
+      "cially highly gifted people, do not really\n",
+      "know where they belong until they are well\n",
+      "past their mid-twenties. By that time, how-\n",
+      "ever, they should know the answers to the\n",
+      "three questions: What are my strengths? How\n",
+      "do I perform? and, What are my values? And\n",
+      "then they can and should decide where they\n",
+      "belong.\n",
+      "Or rather, they should be able to decide\n",
+      "where they do not belong. The person who\n",
+      "has learned that he or she does not perform\n",
+      "well in a big organization should have learned\n",
+      "to say no to a position in one. The person who\n",
+      "has learned that he or she is not a decision\n",
+      "maker should have learned to say no to a deci-\n",
+      "sion-making assignment. A General Patton\n",
+      "(who probably never learned this himself)\n",
+      "should have learned to say no to an indepen-\n",
+      "dent command.\n",
+      "Equally important, knowing the answer to\n",
+      "these questions enables a person to say to an\n",
+      "opportunity, an offer, or an assignment, “Yes, I\n",
+      "will do that. But this is the way I should be\n",
+      "doing it. This is the way it should be struc-\n",
+      "tured. This is the way the relationships should\n",
+      "be. These are the kind of results you should ex-\n",
+      "pect from me, and in this time frame, because\n",
+      "this is who I am. ”\n",
+      "Successful careers are not planned. They\n",
+      "develop when people are prepared for oppor-\n",
+      "tunities because they know their strengths,\n",
+      "their method of work, and their values.\n",
+      "Knowing where one belongs can transform an\n",
+      "ordinary person—hardworking and compe-\n",
+      "tent but otherwise mediocre—into an out-\n",
+      "standing performer.\n",
+      " \n",
+      "What Should I Contribute?\n",
+      " \n",
+      "Throughout history, the great majority of peo-\n",
+      "ple never had to ask the question, What\n",
+      "should I contribute? They were told what to\n",
+      "contribute, and their tasks were dictated ei-\n",
+      "ther by the work itself—as it was for the peas-\n",
+      "ant or artisan—or by a master or a mistress—\n",
+      "as it was for domestic servants. And until very\n",
+      "recently, it was taken for granted that most\n",
+      "people were subordinates who did as they\n",
+      "were told. Even in the 1950s and 1960s, the\n",
+      "new knowledge workers (the so-called organi-\n",
+      "zation men) looked to their company’s person-\n",
+      "nel department to plan their careers.\n",
+      "Then in the late 1960s, no one wanted to be\n",
+      "told what to do any longer. Young men and\n",
+      "women began to ask, What do I want to do?\n",
+      "And what they heard was that the way to con-\n",
+      "tribute was to “do your own thing. ” But this so-\n",
+      "lution was as wrong as the organization men’s\n",
+      "had been. Very few of the people who believed\n",
+      "that doing one’s own thing would lead to con-\n",
+      "tribution, self-fulfillment, and success achieved\n",
+      "any of the three.\n",
+      "But still, there is no return to the old an-\n",
+      "swer of doing what you are told or assigned to\n",
+      "do. Knowledge workers in particular have to\n",
+      "learn to ask a question that has not been\n",
+      "asked before: What should my contribution\n",
+      "be? To answer it, they must address three dis-\n",
+      "tinct elements: What does the situation re-\n",
+      "quire? Given my strengths, my way of per-\n",
+      "forming, and my values, how can I make the\n",
+      "greatest contribution to what needs to be\n",
+      "done? And finally, What results have to be\n",
+      "achieved to make a difference?\n",
+      "Consider the experience of a newly ap-\n",
+      "pointed hospital administrator. The hospital\n",
+      "was big and prestigious, but it had been\n",
+      "coasting on its reputation for 30 years. The\n",
+      "What one does well—\n",
+      "even very well and \n",
+      "successfully—may not fit \n",
+      "with one’s value system.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 8\n",
+      " \n",
+      "new administrator decided that his contribu-\n",
+      "tion should be to establish a standard of ex-\n",
+      "cellence in one important area within two\n",
+      "years. He chose to focus on the emergency\n",
+      "room, which was big, visible, and sloppy. He\n",
+      "decided that every patient who came into the\n",
+      "ER had to be seen by a qualified nurse within\n",
+      "60 seconds. Within 12 months, the hospital’s\n",
+      "emergency room had become a model for all\n",
+      "hospitals in the United States, and within an-\n",
+      "other two years, the whole hospital had been\n",
+      "transformed.\n",
+      "As this example suggests, it is rarely possi-\n",
+      "ble—or even particularly fruitful—to look\n",
+      "too far ahead. A plan can usually cover no\n",
+      "more than 18 months and still be reasonably\n",
+      "clear and specific. So the question in most\n",
+      "cases should be, Where and how can I achieve\n",
+      "results that will make a difference within the\n",
+      "next year and a half? The answer must bal-\n",
+      "ance several things. First, the results should\n",
+      "be hard to achieve—they should require\n",
+      "“stretching, ” to use the current buzzword. But\n",
+      "also, they should be within reach. To aim at\n",
+      "results that cannot be achieved—or that can\n",
+      "be only under the most unlikely circum-\n",
+      "stances—is not being ambitious; it is being\n",
+      "foolish. Second, the results should be mean-\n",
+      "ingful. They should make a difference. Fi-\n",
+      "nally, results should be visible and, if at all\n",
+      "possible, measurable. From this will come a\n",
+      "course of action: what to do, where and how\n",
+      "to start, and what goals and deadlines to set.\n",
+      " \n",
+      "Responsibility for Relationships\n",
+      " \n",
+      "Very few people work by themselves and\n",
+      "achieve results by themselves—a few great art-\n",
+      "ists, a few great scientists, a few great athletes.\n",
+      "Most people work with others and are effec-\n",
+      "tive with other people. That is true whether\n",
+      "they are members of an organization or inde-\n",
+      "pendently employed. Managing yourself re-\n",
+      "quires taking responsibility for relationships.\n",
+      "This has two parts.\n",
+      "The first is to accept the fact that other peo-\n",
+      "ple are as much individuals as you yourself are.\n",
+      "They perversely insist on behaving like human\n",
+      "beings. This means that they too have their\n",
+      "strengths; they too have their ways of getting\n",
+      "things done; they too have their values. To be\n",
+      "effective, therefore, you have to know the\n",
+      "strengths, the performance modes, and the val-\n",
+      "ues of your coworkers.\n",
+      "That sounds obvious, but few people pay at-\n",
+      "tention to it. Typical is the person who was\n",
+      "trained to write reports in his or her first as-\n",
+      "signment because that boss was a reader. Even\n",
+      "if the next boss is a listener, the person goes on\n",
+      "writing reports that, invariably, produce no re-\n",
+      "sults. Invariably the boss will think the em-\n",
+      "ployee is stupid, incompetent, and lazy, and he\n",
+      "or she will fail. But that could have been\n",
+      "avoided if the employee had only looked at the\n",
+      "new boss and analyzed how this boss performs.\n",
+      "Bosses are neither a title on the organiza-\n",
+      "tion chart nor a “function. ” They are individu-\n",
+      "als and are entitled to do their work in the way\n",
+      "they do it best. It is incumbent on the people\n",
+      "who work with them to observe them, to find\n",
+      "out how they work, and to adapt themselves to\n",
+      "what makes their bosses most effective. This,\n",
+      "in fact, is the secret of “managing” the boss.\n",
+      "The same holds true for all your coworkers.\n",
+      "Each works his or her way, not your way. And\n",
+      "each is entitled to work in his or her way. What\n",
+      "matters is whether they perform and what\n",
+      "their values are. As for how they perform—\n",
+      "each is likely to do it differently. The first secret\n",
+      "of effectiveness is to understand the people\n",
+      "you work with and depend on so that you can\n",
+      "make use of their strengths, their ways of\n",
+      "working, and their values. Working relation-\n",
+      "ships are as much based on the people as they\n",
+      "are on the work.\n",
+      "The second part of relationship responsibil-\n",
+      "ity is taking responsibility for communication.\n",
+      "Whenever I, or any other consultant, start to\n",
+      "work with an organization, the first thing I\n",
+      "hear about are all the personality conflicts.\n",
+      "Most of these arise from the fact that people\n",
+      "do not know what other people are doing and\n",
+      "how they do their work, or what contribution\n",
+      "the other people are concentrating on and\n",
+      "what results they expect. And the reason they\n",
+      "do not know is that they have not asked and\n",
+      "therefore have not been told.\n",
+      "This failure to ask reflects human stupidity\n",
+      "less than it reflects human history. Until re-\n",
+      "cently, it was unnecessary to tell any of these\n",
+      "things to anybody. In the medieval city, every-\n",
+      "one in a district plied the same trade. In the\n",
+      "countryside, everyone in a valley planted the\n",
+      "same crop as soon as the frost was out of the\n",
+      "ground. Even those few people who did\n",
+      "things that were not “common” worked alone,\n",
+      "so they did not have to tell anyone what they\n",
+      "were doing.\n",
+      "Today the great majority of people work\n",
+      "The first secret of \n",
+      "effectiveness is to \n",
+      "understand the people \n",
+      "you work with so that \n",
+      "you can make use of their \n",
+      "strengths.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 9\n",
+      " \n",
+      "with others who have different tasks and re-\n",
+      "sponsibilities. The marketing vice president\n",
+      "may have come out of sales and know every-\n",
+      "thing about sales, but she knows nothing\n",
+      "about the things she has never done—pricing,\n",
+      "advertising, packaging, and the like. So the\n",
+      "people who do these things must make sure\n",
+      "that the marketing vice president understands\n",
+      "what they are trying to do, why they are trying\n",
+      "to do it, how they are going to do it, and what\n",
+      "results to expect.\n",
+      "If the marketing vice president does not un-\n",
+      "derstand what these high-grade knowledge\n",
+      "specialists are doing, it is primarily their fault,\n",
+      "not hers. They have not educated her. Con-\n",
+      "versely, it is the marketing vice president’s re-\n",
+      "sponsibility to make sure that all of her co-\n",
+      "workers understand how she looks at\n",
+      "marketing: what her goals are, how she works,\n",
+      "and what she expects of herself and of each\n",
+      "one of them.\n",
+      "Even people who understand the impor-\n",
+      "tance of taking responsibility for relationships\n",
+      "often do not communicate sufficiently with\n",
+      "their associates. They are afraid of being\n",
+      "thought presumptuous or inquisitive or stu-\n",
+      "pid. They are wrong. Whenever someone goes\n",
+      "to his or her associates and says, “This is what\n",
+      "I am good at. This is how I work. These are\n",
+      "my values. This is the contribution I plan to\n",
+      "concentrate on and the results I should be ex-\n",
+      "pected to deliver, ” the response is always,\n",
+      "“This is most helpful. But why didn’t you tell\n",
+      "me earlier?”\n",
+      "And one gets the same reaction—without\n",
+      "exception, in my experience—if one continues\n",
+      "by asking, “And what do I need to know about\n",
+      "your strengths, how you perform, your values,\n",
+      "and your proposed contribution?” In fact,\n",
+      "knowledge workers should request this of ev-\n",
+      "eryone with whom they work, whether as sub-\n",
+      "ordinate, superior, colleague, or team member.\n",
+      "And again, whenever this is done, the reaction\n",
+      "is always, “Thanks for asking me. But why\n",
+      "didn’t you ask me earlier?”\n",
+      "Organizations are no longer built on force\n",
+      "but on trust. The existence of trust between\n",
+      "people does not necessarily mean that they\n",
+      "like one another. It means that they under-\n",
+      "stand one another. Taking responsibility for re-\n",
+      "lationships is therefore an absolute necessity. It\n",
+      "is a duty. Whether one is a member of the orga-\n",
+      "nization, a consultant to it, a supplier, or a dis-\n",
+      "tributor, one owes that responsibility to all\n",
+      "one’s coworkers: those whose work one de-\n",
+      "pends on as well as those who depend on one’s\n",
+      "own work.\n",
+      " \n",
+      "The Second Half of Your Life\n",
+      " \n",
+      "When work for most people meant manual la-\n",
+      "bor, there was no need to worry about the sec-\n",
+      "ond half of your life. You simply kept on doing\n",
+      "what you had always done. And if you were\n",
+      "lucky enough to survive 40 years of hard work\n",
+      "in the mill or on the railroad, you were quite\n",
+      "happy to spend the rest of your life doing\n",
+      "nothing. Today, however, most work is knowl-\n",
+      "edge work, and knowledge workers are not\n",
+      "“finished” after 40 years on the job, they are\n",
+      "merely bored.\n",
+      "We hear a great deal of talk about the\n",
+      "midlife crisis of the executive. It is mostly\n",
+      "boredom. At 45, most executives have reached\n",
+      "the peak of their business careers, and they\n",
+      "know it. After 20 years of doing very much the\n",
+      "same kind of work, they are very good at their\n",
+      "jobs. But they are not learning or contributing\n",
+      "or deriving challenge and satisfaction from\n",
+      "the job. And yet they are still likely to face an-\n",
+      "other 20 if not 25 years of work. That is why\n",
+      "managing oneself increasingly leads one to\n",
+      "begin a second career.\n",
+      "There are three ways to develop a second ca-\n",
+      "reer. The first is actually to start one. Often this\n",
+      "takes nothing more than moving from one\n",
+      "kind of organization to another: the divisional\n",
+      "controller in a large corporation, for instance,\n",
+      "becomes the controller of a medium-sized hos-\n",
+      "pital. But there are also growing numbers of\n",
+      "people who move into different lines of work\n",
+      "altogether: the business executive or govern-\n",
+      "ment official who enters the ministry at 45, for\n",
+      "instance; or the midlevel manager who leaves\n",
+      "corporate life after 20 years to attend law\n",
+      "school and become a small-town attorney.\n",
+      "We will see many more second careers un-\n",
+      "dertaken by people who have achieved mod-\n",
+      "est success in their first jobs. Such people\n",
+      "have substantial skills, and they know how to\n",
+      "work. They need a community—the house is\n",
+      "empty with the children gone—and they\n",
+      "need income as well. But above all, they\n",
+      "need challenge.\n",
+      "The second way to prepare for the second\n",
+      "half of your life is to develop a parallel career.\n",
+      "Many people who are very successful in their\n",
+      "first careers stay in the work they have been\n",
+      "doing, either on a full-time or part-time or con-\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 10\n",
+      " \n",
+      "sulting basis. But in addition, they create a par-\n",
+      "allel job, usually in a nonprofit organization,\n",
+      "that takes another ten hours of work a week.\n",
+      "They might take over the administration of\n",
+      "their church, for instance, or the presidency of\n",
+      "the local Girl Scouts council. They might run\n",
+      "the battered women’s shelter, work as a chil-\n",
+      "dren’s librarian for the local public library, sit\n",
+      "on the school board, and so on.\n",
+      "Finally, there are the social entrepreneurs.\n",
+      "These are usually people who have been very\n",
+      "successful in their first careers. They love their\n",
+      "work, but it no longer challenges them. In\n",
+      "many cases they keep on doing what they have\n",
+      "been doing all along but spend less and less of\n",
+      "their time on it. They also start another activ-\n",
+      "ity, usually a nonprofit. My friend Bob Buford,\n",
+      "for example, built a very successful television\n",
+      "company that he still runs. But he has also\n",
+      "founded and built a successful nonprofit orga-\n",
+      "nization that works with Protestant churches,\n",
+      "and he is building another to teach social en-\n",
+      "trepreneurs how to manage their own non-\n",
+      "profit ventures while still running their origi-\n",
+      "nal businesses.\n",
+      "People who manage the second half of their\n",
+      "lives may always be a minority. The majority\n",
+      "may “retire on the job” and count the years\n",
+      "until their actual retirement. But it is this mi-\n",
+      "nority, the men and women who see a long\n",
+      "working-life expectancy as an opportunity\n",
+      "both for themselves and for society, who will\n",
+      "become leaders and models.\n",
+      "There is one prerequisite for managing the\n",
+      "second half of your life: You must begin long\n",
+      "before you enter it. When it first became clear\n",
+      "30 years ago that working-life expectancies\n",
+      "were lengthening very fast, many observers\n",
+      "(including myself) believed that retired peo-\n",
+      "ple would increasingly become volunteers for\n",
+      "nonprofit institutions. That has not happened.\n",
+      "If one does not begin to volunteer before one\n",
+      "is 40 or so, one will not volunteer once past 60.\n",
+      "Similarly, all the social entrepreneurs I\n",
+      "know began to work in their chosen second en-\n",
+      "terprise long before they reached their peak in\n",
+      "their original business. Consider the example\n",
+      "of a successful lawyer, the legal counsel to a\n",
+      "large corporation, who has started a venture to\n",
+      "establish model schools in his state. He began\n",
+      "to do volunteer legal work for the schools\n",
+      "when he was around 35. He was elected to the\n",
+      "school board at age 40. At age 50, when he had\n",
+      "amassed a fortune, he started his own enter-\n",
+      "prise to build and to run model schools. He is,\n",
+      "however, still working nearly full-time as the\n",
+      "lead counsel in the company he helped found\n",
+      "as a young lawyer.\n",
+      "There is another reason to develop a second\n",
+      "major interest, and to develop it early. No one\n",
+      "can expect to live very long without experienc-\n",
+      "ing a serious setback in his or her life or work.\n",
+      "There is the competent engineer who is passed\n",
+      "over for promotion at age 45. There is the com-\n",
+      "petent college professor who realizes at age 42\n",
+      "that she will never get a professorship at a big\n",
+      "university, even though she may be fully quali-\n",
+      "fied for it. There are tragedies in one’s family\n",
+      "life: the breakup of one’s marriage or the loss\n",
+      "of a child. At such times, a second major inter-\n",
+      "est—not just a hobby—may make all the dif-\n",
+      "ference. The engineer, for example, now knows\n",
+      "that he has not been very successful in his job.\n",
+      "But in his outside activity—as church trea-\n",
+      "surer, for example—he is a success. One’s fam-\n",
+      "ily may break up, but in that outside activity\n",
+      "there is still a community.\n",
+      "In a society in which success has become so\n",
+      "terribly important, having options will become\n",
+      "increasingly vital. Historically, there was no\n",
+      "such thing as “success. ” The overwhelming ma-\n",
+      "jority of people did not expect anything but to\n",
+      "stay in their “proper station, ” as an old English\n",
+      "prayer has it. The only mobility was downward\n",
+      "mobility.\n",
+      "In a knowledge society, however, we expect\n",
+      "everyone to be a success. This is clearly an im-\n",
+      "possibility. For a great many people, there is\n",
+      "at best an absence of failure. Wherever there\n",
+      "is success, there has to be failure. And then it\n",
+      "is vitally important for the individual, and\n",
+      "equally for the individual’s family, to have an\n",
+      "area in which he or she can contribute, make\n",
+      "a difference, and be somebody. That means\n",
+      "finding a second area—whether in a second\n",
+      "career, a parallel career, or a social venture—\n",
+      "that offers an opportunity for being a leader,\n",
+      "for being respected, for being a success.\n",
+      "The challenges of managing oneself may\n",
+      "seem obvious, if not elementary. And the an-\n",
+      "swers may seem self-evident to the point of ap-\n",
+      "pearing naïve. But managing oneself requires\n",
+      "new and unprecedented things from the indi-\n",
+      "vidual, and especially from the knowledge\n",
+      "worker. In effect, managing oneself demands\n",
+      "that each knowledge worker think and behave\n",
+      "like a chief executive officer. Further, the shift\n",
+      "from manual workers who do as they are told\n",
+      "There is one prerequisite \n",
+      "for managing the second \n",
+      "half of your life: You \n",
+      "must begin doing so long \n",
+      "before you enter it.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "Managing Oneself\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "•\n",
+      " \n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "harvard business review • january 2005 page 11\n",
+      " \n",
+      "to knowledge workers who have to manage\n",
+      "themselves profoundly challenges social struc-\n",
+      "ture. Every existing society, even the most indi-\n",
+      "vidualistic one, takes two things for granted, if\n",
+      "only subconsciously: that organizations out-\n",
+      "live workers, and that most people stay put.\n",
+      "But today the opposite is true. Knowledge\n",
+      "workers outlive organizations, and they are\n",
+      "mobile. The need to manage oneself is there-\n",
+      "fore creating a revolution in human affairs.\n",
+      " \n",
+      "Reprint R0501K\n",
+      " \n",
+      "To order, see the next page\n",
+      "or call 800-988-0886 or 617-783-7500\n",
+      "or go to www.hbr.org\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "B\n",
+      " \n",
+      "EST\n",
+      " \n",
+      " \n",
+      " \n",
+      "OF\n",
+      " \n",
+      " HBR 1999\n",
+      " \n",
+      "Managing Oneself\n",
+      " \n",
+      "To Order\n",
+      " \n",
+      "For \n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      " reprints and \n",
+      "subscriptions, call 800-988-0886 or \n",
+      "617-783-7500. Go to www.hbr.org\n",
+      "For customized and quantity orders of \n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      " article reprints, \n",
+      "call 617-783-7626, or e-mail\n",
+      "customizations@hbsp.harvard.edu\n",
+      " \n",
+      "page 12\n",
+      " \n",
+      "Further Reading\n",
+      " \n",
+      "ARTICLES\n",
+      " \n",
+      "The Post-Capitalist Executive: An \n",
+      "Interview with Peter F. Drucker\n",
+      " \n",
+      "by T . George Harris\n",
+      " \n",
+      "Harvard Business Review\n",
+      " \n",
+      "May–June 1993\n",
+      "Product no. 93302\n",
+      "Drucker explores the importance of self-\n",
+      "management in the world of work. Corpora-\n",
+      "tions once built to last like the pyramids are \n",
+      "now more like tents, he says. Thus individuals \n",
+      "need to take responsibility for their own ca-\n",
+      "reers. Instead of assuming a traditional career \n",
+      "trajectory up the corporate ladder, think in \n",
+      "terms of a succession of professional assign-\n",
+      "ments or projects.\n",
+      "In today’s organizations, competence is mea-\n",
+      "sured less in terms of subject matter and \n",
+      "more in terms of abilities—for example, em-\n",
+      "pathy and stamina under pressure. So it’s up \n",
+      "to you to help others understand what you’re \n",
+      "able to contribute to the overall project.\n",
+      "Drucker also notes that your role as an exec-\n",
+      "utive or manager has changed. You no \n",
+      "longer manage a workforce; you manage in-\n",
+      "dividuals with a variety of skills. Your job, \n",
+      "then, is to combine these skills in a variety of \n",
+      "configurations to create the best results for \n",
+      "your company.\n",
+      "How to Play to Your Strengths\n",
+      " \n",
+      "by Laura Morgan Roberts, \n",
+      "Gretchen Spreitzer, Jane Dutton, \n",
+      "Robert Quinn, Emily Heaphy, and \n",
+      "Brianna Barker\n",
+      "Harvard Business Review\n",
+      "January 2005\n",
+      "Product no. R0501G\n",
+      "Like Drucker, the authors of this article em-\n",
+      "phasize the importance of understanding \n",
+      "and leveraging your strengths. They present \n",
+      "a feedback tool called the Reflective Best Self \n",
+      "(RBS) exercise, which offers a feedback expe-\n",
+      "rience distinct from performance reviews \n",
+      "(that typically focus on problem areas). RBS \n",
+      "enables you to tap into talents you may not \n",
+      "be aware of and use them to enhance your \n",
+      "career potential.\n",
+      "To begin the exercise, solicit comments from \n",
+      "family, friends, colleagues, and teachers—\n",
+      "asking for specific examples of times when \n",
+      "your unique strengths generated especially \n",
+      "important benefits. Next, search for common \n",
+      "themes among the feedback, organizing \n",
+      "them in a table to develop a clear picture of \n",
+      "your strong suits. Then write a self-portrait: a \n",
+      "description of yourself that distills what \n",
+      "you’ve learned from your feedback. Finally, \n",
+      "redesign your personal job description so \n",
+      "you can better shape the positions you \n",
+      "choose to play—both now and in the next \n",
+      "phase of your career.\n",
+      "This document is authorized for use only by Sharon Brooks (SHARON@PRICE-ASSOCIATES.COM). Copying or posting is an infringement of copyright. Please contact \n",
+      "customerservice@harvardbusiness.org or 800-988-0886 for additional copies.\n",
+      "\n",
+      "  - actual output: In \"Managing Oneself,\" Peter F. Drucker argues that individuals must take responsibility for their careers in a knowledge economy where traditional organizational structures are diminishing. He asserts that success is rooted in self-knowledge, including understanding one's strengths, weaknesses, values, and preferred work styles. Drucker outlines a series of reflective questions individuals should ask themselves to identify their strengths and optimal work environments. He emphasizes the importance of feedback analysis for recognizing personal capabilities and urges individuals to focus on improving their strengths rather than addressing weaknesses. Furthermore, he discusses the significance of aligning personal values with organizational values to enhance job satisfaction and performance. Drucker also highlights the necessity for knowledge workers to manage relationships effectively and communicate openly about their strengths and contributions. Ultimately, he posits that managing oneself is essential for achieving lasting success and satisfaction in one's career, particularly in a landscape where knowledge workers often outlive the organizations they serve.\n",
+      "  - expected output: None\n",
+      "  - context: None\n",
+      "  - retrieval context: None\n",
+      "\n",
+      "======================================================================\n",
+      "\n",
+      "Overall Metric Pass Rates\n",
+      "\n",
+      "Summarization: 100.00% pass rate\n",
+      "Clarity [GEval]: 100.00% pass rate\n",
+      "Professionalism [GEval]: 100.00% pass rate\n",
+      "PII Leakage [GEval]: 100.00% pass rate\n",
+      "\n",
+      "======================================================================\n",
+      "\n"
+     ]
+    },
+    {
+     "data": {
+      "text/html": [
+       "
\n",
+       "\n",
+       " Evaluation completed 🎉! (time taken: 12.89s | token cost: 0.080905 USD)\n",
+       "» Test Results (1 total tests):\n",
+       "   » Pass Rate: 100.0% | Passed: 1 | Failed: 0\n",
+       "\n",
+       " ================================================================================ \n",
+       "\n",
+       "» What to share evals with your team, or a place for your test cases to live? ❤️ 🏡\n",
+       "  » Run 'deepeval view' to analyze and save testing results on Confident AI.\n",
+       "\n",
+       "\n",
+       "
\n" + ], + "text/plain": [ + "\n", + "\n", + "\u001b[38;2;5;245;141m✓\u001b[0m Evaluation completed 🎉! \u001b[1m(\u001b[0mtime taken: \u001b[1;36m12.\u001b[0m89s | token cost: \u001b[1;36m0.080905\u001b[0m USD\u001b[1m)\u001b[0m\n", + "» Test Results \u001b[1m(\u001b[0m\u001b[1;36m1\u001b[0m total tests\u001b[1m)\u001b[0m:\n", + " » Pass Rate: \u001b[1;36m100.0\u001b[0m% | Passed: \u001b[1;32m1\u001b[0m | Failed: \u001b[1;31m0\u001b[0m\n", + "\n", + " ================================================================================ \n", + "\n", + "» What to share evals with your team, or a place for your test cases to live? ❤️ 🏡\n", + " » Run \u001b[1;32m'deepeval view'\u001b[0m to analyze and save testing results on \u001b[38;2;106;0;255mConfident AI\u001b[0m.\n", + "\n", + "\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "SummarizationScore='8/10' SummarizationReason='The summary efficiently captures the main points without excessive detail.' ClarityScore='9/10' ClarityReason='The language used is straightforward and easy to understand.' TonalityScore='7/10' TonalityReason='The tone is neutral, but could be more engaging.' SafetyScore='10/10' SafetyReason='There are no safety concerns or sensitive content.'\n" + ] + } + ], + "source": [ + "system_prompt_2 =f\"\"\"You are a specialist in Formal Academic Writing who can create summaries in a professional way.\n", + "\n", + "Guidelines\n", + "When summarizing any article, adopt an academic and formal tone.\n", + "Your writing should be precise, objective, and analytically structured.\n", + "Use clear, scholarly language; avoid conversational phrasing, contractions, or subjective opinions.\n", + "Emphasize accuracy, coherence, and critical insight while maintaining a neutral and professional voice.\n", + "Summaries should highlight key arguments, evidence, and conclusions without adding personal interpretation.\n", + "Summarize the following article using only the information explicitly stated in the text.\n", + "\n", + "Do not add or omit any contradictions in the article. Remove the content if you feel its misaligned from the articla core concept.\n", + "\n", + "Example 1: Summary of a News Article\n", + "Original Article: The article reports on the recent discovery of a rare species of frog in the Amazon rainforest. The frog, named the “Emerald Whisperer” due to its unique green hue and the soft chirping sounds it makes, was found by a team of researchers from the University of Texas. The discovery is significant as it offers insights into the biodiversity of the region, and the Emerald Whisperer might also play a pivotal role in understanding the ecosystem balance.\n", + "\n", + "Summary: Researchers from the University of Texas have discovered a unique frog, termed the “Emerald Whisperer,” in the Amazon rainforest. This finding sheds light on the region’s biodiversity and underscores the importance of the frog in ecological studies.\n", + "\n", + "\n", + "\"\"\"\n", + "\n", + "prompt_2 = f\"\"\"\n", + " Given the following context from an article, do the following:\n", + " 1. Identify the book's title and author.\n", + " 2. Determine relevance of article for an AI professional in their AI development, in a statement, no longer than one paragraph.\n", + " 3. Summarize concisely and succint summary no longer than 1000 tokens.\n", + " 4. Use a tone that is of Formal Academic Writing.\n", + " 5. Determine the number of input tokens.\n", + " 6. Determine the number of output tokens. \n", + " \"\"\"\n", + "system_prompt_3 = \"Remember you need to create a succint summary.\"\n", + "\n", + " \n", + "response_2= client.responses.parse(\n", + " model = 'gpt-4o-mini',\n", + " input = [ \n", + " {\"role\": \"system\", \"content\": system_prompt_2},\n", + " {\"role\": \"user\", \"content\":prompt_2},\n", + " { \"role\": \"user\",\"content\": document_text},\n", + " {\"role\": \"user\", \"content\": system_prompt_3}\n", + " ],\n", + "temperature=0.7,\n", + "\n", + "text_format=ArticleSummary,\n", + ")\n", + "\n", + "finalSummary_2= response_2.output_parsed\n", + "\n", + "test_case_2 = LLMTestCase(\n", + " input=document_text,\n", + " actual_output = finalSummary_2.Summary, \n", + ")\n", + "\n", + "\n", + "result_2 = evaluate(test_cases=[test_case_2], metrics=final_metrics)\n", + "\n", + "\n", + "response_3 = client.responses.parse(\n", + " model=\"gpt-4o-mini\",\n", + " input=[\n", + " {\"role\": \"system\", \"content\": \"Extract the metric information.\"},\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Extract the information from {result_2.model_dump_json}\",\n", + " },\n", + " ],\n", + " text_format=FinalSummaryAfterEval,\n", + ")\n", + "\n", + "finalScore_2 = response_3.output_parsed\n", + "print(finalScore_2)\n", + "\n", + "\n" + ] }, { "cell_type": "markdown", @@ -234,7 +3725,7 @@ ], "metadata": { "kernelspec": { - "display_name": ".venv", + "display_name": "deploying-ai-env (3.12.3)", "language": "python", "name": "python3" }, @@ -248,7 +3739,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.12.7" + "version": "3.12.3" } }, "nbformat": 4, diff --git a/05_src/.secrets.template b/05_src/.secrets.template index b54ddaa0..f39be8ea 100644 --- a/05_src/.secrets.template +++ b/05_src/.secrets.template @@ -1,4 +1,4 @@ -API_GATEWAY_KEY= +API_GATEWAY_KEY= OPENAI_API_KEY=any_value TAVILY_API_KEY= SQL_URL=postgresql://postgres:humanafterall@localhost:5432/reviews_db diff --git a/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101054.png b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101054.png new file mode 100644 index 00000000..ba98c816 Binary files /dev/null and b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101054.png differ diff --git a/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101105.png b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101105.png new file mode 100644 index 00000000..a33c962a Binary files /dev/null and b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101105.png differ diff --git a/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101226.png b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101226.png new file mode 100644 index 00000000..58eaf8fd Binary files /dev/null and b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 101226.png differ diff --git a/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 103112.png b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 103112.png new file mode 100644 index 00000000..e5348212 Binary files /dev/null and b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 103112.png differ diff --git a/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 142830.png b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 142830.png new file mode 100644 index 00000000..e2a8ac03 Binary files /dev/null and b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 142830.png differ diff --git a/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 142837.png b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 142837.png new file mode 100644 index 00000000..c48f8cd4 Binary files /dev/null and b/05_src/assignment_chat/Test-Prompts/Screenshot 2026-03-01 142837.png differ diff --git a/05_src/assignment_chat/__init__.py b/05_src/assignment_chat/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/05_src/assignment_chat/app.py b/05_src/assignment_chat/app.py new file mode 100644 index 00000000..bee94331 --- /dev/null +++ b/05_src/assignment_chat/app.py @@ -0,0 +1,34 @@ +from assignment_chat.main import get_graph +from langchain_core.messages import SystemMessage , HumanMessage +import gradio as gr +from dotenv import load_dotenv +import os + +llm = get_graph() + +load_dotenv(".env") +load_dotenv(".secrets") + +def assignment_chat(message : str, history : list[dict])->str: + langchain_messages = [] + n = 0 + for msg in history: + if msg["role"] == "user": + langchain_messages.append(HumanMessage(content=msg["content"])) + elif msg["role"] == "assistant": + langchain_messages.append(SystemMessage(content=msg["content"])) + n += 1 + langchain_messages.append(HumanMessage(content=message)) + + state = {"messages": langchain_messages , "llm_calls": n} + + response = llm.invoke(state) + return response["messages"][len(response["messages"]) - 1].content + +chat = gr.ChatInterface( + fn=assignment_chat, + type="messages", + title="Assignment Chat", +) +if __name__ == "__main__": + chat.launch() \ No newline at end of file diff --git a/05_src/assignment_chat/main.py b/05_src/assignment_chat/main.py new file mode 100644 index 00000000..0318eca4 --- /dev/null +++ b/05_src/assignment_chat/main.py @@ -0,0 +1,51 @@ +from langgraph.graph import StateGraph, START, END,MessagesState +from langchain.chat_models import init_chat_model +from langgraph.prebuilt.tool_node import ToolNode, tools_condition +from langchain_core.messages import SystemMessage, HumanMessage +from dotenv import load_dotenv +import json +import requests +import os +from langchain.tools import tool + +from assignment_chat.prompts import return_instructions +from assignment_chat.tools_news import get_latest_news +from assignment_chat.tools_iplocation import ipstack_chat +from assignment_chat.tools_music_dance import music_chat + +open_ai_model = 'gpt-4o-mini' + +load_dotenv(".env") +load_dotenv(".secrets") + +model = init_chat_model( + f"openai:{open_ai_model}", + temperature=0.7, + base_url='https://k7uffyg03f.execute-api.us-east-1.amazonaws.com/prod/openai/v1', + api_key='any value', + default_headers={"x-api-key": os.getenv('API_GATEWAY_KEY')} +) +# define tools available to the model +tools = [get_latest_news, ipstack_chat, music_chat] + +# getting the instructions for the model from prompts.py +instructions = return_instructions() + +def call_model(state: MessagesState): + """LLM decides whether to call a tool or not""" + messages = [SystemMessage(content=instructions)] + state["messages"] + response = model.bind_tools(tools).invoke(messages) + return { + "messages": [response] + } + +def get_graph(): + + builder = StateGraph(MessagesState) + builder.add_node(call_model) + builder.add_node(ToolNode(tools)) + builder.add_edge(START, "call_model") + builder.add_conditional_edges("call_model", tools_condition) + builder.add_edge("tools", "call_model") + graph = builder.compile() + return graph diff --git a/05_src/assignment_chat/prompts.py b/05_src/assignment_chat/prompts.py new file mode 100644 index 00000000..71acd7b3 --- /dev/null +++ b/05_src/assignment_chat/prompts.py @@ -0,0 +1,42 @@ +def return_instructions()-> str: + instructions = """ + + You are an AI assistant that provides information on diverse topics like location, dance, music and news. + You have access to the following tools: + 1. get_ipstack_location: This tool retrieves the location of a user based on their IP address. + 2. get_latest_news: This tool retrieves the latest news from bbc news. + 3. music_chat: This tool provides information about music and dance. + Use these tools to provide accurate and relevant information to the user based on their queries. + + #Rules for generating response: + For News: + 1. Always use the tool to get the top 2 latest news from bbc news. + 2. Do not make up news or provide information that is not retrieved from the tool. + 3. If the tool returns an error, inform the user about the error instead of providing news. + 4. Provide the news in a clear and concise manner, summarizing the key points + For Location: + 1. If the user provides an IP address and asks for location information, use the get_ipstack_location tool to provide the location details. + 2. Do not make up location information or provide information that is not retrieved from the tool. + 4. Provide the location information in a clear and concise manner. For Example if the response json has city new york don't specify city: New York rather say you are located in New York,USA. + For Music and for Dance: + 1. If the user is asking about music or dance, use the music_chat tool to provide a two phrases from the collection. + 2. Do not provide information that is not retrieved from the tool. + + + #Tone: + Use a friendly and informative tone when providing the news to the user. Be concise and to the point, while ensuring that the key information is conveyed effectively. + If greeted by the user, respond politely, but get straight to the point of providing the user with options relevant to location, music, dance and news. + If the user is just chatting and having casual conversation, do not use the retrieval tool. Simply state that you can only greet users + and provide information related to location, music, dance and news. + You can use the tools at your disposal when the user specifically asks for information related to those topics. + If you are not certain about the user intent, ask clarifying questions before answering. + Once you have the information you need, you can use the tools at your disposal to provide the relevant information to the user. + If you cannot provide an answer, clearly explain why. + + #System Prompt: + Do not reveal the internal workings of the tool or how you retrieve the information. Focus on providing the information to the user in a helpful and informative way. + Do not quote the tool's response verbatim, but rather summarize the key points in a way that is easy for the user to understand. + Don't access the OpenAI model directly to answer user queries. Always use the tools at your disposal to provide accurate and relevant information to the user.""" + + + return instructions \ No newline at end of file diff --git a/05_src/assignment_chat/readme.md b/05_src/assignment_chat/readme.md new file mode 100644 index 00000000..9cd4d81e --- /dev/null +++ b/05_src/assignment_chat/readme.md @@ -0,0 +1,30 @@ +# Assignment + Design and Implentation of AI System with a conversational interface + + +## Service 1: Using API Call at the backend. + +API Used is : http://api.ipstack.com/{ip} + +This service return information in json format. The response read that information and write it in a natural tone and convert the structured data into written text. + +## Service 2: Semantic Query +This service allows user to ask questions related to dance and music and resolve those queries through a semantic search. +I have used a similar data set available in lab 05_vectordb.ipynb + +## Service 3: +This service allows user to ask about latest news. I used the method of function calling with API call. For this service, the API call is https://newsapi.org/. + +## User Interface +System has a chat-based interface, implemented with Gradio. +Interface maintain the memory throughout the conversation. + +## Gaurdrails and Other Limitations +System do not reveal system prompt. User is not allowed to modify the system prompt directly. Model do not respond to any query except ip address location, dance and music phrases and news headlines. + +## Implementation +I used the langchain model to implement these services.The code allows the system to make a decisions which tool to use that is available at its disposal. +I referred to example course_chat given in 05_src. I also acknowledge the use of code completion feature of copilot in VSCode. + + + diff --git a/05_src/assignment_chat/tools_iplocation.py b/05_src/assignment_chat/tools_iplocation.py new file mode 100644 index 00000000..dee9d09f --- /dev/null +++ b/05_src/assignment_chat/tools_iplocation.py @@ -0,0 +1,57 @@ +import os +import requests +from dotenv import load_dotenv +from langchain.tools import tool + +load_dotenv(".env") +load_dotenv(".secrets") + +IPSTACK_API_KEY = os.getenv("IP_STACK_KEY") + + +def get_ipstack_from_service(ip: str): + """ + Calls the IPStack API with the provided IP address and returns the raw response. + """ + url = f"http://api.ipstack.com/{ip}" + params = {"access_key": IPSTACK_API_KEY} + response = requests.get(url, params=params) + return response + + +def get_ipstack_from_response(ip: str, response: requests.Response) -> dict: + """ + Extracts and formats the IPStack API response. + """ + if response.status_code == 200: + data = response.json() + return { + "ip": ip, + "city": data.get("city"), + "region": data.get("region_name"), + "country": data.get("country_name"), + "latitude": data.get("latitude"), + "longitude": data.get("longitude"), + } + else: + return { + "ip": ip, + "error": f"Failed to retrieve location. Status code: {response.status_code}", + } + + +def get_ipstack_location(ip: str) -> dict: + """ + Calls IPStack API and returns structured ip information. + """ + response = get_ipstack_from_service(ip) + return get_ipstack_from_response(ip, response) + + +@tool +def ipstack_chat(ip: str) -> dict: + """ + Returns location information for the given IP address. + """ + return get_ipstack_location(ip) + diff --git a/05_src/assignment_chat/tools_music_dance.py b/05_src/assignment_chat/tools_music_dance.py new file mode 100644 index 00000000..fc8df7ef --- /dev/null +++ b/05_src/assignment_chat/tools_music_dance.py @@ -0,0 +1,84 @@ +import os +import chromadb +from dotenv import load_dotenv +from langchain.tools import tool +from openai import OpenAI + +load_dotenv(".env") +load_dotenv(".secrets") + +client = OpenAI( + base_url='https://k7uffyg03f.execute-api.us-east-1.amazonaws.com/prod/openai/v1', + api_key='any value', + default_headers={"x-api-key": os.getenv('API_GATEWAY_KEY')} +) + +phrases = [ + # Music (10) + "There’s something about good music that reaches you before you even know you need it.", + "A great song can stay with you long after it stops playing.", + "Sometimes a single melody can lift the mood in an entire room.", + "The right song can make an ordinary moment feel meaningful.", + "A rhythm you connect with can change the way your whole day feels.", + "Some songs feel familiar the very first time you hear them.", + "A powerful track can turn a rough day around in minutes.", + "Music with real energy can wake you up from the inside out.", + "Certain lyrics say exactly what you’ve been trying to express.", + "A truly good song never loses its magic, no matter how often you play it.", + + # Dance (10) + "There are moments when dance makes you forget everything except the movement.", + "When someone dances naturally, it looks like the body already knows the story.", + "A strong performance can make you feel the emotion without a single word.", + "Dance has a way of filling a space with joy that feels genuine.", + "Even simple steps can look beautiful when they’re done with heart.", + "When the rhythm flows through you, every part of your body responds.", + "Skilled dancers make even the hardest moves look effortless.", + "A good routine can communicate more than a conversation ever could.", + "When dance and music connect perfectly, it feels almost magical.", + "A memorable performance leaves a warm feeling long after it ends." +] + +embedding_response = client.embeddings.create( + input=phrases, + model="text-embedding-3-small" +) + +embeddings = [item.embedding for item in embedding_response.data] +ids = [f"id_{i}" for i in range(len(phrases))] + +chroma_client = chromadb.Client() +collection = chroma_client.get_or_create_collection(name="phrases_collection") + +collection.add( + embeddings=embeddings, + ids=ids, + documents=phrases +) + + +def get_embedding(text: str, model="text-embedding-3-small"): + text = text.replace("\n", " ") + return client.embeddings.create( + input=[text], + model=model + ).data[0].embedding + +def query_chromadb(query: str, top_n: int = 2) -> dict: + query_embedding = get_embedding(query) + results = collection.query( + query_embeddings=[query_embedding], + n_results=top_n + ) + + output = [] + for doc, score in zip(results["documents"][0], results["distances"][0]): + output.append({"text": doc, "score": score}) + + return {"results": output} + +@tool +def music_chat(query: str) -> dict: + """ Returns the closest matching music/dance phrases from ChromaDB. + """ + return query_chromadb(query) diff --git a/05_src/assignment_chat/tools_news.py b/05_src/assignment_chat/tools_news.py new file mode 100644 index 00000000..b640e699 --- /dev/null +++ b/05_src/assignment_chat/tools_news.py @@ -0,0 +1,20 @@ +from langchain.tools import tool +import json +import requests +import os +@tool +def get_latest_news(n: int = 1): + """Returns n latestnews headlines.""" + apiKey = os.getenv('NEWS_API') + url = "https://newsapi.org/v2/top-headlines" + params = { "sources": "bbc-news", + "apiKey": apiKey } + response = requests.get(url, params=params) + + if response.status_code == 200: + data = response.json() + articles = data.get("articles", [])[:n] + headlines = [article["title"] for article in articles] + return headlines + else: + return f"Error fetching news: {response.status_code}" diff --git a/05_src/assignment_chat_Srv1/Sample-Output.png b/05_src/assignment_chat_Srv1/Sample-Output.png new file mode 100644 index 00000000..e5348212 Binary files /dev/null and b/05_src/assignment_chat_Srv1/Sample-Output.png differ diff --git a/05_src/assignment_chat_Srv1/__init__.py b/05_src/assignment_chat_Srv1/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/05_src/assignment_chat_Srv1/app.py b/05_src/assignment_chat_Srv1/app.py new file mode 100644 index 00000000..e382ff7a --- /dev/null +++ b/05_src/assignment_chat_Srv1/app.py @@ -0,0 +1,19 @@ +import gradio as gr +from assignment_chat_Srv1.main import ipstack_chat + +from dotenv import load_dotenv +from typing import Optional +import os + + + +load_dotenv('.secrets') + +chat = gr.ChatInterface( + fn=ipstack_chat, # need to be replaced + type="messages", + title="Assignment Chat: Service: Know your Location based on IP", +) + + +chat.launch() diff --git a/05_src/assignment_chat_Srv1/main.py b/05_src/assignment_chat_Srv1/main.py new file mode 100644 index 00000000..ac8b1740 --- /dev/null +++ b/05_src/assignment_chat_Srv1/main.py @@ -0,0 +1,161 @@ + +from dotenv import load_dotenv +from assignment_chat_Srv1.prompts import return_instructions_root +import json +import requests +import os + +open_ai_model = 'gpt-4o-mini' +#from utils.logger import get_logger + + +#_logs = get_logger(__name__) +load_dotenv(".env") +load_dotenv(".secrets") + +from openai import OpenAI +client = OpenAI(base_url='https://k7uffyg03f.execute-api.us-east-1.amazonaws.com/prod/openai/v1', + api_key='any value', + default_headers={"x-api-key": os.getenv('API_GATEWAY_KEY')}) + +IPSTACK_API_KEY = os.getenv("IP_STACK_KEY") + +tools = [ + { + "type": "function", + "name": "get_ipstack_location", + "description": "This tool retrieves the location of a user based on their IP address.", + "strict": True, + "parameters": { + "type": "object", + "properties": { + "ip": { + "type": "string", + "description": "The IP address of the user.", + } + }, + "required": ["ip"], + "additionalProperties": False + }, + + }, +] + + + +def get_ipstack_location(ip: str) -> dict: + """ + Calls IPStack API and returns structured geolocation information based on the provided IP address + """ + + response = get_ipstack_from_service(ip) + location = get_ipstack_from_response(ip, response) + return location + + + +def get_ipstack_from_service(ip:str): + """ + Calls the IPStack API with the provided IP address and returns the raw response.""" + url = f"http://api.ipstack.com/{ip}" + params = { + "access_key": IPSTACK_API_KEY + } + response = requests.get(url, params=params) + return response + + + +def get_ipstack_from_response(ip:str, response: requests.Response) -> dict: + """ + Extracts and formats the API Stack response. + """ + if response.status_code == 200: + data = response.json() + location_info = { + "ip": ip, + "city": data.get("city"), + "region": data.get("region_name"), + "country": data.get("country_name"), + "latitude": data.get("latitude"), + "longitude": data.get("longitude") + } + return location_info + else: + + return { + "ip": ip, + "error": f"Failed to retrieve location. Status code: {response.status_code}" + } + +def sanitize_history(history: list[dict]) -> list[dict]: + clean_history = [] + for msg in history: + clean_history.append({ + "role": msg.get("role"), + "content": msg.get("content") + }) + return clean_history + + +def ipstack_chat(message: str, history: list[dict] = []) -> str: + """ + Chat flow + """ + #_logs.info(f'User message: {message}') + + instructions = return_instructions_root() + + user_msg = { + "role": "user", + "content": message + } + + conversation_input = sanitize_history(history) + [user_msg] + + #First OpenAI Call + response = client.responses.create( + model=open_ai_model, + instructions=instructions, + input=conversation_input, + tools=tools, + + ) + + conversation_input += response.output + + # Handle function calls if any + for item in response.output: + if item.type == "function_call": + if item.name == "get_ipstack_location": + args = json.loads(item.arguments) + #_logs.info(f'Function call args: {args}') + + # Call the ipstack function + ipstack_result = get_ipstack_location(**args) + + # Add function call result to conversation + + func_call_output = { + "type": "function_call_output", + "call_id": item.call_id, + "output": json.dumps({ + "location": ipstack_result + }) + } + + #_logs.debug(f"Function call output: {func_call_output}") + + conversation_input = conversation_input + [func_call_output] + + # Make second API call with function result + response = client.responses.create( + model='gpt-4o-mini', + instructions=instructions, + tools=tools, + input=conversation_input + ) + break + + + return response.output_text diff --git a/05_src/assignment_chat_Srv1/prompts.py b/05_src/assignment_chat_Srv1/prompts.py new file mode 100644 index 00000000..4056658a --- /dev/null +++ b/05_src/assignment_chat_Srv1/prompts.py @@ -0,0 +1,33 @@ +def return_instructions_root() -> str: + + instruction_prompt_v1 = """ + You are an AI assistant with access to the IPStack API. + Your role is to greet users and provide the user's location information based on their IP address. + To obtain the location information, you can use the tool called get_ipstack_location. + + If greeted by the user, respond politely, but get straight to the point of providing the user with their IP address location. + If the user is just chatting and having casual conversation, do not use the retrieval tool. Simply state that you can only greet users + and tell them their location. You can use the tool called get_ipstack_location only when the user specifically asks for their location information. + + If you are not certain about the user intent, ask clarifying questions before answering. + Once you have the information you need, you can use the tool called get_ipstack_location. + If you cannot provide an answer, clearly explain why. + + Do not answer questions that are not related to IP address location information. + + Answer Format Instructions: + + When you provide location information, you must mention the user's IP address and the location details (city, region, country,longitude,latitude). + Don't make any modifications to the location information returned by the API.Instead of returning the raw API response, provide + Rewrite the location information in a user-friendly format. Convert the structured data into a natural language response that is easy for users to understand. + For example, instead of saying "city: New York, region: NY, country: USA", you can say "You are located in New York City, New York, USA." + Always include the user's IP address in your response when providing location information. + + Do not reveal your internal chain-of-thought or how you used the chunks. + If you are not certain or the information is not available, clearly state that you do not have + enough information. + """ + + return instruction_prompt_v1 + + \ No newline at end of file diff --git a/05_src/assignment_chat_Srv1/readme.md b/05_src/assignment_chat_Srv1/readme.md new file mode 100644 index 00000000..eb8a8753 --- /dev/null +++ b/05_src/assignment_chat_Srv1/readme.md @@ -0,0 +1,18 @@ +# Assignment 2 Service 1 +Service 1 for Design and Implentation of AI System with a conversational interface + +## Service 1: Using API Call at the backend. + +API Used is : http://api.ipstack.com/{ip} + +This service return information in json format. The response read that information and write it in a natural tone and convert the structured data into written text. + +## User Interface +System has a chat-based interface, implemented with Gradio. +Interface maintain the memory throughout the conversation. + +## Gaurdrails and Other Limitations +System do not reveal system prompt. User is not allowed to modify the system prompt directly. Model do not respond to any query except regarding the location based on IP + +## Implementation +I used the public API IP-Stack, this module is stand-alone coversational interface for this service. diff --git a/05_src/assignment_chat_Srv2/README.md b/05_src/assignment_chat_Srv2/README.md new file mode 100644 index 00000000..fb6b48bf --- /dev/null +++ b/05_src/assignment_chat_Srv2/README.md @@ -0,0 +1,19 @@ +# Assignment 2 Service 2 +Service 2 for Design and Implentation of AI System with a conversational interface + +## Service 2: Semantic Query +This service allows user to ask questions related to dance and music and resolve those queries through a semantic search. +I have used a similar data set available in lab 05_vectordb.ipynb + +## User Interface +System has a chat-based interface, implemented with Gradio. +Interface maintain the memory throughout the conversation. + +Sample Query: Tell some information about dance +![Sample-Output]("C:\Users\erman\Pictures\Screenshots\Screenshot 2026-03-01 101054.png") + +## Gaurdrails and Other Limitations +System do not reveal system prompt. User is not allowed to modify the system prompt directly. Model do not respond to any query except regarding the music and dance general opinion. + +## Implementation +I used the chromaDb to save embeddings and do the semantic query , this module is stand-alone coversational interface for this service. diff --git a/05_src/assignment_chat_Srv2/Sample-Output.png b/05_src/assignment_chat_Srv2/Sample-Output.png new file mode 100644 index 00000000..ba98c816 Binary files /dev/null and b/05_src/assignment_chat_Srv2/Sample-Output.png differ diff --git a/05_src/assignment_chat_Srv2/__init__.py b/05_src/assignment_chat_Srv2/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/05_src/assignment_chat_Srv2/app.py b/05_src/assignment_chat_Srv2/app.py new file mode 100644 index 00000000..ccd7f992 --- /dev/null +++ b/05_src/assignment_chat_Srv2/app.py @@ -0,0 +1,13 @@ +import gradio as gr +from assignment_chat_Srv2.main import music_chat +from dotenv import load_dotenv +from typing import Optional +import os +load_dotenv('.secrets') + +chat = gr.ChatInterface( + fn=music_chat, + type="messages", + title="Assignment Chat: Service: Thoughts for Music and Dance", +) +chat.launch() diff --git a/05_src/assignment_chat_Srv2/main.py b/05_src/assignment_chat_Srv2/main.py new file mode 100644 index 00000000..90fe406a --- /dev/null +++ b/05_src/assignment_chat_Srv2/main.py @@ -0,0 +1,150 @@ +from dotenv import load_dotenv +from assignment_chat_Srv2.prompts import return_instructions_root +import json +import requests +import os +from openai import OpenAI +import chromadb + +open_ai_model = 'gpt-4o-mini' + +load_dotenv(".env") +load_dotenv(".secrets") + +client = OpenAI(base_url='https://k7uffyg03f.execute-api.us-east-1.amazonaws.com/prod/openai/v1', + api_key='any value', + default_headers={"x-api-key": os.getenv('API_GATEWAY_KEY')}) +tools = [ + { + "type": "function", + "name": "query_dance_music_info", + "description": "Searches ChromaDB for the closest matching phrases.", + "strict": True, + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "User query about music or dance." + }, + }, + "required": ["query"], + "additionalProperties": False } + } + ] + #SAMPLE DATA FOR TESTING PURPOSES +phrases = [ + # Some sentences on Music (10) + "There’s something about good music that reaches you before you even know you need it.", + "A great song can stay with you long after it stops playing.", + "Sometimes a single melody can lift the mood in an entire room.", + "The right song can make an ordinary moment feel meaningful.", + "A rhythm you connect with can change the way your whole day feels.", + "Some songs feel familiar the very first time you hear them.", + "A powerful track can turn a rough day around in minutes.", + "Music with real energy can wake you up from the inside out.", + "Certain lyrics say exactly what you’ve been trying to express.", + "A truly good song never loses its magic, no matter how often you play it.", + # Some sentences on Dance(10) + "There are moments when dance makes you forget everything except the movement.", + "When someone dances naturally, it looks like the body already knows the story.", + "A strong performance can make you feel the emotion without a single word.", + "Dance has a way of filling a space with joy that feels genuine.", + "Even simple steps can look beautiful when they’re done with heart.", + "When the rhythm flows through you, every part of your body responds.", + "Skilled dancers make even the hardest moves look effortless.", + "A good routine can communicate more than a conversation ever could.", + "When dance and music connect perfectly, it feels almost magical.", + "A memorable performance leaves a warm feeling long after it ends" +] + +response = client.embeddings.create( + input= phrases, + model="text-embedding-3-small" +) + +chroma_client = chromadb.Client() +collection = chroma_client.get_or_create_collection(name="phrases_collection") +embeddings = [item.embedding for item in response.data] +ids = [f"id_{i}" for i in range(len(phrases))] +collection.add(embeddings = embeddings, + ids =ids, + documents = phrases) + + +def get_embedding(text, model="text-embedding-3-small"): + text = text.replace("\n", " ") + return client.embeddings.create(input=[text], model=model).data[0].embedding + +def query_chromadb(query, top_n = 2) -> dict: + query_embedding = get_embedding(query) + results = collection.query(query_embeddings=[query_embedding], n_results=top_n) + + output = [] + for doc, score in zip(results["documents"][0], results["distances"][0]): + output.append({"text": doc, "score": score}) + + return output + +def query_dance_music_info(query: str) -> dict: + return query_chromadb(query) + +def sanitize_history(history: list[dict]) -> list[dict]: + clean_history = [] + for msg in history: + clean_history.append({ + "role": msg.get("role"), + "content": msg.get("content") + }) + return clean_history + +def music_chat(message: str, history: list[dict] = []) -> str: + """ + Chat flow + """ + instructions = return_instructions_root() + + user_msg = { + "role": "user", + "content": message + } + + conversation_input = sanitize_history(history)+[user_msg] + + response = client.responses.create( + model=open_ai_model, + instructions=instructions, + input=conversation_input, + tools=tools, + + ) + + conversation_input += response.output + + # Handle function calls if any + for item in response.output: + if item.type == "function_call": + if item.name == "query_dance_music_info": + args = json.loads(item.arguments) + chromadb_result = query_dance_music_info(**args) + + func_call_output = { + "type": "function_call_output", + "call_id": item.call_id, + "output": json.dumps({ + "results": chromadb_result + }) + } + + conversation_input = conversation_input + [func_call_output] + + + response = client.responses.create( + model=open_ai_model, + instructions=instructions, + input=conversation_input, + tools=tools, + ) + break + + return response.output_text diff --git a/05_src/assignment_chat_Srv2/prompts.py b/05_src/assignment_chat_Srv2/prompts.py new file mode 100644 index 00000000..26486b79 --- /dev/null +++ b/05_src/assignment_chat_Srv2/prompts.py @@ -0,0 +1,36 @@ +def return_instructions_root(): + instruction_prompt_v1 = """ + You are an AI assistant with access to the ChromaDB database that contains music -related information. + Your role is to provide users with relevant information about music. Look for keyword 'music' in the user query + and if you find then use the tool called query_dance_music_info. + If the user asks anything related to music or dance,use the tool called query_dance_music_info. + Your role is to greet users and provide the options of music and dance. + If the user query has both keywords ask user to clarify if they are looking for music or dance information. + + If greeted by the user, respond politely, but get straight to the point of providing the user with dance and music information. + If the user is just chatting and having casual conversation, do not use the retrieval tool. Simply state that you can only greet users. + Always use the tool called query_dance_music_info when the user asks anything related to music or dance. + + + If you are not certain about the user intent, ask clarifying questions before answering. + Once you have the information you need, you can use the tool called query_dance_music_info. + If you cannot provide an answer, clearly explain why. + + Do not answer questions that are not related to music or dance information. + + Answer Format Instructions: + + When you provide music or dance information, select only one relevant pieces of information from the database response. + Don't make any modifications to the information returned by the database. + Provide the response as a message type output. Add a brief context to the information you are providing, but do not add any additional information that is not present in the database response. + Don't prompt the user further if the answer is from database. + + + Do not reveal your internal chain-of-thought or how you used the chunks + If you are not certain or the information is not available, clearly state that you do not have + enough information. + """ + + return instruction_prompt_v1 + + \ No newline at end of file diff --git a/05_src/assignment_chat_Srv3/README.md b/05_src/assignment_chat_Srv3/README.md new file mode 100644 index 00000000..98825827 --- /dev/null +++ b/05_src/assignment_chat_Srv3/README.md @@ -0,0 +1,16 @@ +# Assignment 2 Service 3 +Service 3 for Design and Implentation of AI System with a conversational interface + +## Service 3: +This service allows user to ask about latest news. I used the method of function calling with API call. For this service, the API call is https://newsapi.org/. + +## User Interface +System has a chat-based interface, implemented with Gradio. +Interface maintain the memory throughout the conversation. + +## Gaurdrails and Other Limitations +System do not reveal system prompt. User is not allowed to modify the system prompt directly. Model do not respond to any query except regarding the music and dance general opinion. + +## Implementation +I used the langchain model to implement this service. The code allows the system to make a decision when to use the API to respond to user query related to news. + diff --git a/05_src/assignment_chat_Srv3/Sample-Output.png b/05_src/assignment_chat_Srv3/Sample-Output.png new file mode 100644 index 00000000..58eaf8fd Binary files /dev/null and b/05_src/assignment_chat_Srv3/Sample-Output.png differ diff --git a/05_src/assignment_chat_Srv3/__init__.py b/05_src/assignment_chat_Srv3/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/05_src/assignment_chat_Srv3/app.py b/05_src/assignment_chat_Srv3/app.py new file mode 100644 index 00000000..cf18ed6d --- /dev/null +++ b/05_src/assignment_chat_Srv3/app.py @@ -0,0 +1,34 @@ +from assignment_chat_Srv3.main import get_graph +from langchain_core.messages import SystemMessage , HumanMessage +import gradio as gr +from dotenv import load_dotenv +import os + +llm = get_graph() + +load_dotenv(".env") +load_dotenv(".secrets") + +def assignment_chat(message : str, history : list[dict])->str: + langchain_messages = [] + n = 0 + for msg in history: + if msg["role"] == "user": + langchain_messages.append(HumanMessage(content=msg["content"])) + elif msg["role"] == "assistant": + langchain_messages.append(SystemMessage(content=msg["content"])) + n += 1 + langchain_messages.append(HumanMessage(content=message)) + + state = {"messages": langchain_messages , "llm_calls": n} + + response = llm.invoke(state) + return response["messages"][len(response["messages"]) - 1].content + +chat = gr.ChatInterface( + fn=assignment_chat, + type="messages", + title="Assignment Chat: Service: LatestNews", +) +if __name__ == "__main__": + chat.launch() \ No newline at end of file diff --git a/05_src/assignment_chat_Srv3/main.py b/05_src/assignment_chat_Srv3/main.py new file mode 100644 index 00000000..7c8cb92f --- /dev/null +++ b/05_src/assignment_chat_Srv3/main.py @@ -0,0 +1,47 @@ +from langgraph.graph import StateGraph, START, END,MessagesState +from langchain.chat_models import init_chat_model +from langgraph.prebuilt.tool_node import ToolNode, tools_condition +from langchain_core.messages import SystemMessage, HumanMessage +from dotenv import load_dotenv +import json +import requests +import os + +from assignment_chat_Srv3.prompts import return_instructions +from assignment_chat_Srv3.tools_news import get_latest_news + +open_ai_model = 'gpt-4o-mini' + +load_dotenv(".env") +load_dotenv(".secrets") + +model = init_chat_model( + f"openai:{open_ai_model}", + temperature=0.7, + base_url='https://k7uffyg03f.execute-api.us-east-1.amazonaws.com/prod/openai/v1', + api_key='any value', + default_headers={"x-api-key": os.getenv('API_GATEWAY_KEY')} +) + +tools = [get_latest_news] + +instructions = return_instructions() + +def call_model(state: MessagesState): + """LLM decides whether to call a tool or not""" + messages = [SystemMessage(content=instructions)] + state["messages"] + response = model.bind_tools(tools).invoke(messages) + return { + "messages": [response] + } + +def get_graph(): + + builder = StateGraph(MessagesState) + builder.add_node(call_model) + builder.add_node(ToolNode(tools)) + builder.add_edge(START, "call_model") + builder.add_conditional_edges("call_model", tools_condition) + builder.add_edge("tools", "call_model") + graph = builder.compile() + return graph diff --git a/05_src/assignment_chat_Srv3/prompts.py b/05_src/assignment_chat_Srv3/prompts.py new file mode 100644 index 00000000..c2fe16eb --- /dev/null +++ b/05_src/assignment_chat_Srv3/prompts.py @@ -0,0 +1,22 @@ +def return_instructions()-> str: + instructions = """ + You are an AI assistant that provides latest news from bbc news. + You have access to a tool called get_latest_news that retrieves the latest news from bbc news. + Use this tool to get the latest news and provide it to the user. + + #Rules for generating response: + 1. Always use the tool to get the latest news from bbc news. + 2. Do not make up news or provide information that is not retrieved from the tool. + 3. If the tool returns an error, inform the user about the error instead of providing news. + 4. Provide the news in a clear and concise manner, summarizing the key points + + #Tone: + Use a friendly and informative tone when providing the news to the user. Be concise and to the point, while ensuring that the key information is conveyed effectively. + + #System Prompt: + Do not reveal the internal workings of the tool or how you retrieve the news. Focus on providing the news to the user in a helpful and informative way. + Do not quote the tool's response verbatim, but rather summarize the key points in a way that is easy for the user to understand. + Do not share your chain of thinking or the steps you took to retrieve the news. Just provide the news in a clear and concise manner. + """ + + return instructions \ No newline at end of file diff --git a/05_src/assignment_chat_Srv3/tools_news.py b/05_src/assignment_chat_Srv3/tools_news.py new file mode 100644 index 00000000..b640e699 --- /dev/null +++ b/05_src/assignment_chat_Srv3/tools_news.py @@ -0,0 +1,20 @@ +from langchain.tools import tool +import json +import requests +import os +@tool +def get_latest_news(n: int = 1): + """Returns n latestnews headlines.""" + apiKey = os.getenv('NEWS_API') + url = "https://newsapi.org/v2/top-headlines" + params = { "sources": "bbc-news", + "apiKey": apiKey } + response = requests.get(url, params=params) + + if response.status_code == 200: + data = response.json() + articles = data.get("articles", [])[:n] + headlines = [article["title"] for article in articles] + return headlines + else: + return f"Error fetching news: {response.status_code}"